1 /*
2 * Copyright (c) 2000-2022 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
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.
47 *
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
58 * SUCH DAMAGE.
59 *
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 $
62 */
63 /*
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,
67 * Version 2.0.
68 */
69
70 #include "tcp_includes.h"
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/kernel.h>
75 #include <sys/sysctl.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/proc.h> /* for proc0 declaration */
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/syslog.h>
83 #include <sys/mcache.h>
84 #include <sys/kauth.h>
85 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
86
87 #include <machine/endian.h>
88
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/route.h>
92 #include <net/ntstat.h>
93 #include <net/content_filter.h>
94 #include <net/dlil.h>
95 #include <net/multi_layer_pkt_log.h>
96 #include <net/droptap.h>
97
98 #include <netinet/in.h>
99 #include <netinet/in_systm.h>
100 #include <netinet/ip.h>
101 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
102 #include <netinet/in_var.h>
103 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
104 #include <netinet/in_pcb.h>
105 #include <netinet/ip_var.h>
106 #include <mach/sdt.h>
107 #include <netinet/ip6.h>
108 #include <netinet/icmp6.h>
109 #include <netinet6/nd6.h>
110 #include <netinet6/ip6_var.h>
111 #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>
121 #include <netinet6/tcp6_var.h>
122 #include <netinet/tcpip.h>
123 #include <netinet/tcp_log.h>
124
125 #if IPSEC
126 #include <netinet6/ipsec.h>
127 #include <netinet6/ipsec6.h>
128 #include <netkey/key.h>
129 #endif /*IPSEC*/
130
131 #include <sys/kdebug.h>
132 #if MPTCP
133 #include <netinet/mptcp_var.h>
134 #include <netinet/mptcp.h>
135 #include <netinet/mptcp_opt.h>
136 #endif /* MPTCP */
137
138 #include <corecrypto/ccaes.h>
139 #include <net/sockaddr_utils.h>
140
141 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
142 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
143 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
144 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
145
146 #define TCP_RTT_HISTORY_EXPIRE_TIME (60 * TCP_RETRANSHZ)
147 #define TCP_RECV_THROTTLE_WIN (5 * TCP_RETRANSHZ)
148 #define TCP_STRETCHACK_ENABLE_PKTCNT 2000
149
150 struct tcpstat tcpstat;
151
152 SYSCTL_SKMEM_TCP_INT(OID_AUTO, flow_control_response,
153 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_flow_control_response, 1,
154 "Improved response to Flow-control events");
155
156 static int log_in_vain = 0;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain,
158 CTLFLAG_RW | CTLFLAG_LOCKED, &log_in_vain, 0,
159 "Log all incoming TCP connections");
160
161 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ack_strategy,
162 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ack_strategy, TCP_ACK_STRATEGY_MODERN,
163 "Revised TCP ACK-strategy, avoiding stretch-ACK implementation");
164
165 static int blackhole = 0;
166 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole,
167 CTLFLAG_RW | CTLFLAG_LOCKED, &blackhole, 0,
168 "Do not send RST when dropping refused connections");
169
170 /* TODO - remove once uTCP stopped using it */
171 SYSCTL_SKMEM_TCP_INT(OID_AUTO, aggressive_rcvwnd_inc,
172 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_aggressive_rcvwnd_inc, 1,
173 "Be more aggressive about increasing the receive-window.");
174
175 SYSCTL_SKMEM_TCP_INT(OID_AUTO, delayed_ack,
176 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_delack_enabled, 3,
177 "Delay ACK to try and piggyback it onto a data packet");
178
179 SYSCTL_SKMEM_TCP_INT(OID_AUTO, recvbg, CTLFLAG_RW | CTLFLAG_LOCKED,
180 int, tcp_recv_bg, 0, "Receive background");
181
182 SYSCTL_SKMEM_TCP_INT(OID_AUTO, drop_synfin,
183 CTLFLAG_RW | CTLFLAG_LOCKED, static int, drop_synfin, 1,
184 "Drop TCP packets with SYN+FIN set");
185
186 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW | CTLFLAG_LOCKED, 0,
187 "TCP Segment Reassembly Queue");
188
189 static int tcp_reass_overflows = 0;
190 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows,
191 CTLFLAG_RD | CTLFLAG_LOCKED, &tcp_reass_overflows, 0,
192 "Global number of TCP segment reassembly queue overflows");
193
194 int tcp_reass_total_qlen = 0;
195 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, qlen,
196 CTLFLAG_RD | CTLFLAG_LOCKED, &tcp_reass_total_qlen, 0,
197 "Total number of TCP segments in reassembly queues");
198
199
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");
203
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");
207
208 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rfc3465, CTLFLAG_RW | CTLFLAG_LOCKED,
209 int, tcp_do_rfc3465, 1, "");
210
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");
214
215 int rtt_samples_per_slot = 20;
216
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
223 SYSCTL_SKMEM_TCP_INT(OID_AUTO, doautorcvbuf,
224 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_do_autorcvbuf, 1,
225 "Enable automatic socket buffer tuning");
226
227 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autotunereorder,
228 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_autotune_reorder, 1,
229 "Enable automatic socket buffer tuning even when reordering is present");
230
231 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autorcvbufmax,
232 CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, u_int32_t, tcp_autorcvbuf_max, 2 * 1024 * 1024,
233 "Maximum receive socket buffer size");
234
235 int tcp_disable_access_to_stats = 1;
236 SYSCTL_INT(_net_inet_tcp, OID_AUTO, disable_access_to_stats,
237 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_disable_access_to_stats, 0,
238 "Disable access to tcpstat");
239
240 SYSCTL_SKMEM_TCP_INT(OID_AUTO, challengeack_limit,
241 CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_challengeack_limit, 10,
242 "Maximum number of challenge ACKs per connection per second");
243
244 /* TO BE REMOVED */
245 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_rfc5961,
246 CTLFLAG_RW | CTLFLAG_LOCKED, static int, tcp_do_rfc5961, 1,
247 "Enable/Disable full RFC 5961 compliance");
248
249 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_better_lr,
250 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_better_lr, 1,
251 "Improved TCP Loss Recovery");
252
253 SYSCTL_SKMEM_TCP_INT(OID_AUTO, use_min_curr_rtt,
254 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_use_min_curr_rtt, 1,
255 "Use a min of k=4 RTT samples for congestion controllers");
256
257 SYSCTL_SKMEM_TCP_INT(OID_AUTO, awdl_rtobase,
258 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_awdl_rtobase, 100,
259 "Initial RTO for AWDL interface");
260
261 extern int tcp_acc_iaj_high;
262 extern int tcp_acc_iaj_react_limit;
263 extern int tcp_fin_timeout;
264
265 uint8_t tcprexmtthresh = 3;
266
267 uint32_t tcp_now;
268 struct timeval tcp_uptime; /* uptime when tcp_now was last updated */
269
270 /* Used to sychronize updates to tcp_now */
271 static LCK_GRP_DECLARE(tcp_uptime_mtx_grp, "tcpuptime");
272 LCK_SPIN_DECLARE(tcp_uptime_lock, &tcp_uptime_mtx_grp);
273
274 struct inpcbhead tcb;
275 #define tcb6 tcb /* for KAME src sync over BSD*'s */
276 struct inpcbinfo tcbinfo;
277
278 static void tcp_dooptions(struct tcpcb *, u_char *, int, struct tcphdr *,
279 struct tcpopt *);
280 static void tcp_finalize_options(struct tcpcb *, struct tcpopt *, unsigned int);
281 static void tcp_pulloutofband(struct socket *,
282 struct tcphdr *, struct mbuf *, int);
283 static void tcp_xmit_timer(struct tcpcb *, int, u_int32_t, tcp_seq);
284 static inline unsigned int tcp_maxmtu(struct rtentry *);
285 static inline int tcp_stretch_ack_enable(struct tcpcb *tp, int thflags);
286 static inline void tcp_adaptive_rwtimo_check(struct tcpcb *, int);
287
288 #if TRAFFIC_MGT
289 static inline void compute_iaj(struct tcpcb *tp);
290 static inline void compute_iaj_meat(struct tcpcb *tp, uint32_t cur_iaj);
291 #endif /* TRAFFIC_MGT */
292
293 static inline unsigned int tcp_maxmtu6(struct rtentry *);
294 unsigned int get_maxmtu(struct rtentry *);
295
296 static void tcp_sbrcv_grow(struct tcpcb *tp, struct sockbuf *sb,
297 struct tcpopt *to, uint32_t tlen);
298 void tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sb);
299 static void tcp_sbsnd_trim(struct sockbuf *sbsnd);
300 static inline void tcp_sbrcv_tstmp_check(struct tcpcb *tp);
301 static inline void tcp_sbrcv_reserve(struct tcpcb *tp, struct sockbuf *sb,
302 u_int32_t newsize, u_int32_t idealsize, u_int32_t rcvbuf_max);
303 static void tcp_bad_rexmt_restore_state(struct tcpcb *tp, struct tcphdr *th);
304 static void tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to,
305 struct tcphdr *th);
306 static void tcp_compute_rcv_rtt(struct tcpcb *tp, struct tcpopt *to,
307 struct tcphdr *th);
308 static void tcp_early_rexmt_check(struct tcpcb *tp, struct tcphdr *th);
309 static void tcp_bad_rexmt_check(struct tcpcb *tp, struct tcphdr *th,
310 struct tcpopt *to);
311 /*
312 * Constants used for resizing receive socket buffer
313 * when timestamps are not supported
314 */
315 #define TCPTV_RCVNOTS_QUANTUM 100
316 #define TCP_RCVNOTS_BYTELEVEL 204800
317
318 /*
319 * Constants used for limiting early retransmits
320 * to 10 per minute.
321 */
322 #define TCP_EARLY_REXMT_WIN (60 * TCP_RETRANSHZ) /* 60 seconds */
323 #define TCP_EARLY_REXMT_LIMIT 10
324
325 #define log_in_vain_log( a ) { log a; }
326
327 int tcp_rcvunackwin = TCPTV_UNACKWIN;
328 int tcp_maxrcvidle = TCPTV_MAXRCVIDLE;
329 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rcvsspktcnt, CTLFLAG_RW | CTLFLAG_LOCKED,
330 int, tcp_rcvsspktcnt, TCP_RCV_SS_PKTCOUNT, "packets to be seen before receiver stretches acks");
331
332 #define DELAY_ACK(tp, th) \
333 (CC_ALGO(tp)->delay_ack != NULL && CC_ALGO(tp)->delay_ack(tp, th))
334
335 static int tcp_dropdropablreq(struct socket *head);
336 static void tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th);
337 static void update_base_rtt(struct tcpcb *tp, uint32_t rtt);
338 void tcp_set_background_cc(struct socket *so);
339 void tcp_set_foreground_cc(struct socket *so);
340 static void tcp_set_new_cc(struct socket *so, uint8_t cc_index);
341 static void tcp_bwmeas_check(struct tcpcb *tp);
342
343 #if TRAFFIC_MGT
344 void
reset_acc_iaj(struct tcpcb * tp)345 reset_acc_iaj(struct tcpcb *tp)
346 {
347 tp->acc_iaj = 0;
348 CLEAR_IAJ_STATE(tp);
349 }
350
351 static inline void
update_iaj_state(struct tcpcb * tp,int size,int rst_size)352 update_iaj_state(struct tcpcb *tp, int size, int rst_size)
353 {
354 if (rst_size > 0) {
355 tp->iaj_size = 0;
356 }
357 if (tp->iaj_size == 0 || size >= tp->iaj_size) {
358 tp->iaj_size = size;
359 tp->iaj_rcv_ts = tcp_now;
360 tp->iaj_small_pkt = 0;
361 }
362 }
363
364 /* For every 64-bit unsigned integer(v), this function will find the
365 * largest 32-bit integer n such that (n*n <= v). This takes at most 32 iterations
366 * irrespective of the value of v and does not involve multiplications.
367 */
368 static inline uint32_t
isqrt(uint64_t val)369 isqrt(uint64_t val)
370 {
371 uint32_t sqrt_cache[11] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100};
372 uint64_t temp, g = 0, b = 1 << 31, bshft = 31;
373 if (val <= 100) {
374 for (g = 0; g <= 10; ++g) {
375 if (sqrt_cache[g] > val) {
376 g--;
377 break;
378 } else if (sqrt_cache[g] == val) {
379 break;
380 }
381 }
382 } else {
383 do {
384 temp = (((g << 1) + b) << (bshft--));
385 if (val >= temp) {
386 g += b;
387 val -= temp;
388 }
389 b >>= 1;
390 } while (b > 0 && val > 0);
391 }
392 return (uint32_t)g;
393 }
394
395 static inline void
compute_iaj_meat(struct tcpcb * tp,uint32_t cur_iaj)396 compute_iaj_meat(struct tcpcb *tp, uint32_t cur_iaj)
397 {
398 /* When accumulated IAJ reaches MAX_ACC_IAJ in milliseconds,
399 * throttle the receive window to a minimum of MIN_IAJ_WIN packets
400 */
401 #define MAX_ACC_IAJ (tcp_acc_iaj_high_thresh + tcp_acc_iaj_react_limit)
402 #define IAJ_DIV_SHIFT 4
403 #define IAJ_ROUNDUP_CONST (1 << (IAJ_DIV_SHIFT - 1))
404
405 uint32_t allowed_iaj, acc_iaj = 0;
406
407 /* Using 64-bit storage for the inter-arrival jitter deviation,
408 * to avoid accidentally rolling over if the inter-arrival time exceeds 62 seconds.
409 */
410 int64_t mean, temp, cur_iaj_dev;
411
412 cur_iaj_dev = (cur_iaj - tp->avg_iaj);
413
414 /* Allow a jitter of "allowed_iaj" milliseconds. Some connections
415 * may have a constant jitter more than that. We detect this by
416 * using standard deviation.
417 */
418 allowed_iaj = tp->avg_iaj + tp->std_dev_iaj;
419 if (allowed_iaj < tcp_allowed_iaj) {
420 allowed_iaj = tcp_allowed_iaj;
421 }
422
423 /* Initially when the connection starts, the senders congestion
424 * window is small. During this period we avoid throttling a
425 * connection because we do not have a good starting point for
426 * allowed_iaj. IAJ_IGNORE_PKTCNT is used to quietly gloss over
427 * the first few packets.
428 */
429 if (tp->iaj_pktcnt > IAJ_IGNORE_PKTCNT) {
430 if (cur_iaj <= allowed_iaj) {
431 if (tp->acc_iaj >= 2) {
432 acc_iaj = tp->acc_iaj - 2;
433 } else {
434 acc_iaj = 0;
435 }
436 } else {
437 acc_iaj = tp->acc_iaj + (cur_iaj - allowed_iaj);
438 }
439
440 if (acc_iaj > MAX_ACC_IAJ) {
441 acc_iaj = MAX_ACC_IAJ;
442 }
443 tp->acc_iaj = acc_iaj;
444 }
445
446 /* Compute weighted average where the history has a weight of
447 * 15 out of 16 and the current value has a weight of 1 out of 16.
448 * This will make the short-term measurements have more weight.
449 *
450 * The addition of 8 will help to round-up the value
451 * instead of round-down
452 */
453 tp->avg_iaj = (((tp->avg_iaj << IAJ_DIV_SHIFT) - tp->avg_iaj)
454 + cur_iaj + IAJ_ROUNDUP_CONST) >> IAJ_DIV_SHIFT;
455
456 /* Compute Root-mean-square of deviation where mean is a weighted
457 * average as described above.
458 */
459 temp = tp->std_dev_iaj * tp->std_dev_iaj;
460 mean = (((temp << IAJ_DIV_SHIFT) - temp)
461 + (cur_iaj_dev * cur_iaj_dev)
462 + IAJ_ROUNDUP_CONST) >> IAJ_DIV_SHIFT;
463
464 tp->std_dev_iaj = isqrt(mean);
465
466 DTRACE_TCP3(iaj, struct tcpcb *, tp, uint32_t, cur_iaj,
467 uint32_t, allowed_iaj);
468
469 return;
470 }
471
472 static inline void
compute_iaj(struct tcpcb * tp)473 compute_iaj(struct tcpcb *tp)
474 {
475 compute_iaj_meat(tp, (tcp_now - tp->iaj_rcv_ts));
476 }
477 #endif /* TRAFFIC_MGT */
478
479 /*
480 * Perform rate limit check per connection per second
481 * tp->t_challengeack_last is the last_time diff was greater than 1sec
482 * tp->t_challengeack_count is the number of ACKs sent (within 1sec)
483 * Return TRUE if we shouldn't send the ACK due to rate limitation
484 * Return FALSE if it is still ok to send challenge ACK
485 */
486 static boolean_t
tcp_is_ack_ratelimited(struct tcpcb * tp)487 tcp_is_ack_ratelimited(struct tcpcb *tp)
488 {
489 boolean_t ret = TRUE;
490 uint32_t now = tcp_now;
491 int32_t diff = 0;
492
493 diff = timer_diff(now, 0, tp->t_challengeack_last, 0);
494 /* If it is first time or diff > 1000ms,
495 * update the challengeack_last and reset the
496 * current count of ACKs
497 */
498 if (tp->t_challengeack_last == 0 || diff >= 1000) {
499 tp->t_challengeack_last = now;
500 tp->t_challengeack_count = 0;
501 ret = FALSE;
502 } else if (tp->t_challengeack_count < tcp_challengeack_limit) {
503 ret = FALSE;
504 }
505
506 /* Careful about wrap-around */
507 if (ret == FALSE && (tp->t_challengeack_count + 1 > 0)) {
508 tp->t_challengeack_count++;
509 }
510
511 return ret;
512 }
513
514 /* Check if enough amount of data has been acknowledged since
515 * bw measurement was started
516 */
517 static void
tcp_bwmeas_check(struct tcpcb * tp)518 tcp_bwmeas_check(struct tcpcb *tp)
519 {
520 int32_t bw_meas_bytes;
521 uint32_t bw, bytes, elapsed_time;
522
523 if (SEQ_LEQ(tp->snd_una, tp->t_bwmeas->bw_start)) {
524 return;
525 }
526
527 bw_meas_bytes = tp->snd_una - tp->t_bwmeas->bw_start;
528 if ((tp->t_flagsext & TF_BWMEAS_INPROGRESS) &&
529 bw_meas_bytes >= (int32_t)(tp->t_bwmeas->bw_size)) {
530 bytes = bw_meas_bytes;
531 elapsed_time = tcp_now - tp->t_bwmeas->bw_ts;
532 if (elapsed_time > 0) {
533 bw = bytes / elapsed_time;
534 if (bw > 0) {
535 if (tp->t_bwmeas->bw_sndbw > 0) {
536 tp->t_bwmeas->bw_sndbw =
537 (((tp->t_bwmeas->bw_sndbw << 3)
538 - tp->t_bwmeas->bw_sndbw)
539 + bw) >> 3;
540 } else {
541 tp->t_bwmeas->bw_sndbw = bw;
542 }
543
544 /* Store the maximum value */
545 if (tp->t_bwmeas->bw_sndbw_max == 0) {
546 tp->t_bwmeas->bw_sndbw_max =
547 tp->t_bwmeas->bw_sndbw;
548 } else {
549 tp->t_bwmeas->bw_sndbw_max =
550 max(tp->t_bwmeas->bw_sndbw,
551 tp->t_bwmeas->bw_sndbw_max);
552 }
553 }
554 }
555 tp->t_flagsext &= ~(TF_BWMEAS_INPROGRESS);
556 }
557 }
558
559 static int
tcp_reass(struct tcpcb * tp,struct tcphdr * th,int * tlenp,struct mbuf * m,struct ifnet * ifp,int * dowakeup)560 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m,
561 struct ifnet *ifp, int *dowakeup)
562 {
563 struct tseg_qent *q;
564 struct tseg_qent *p = NULL;
565 struct tseg_qent *nq;
566 struct tseg_qent *te = NULL;
567 struct inpcb *inp = tp->t_inpcb;
568 struct socket *so = inp->inp_socket;
569 int flags = 0;
570 uint32_t qlimit;
571 stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
572 boolean_t dsack_set = FALSE;
573
574 /*
575 * If the reassembly queue already has entries or if we are going
576 * to add a new one, then the connection has reached a loss state.
577 * Reset the stretch-ack algorithm at this point.
578 */
579 tcp_reset_stretch_ack(tp);
580 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
581
582 #if TRAFFIC_MGT
583 if (tp->acc_iaj > 0) {
584 reset_acc_iaj(tp);
585 }
586 #endif /* TRAFFIC_MGT */
587
588 if (th->th_seq != tp->rcv_nxt) {
589 struct mbuf *tmp = m;
590 while (tmp != NULL) {
591 if (mbuf_class_under_pressure(tmp)) {
592 m_freem(m);
593 tcp_reass_overflows++;
594 tcpstat.tcps_rcvmemdrop++;
595 *tlenp = 0;
596 return 0;
597 }
598
599 tmp = tmp->m_next;
600 }
601 }
602
603 /*
604 * Limit the number of segments in the reassembly queue to prevent
605 * holding on to too many segments (and thus running out of mbufs).
606 * Make sure to let the missing segment through which caused this
607 * queue. Always keep one global queue entry spare to be able to
608 * process the missing segment.
609 */
610 qlimit = min(max(100, so->so_rcv.sb_hiwat >> 10),
611 (tcp_autorcvbuf_max >> 10));
612 if (th->th_seq != tp->rcv_nxt &&
613 (tp->t_reassqlen + 1) >= qlimit) {
614 tcp_reass_overflows++;
615 tcpstat.tcps_rcvmemdrop++;
616 m_freem(m);
617 *tlenp = 0;
618 return 0;
619 }
620
621 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
622 te = zalloc_flags(tcp_reass_zone, Z_WAITOK | Z_NOFAIL);
623 tp->t_reassqlen++;
624 OSIncrementAtomic(&tcp_reass_total_qlen);
625
626 /*
627 * Find a segment which begins after this one does.
628 */
629 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
630 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq)) {
631 break;
632 }
633 p = q;
634 }
635
636 /*
637 * If there is a preceding segment, it may provide some of
638 * our data already. If so, drop the data from the incoming
639 * segment. If it provides all of our data, drop us.
640 */
641 if (p != NULL) {
642 int i;
643 /* conversion to int (in i) handles seq wraparound */
644 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
645 if (i > 0) {
646 if (i > 1) {
647 /*
648 * Note duplicate data sequnce numbers
649 * to report in DSACK option
650 */
651 tp->t_dsack_lseq = th->th_seq;
652 tp->t_dsack_rseq = th->th_seq +
653 min(i, *tlenp);
654
655 /*
656 * Report only the first part of partial/
657 * non-contiguous duplicate sequence space
658 */
659 dsack_set = TRUE;
660 }
661 if (i >= *tlenp) {
662 tcpstat.tcps_rcvduppack++;
663 tcpstat.tcps_rcvdupbyte += *tlenp;
664 if (nstat_collect) {
665 nstat_route_rx(inp->inp_route.ro_rt,
666 1, *tlenp,
667 NSTAT_RX_FLAG_DUPLICATE);
668 INP_ADD_STAT(inp, ifnet_count_type,
669 rxpackets, 1);
670 INP_ADD_STAT(inp, ifnet_count_type,
671 rxbytes, *tlenp);
672 tp->t_stat.rxduplicatebytes += *tlenp;
673 inp_set_activity_bitmap(inp);
674 }
675 m_freem(m);
676 zfree(tcp_reass_zone, te);
677 te = NULL;
678 tp->t_reassqlen--;
679 OSDecrementAtomic(&tcp_reass_total_qlen);
680 /*
681 * Try to present any queued data
682 * at the left window edge to the user.
683 * This is needed after the 3-WHS
684 * completes.
685 */
686 goto present;
687 }
688 m_adj(m, i);
689 *tlenp -= i;
690 th->th_seq += i;
691 }
692 }
693
694 if (th->th_seq != tp->rcv_nxt) {
695 tp->t_rcvoopack++;
696 tcpstat.tcps_rcvoopack++;
697 tcpstat.tcps_rcvoobyte += *tlenp;
698 if (nstat_collect) {
699 tp->t_stat.rxoutoforderbytes += *tlenp;
700 }
701 }
702
703 if (nstat_collect) {
704 nstat_route_rx(inp->inp_route.ro_rt, 1, *tlenp,
705 NSTAT_RX_FLAG_OUT_OF_ORDER);
706 INP_ADD_STAT(inp, ifnet_count_type, rxpackets, 1);
707 INP_ADD_STAT(inp, ifnet_count_type, rxbytes, *tlenp);
708 inp_set_activity_bitmap(inp);
709 }
710
711 /*
712 * While we overlap succeeding segments trim them or,
713 * if they are completely covered, dequeue them.
714 */
715 while (q) {
716 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
717 if (i <= 0) {
718 break;
719 }
720
721 /*
722 * Report only the first part of partial/non-contiguous
723 * duplicate segment in dsack option. The variable
724 * dsack_set will be true if a previous entry has some of
725 * the duplicate sequence space.
726 */
727 if (i > 1 && !dsack_set) {
728 if (tp->t_dsack_lseq == 0) {
729 tp->t_dsack_lseq = q->tqe_th->th_seq;
730 tp->t_dsack_rseq =
731 tp->t_dsack_lseq + min(i, q->tqe_len);
732 } else {
733 /*
734 * this segment overlaps data in multple
735 * entries in the reassembly queue, move
736 * the right sequence number further.
737 */
738 tp->t_dsack_rseq =
739 tp->t_dsack_rseq + min(i, q->tqe_len);
740 }
741 }
742 if (i < q->tqe_len) {
743 q->tqe_th->th_seq += i;
744 q->tqe_len -= i;
745 m_adj(q->tqe_m, i);
746 break;
747 }
748
749 nq = LIST_NEXT(q, tqe_q);
750 LIST_REMOVE(q, tqe_q);
751 tp->t_reassq_mbcnt -= _MSIZE + (q->tqe_m->m_flags & M_EXT) ?
752 q->tqe_m->m_ext.ext_size : 0;
753 m_freem(q->tqe_m);
754 zfree(tcp_reass_zone, q);
755 tp->t_reassqlen--;
756 OSDecrementAtomic(&tcp_reass_total_qlen);
757 q = nq;
758 }
759
760 /* Insert the new segment queue entry into place. */
761 te->tqe_m = m;
762 te->tqe_th = th;
763 te->tqe_len = *tlenp;
764
765 tp->t_reassq_mbcnt += _MSIZE + (m->m_flags & M_EXT) ? m->m_ext.ext_size : 0;
766
767 if (p == NULL) {
768 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
769 } else {
770 LIST_INSERT_AFTER(p, te, tqe_q);
771 }
772
773 present:
774 /*
775 * Present data to user, advancing rcv_nxt through
776 * completed sequence space.
777 */
778 if (!TCPS_HAVEESTABLISHED(tp->t_state)) {
779 return 0;
780 }
781 q = LIST_FIRST(&tp->t_segq);
782 if (!q || q->tqe_th->th_seq != tp->rcv_nxt) {
783 return 0;
784 }
785
786 /*
787 * If there is already another thread doing reassembly for this
788 * connection, it is better to let it finish the job --
789 * (radar 16316196)
790 */
791 if (tp->t_flagsext & TF_REASS_INPROG) {
792 return 0;
793 }
794
795 tp->t_flagsext |= TF_REASS_INPROG;
796 /* lost packet was recovered, so ooo data can be returned */
797 tcpstat.tcps_recovered_pkts++;
798
799 do {
800 tp->rcv_nxt += q->tqe_len;
801 flags = q->tqe_th->th_flags & TH_FIN;
802 LIST_REMOVE(q, tqe_q);
803 tp->t_reassq_mbcnt -= _MSIZE + (q->tqe_m->m_flags & M_EXT) ?
804 q->tqe_m->m_ext.ext_size : 0;
805 if (so->so_state & SS_CANTRCVMORE) {
806 m_freem(q->tqe_m);
807 } else {
808 so_recv_data_stat(so, q->tqe_m, 0); /* XXXX */
809 if (q->tqe_th->th_flags & TH_PUSH) {
810 tp->t_flagsext |= TF_LAST_IS_PSH;
811 } else {
812 tp->t_flagsext &= ~TF_LAST_IS_PSH;
813 }
814
815 if (sbappendstream_rcvdemux(so, q->tqe_m)) {
816 *dowakeup = 1;
817 }
818 }
819 zfree(tcp_reass_zone, q);
820 tp->t_reassqlen--;
821 OSDecrementAtomic(&tcp_reass_total_qlen);
822 q = LIST_FIRST(&tp->t_segq);
823 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
824 tp->t_flagsext &= ~TF_REASS_INPROG;
825
826 if ((inp->inp_vflag & INP_IPV6) != 0) {
827 KERNEL_DEBUG(DBG_LAYER_BEG,
828 ((inp->inp_fport << 16) | inp->inp_lport),
829 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
830 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
831 0, 0, 0);
832 } else {
833 KERNEL_DEBUG(DBG_LAYER_BEG,
834 ((inp->inp_fport << 16) | inp->inp_lport),
835 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
836 (inp->inp_faddr.s_addr & 0xffff)),
837 0, 0, 0);
838 }
839
840 return flags;
841 }
842
843 /*
844 * Enter fast recovery and reduce congestion window,
845 * used when CE is seen or when a tail loss
846 * probe recovers the last packet. Also used by RACK.
847 */
848 void
tcp_enter_fast_recovery(struct tcpcb * tp)849 tcp_enter_fast_recovery(struct tcpcb *tp)
850 {
851 /*
852 * If the current tcp cc module has
853 * defined a hook for tasks to run
854 * before entering FR, call it
855 */
856 if (CC_ALGO(tp)->pre_fr != NULL) {
857 CC_ALGO(tp)->pre_fr(tp);
858 }
859 ENTER_FASTRECOVERY(tp);
860 if (tp->t_flags & TF_SENTFIN) {
861 tp->snd_recover = tp->snd_max - 1;
862 } else {
863 tp->snd_recover = tp->snd_max;
864 }
865
866 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
867
868 tp->t_timer[TCPT_REXMT] = 0;
869 tp->t_timer[TCPT_PTO] = 0;
870 tp->t_rtttime = 0;
871 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
872 tcp_cc_adjust_nonvalidated_cwnd(tp);
873 } else {
874 /* No need to inflate the congestion window */
875 tp->snd_cwnd = tp->snd_ssthresh;
876 }
877 }
878
879 /*
880 * This function is called upon reception of data on a socket. It's purpose is
881 * to handle the adaptive keepalive timers that monitor whether the connection
882 * is making progress. First the adaptive read-timer, second the TFO probe-timer.
883 *
884 * The application wants to get an event if there is a stall during read.
885 * Set the initial keepalive timeout to be equal to twice RTO.
886 *
887 * If the outgoing interface is in marginal conditions, we need to
888 * enable read probes for that too.
889 */
890 static inline void
tcp_adaptive_rwtimo_check(struct tcpcb * tp,int tlen)891 tcp_adaptive_rwtimo_check(struct tcpcb *tp, int tlen)
892 {
893 struct ifnet *outifp = tp->t_inpcb->inp_last_outifp;
894
895 if ((tp->t_adaptive_rtimo > 0 ||
896 (outifp != NULL &&
897 (outifp->if_eflags & IFEF_PROBE_CONNECTIVITY)))
898 && tlen > 0 &&
899 tp->t_state == TCPS_ESTABLISHED) {
900 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
901 (TCP_REXMTVAL(tp) << 1));
902 tp->t_flagsext |= TF_DETECT_READSTALL;
903 tp->t_rtimo_probes = 0;
904 }
905 }
906
907 inline void
tcp_keepalive_reset(struct tcpcb * tp)908 tcp_keepalive_reset(struct tcpcb *tp)
909 {
910 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
911 TCP_CONN_KEEPIDLE(tp));
912 tp->t_flagsext &= ~(TF_DETECT_READSTALL);
913 tp->t_rtimo_probes = 0;
914 }
915
916 void
tcp_set_finwait_timeout(struct tcpcb * tp)917 tcp_set_finwait_timeout(struct tcpcb *tp)
918 {
919 /*
920 * Starting the TCPT_2MSL timer is contrary to the
921 * specification, but if we don't get a FIN
922 * we'll hang forever.
923 */
924 ASSERT(tp->t_state == TCPS_FIN_WAIT_2);
925 ASSERT((tp->t_inpcb->inp_socket->so_state & (SS_CANTRCVMORE)) == SS_CANTRCVMORE);
926
927 if (tcp_fin_timeout > 0 &&
928 tcp_fin_timeout < TCP_CONN_MAXIDLE(tp)) {
929 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp, tcp_fin_timeout);
930 } else {
931 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp, TCP_CONN_MAXIDLE(tp));
932 }
933 }
934
935 /*
936 * TCP input routine, follows pages 65-76 of the
937 * protocol specification dated September, 1981 very closely.
938 */
939 int
tcp6_input(struct mbuf ** mp,int * offp,int proto)940 tcp6_input(struct mbuf **mp, int *offp, int proto)
941 {
942 #pragma unused(proto)
943 struct mbuf *m = *mp;
944 uint32_t ia6_flags;
945 struct ifnet *ifp = m->m_pkthdr.rcvif;
946
947 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), return IPPROTO_DONE);
948
949 /* Expect 32-bit aligned data pointer on strict-align platforms */
950 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
951
952 /*
953 * draft-itojun-ipv6-tcp-to-anycast
954 * better place to put this in?
955 */
956 if (ip6_getdstifaddr_info(m, NULL, &ia6_flags) == 0) {
957 if (ia6_flags & IN6_IFF_ANYCAST) {
958 struct ip6_hdr *ip6;
959
960 ip6 = mtod(m, struct ip6_hdr *);
961 icmp6_error(m, ICMP6_DST_UNREACH,
962 ICMP6_DST_UNREACH_ADDR,
963 (int)((caddr_t)&ip6->ip6_dst - (caddr_t)ip6));
964
965 IF_TCP_STATINC(ifp, icmp6unreach);
966
967 return IPPROTO_DONE;
968 }
969 }
970
971 tcp_input(m, *offp);
972 return IPPROTO_DONE;
973 }
974
975 static void
tcp_sbrcv_reserve(struct tcpcb * tp,struct sockbuf * sbrcv,u_int32_t newsize,u_int32_t idealsize,u_int32_t rcvbuf_max)976 tcp_sbrcv_reserve(struct tcpcb *tp, struct sockbuf *sbrcv,
977 u_int32_t newsize, u_int32_t idealsize, u_int32_t rcvbuf_max)
978 {
979 /* newsize should not exceed max */
980 newsize = min(newsize, rcvbuf_max);
981
982 /* The receive window scale negotiated at the
983 * beginning of the connection will also set a
984 * limit on the socket buffer size
985 */
986 newsize = min(newsize, TCP_MAXWIN << tp->rcv_scale);
987
988 /* Set new socket buffer size */
989 if (newsize > sbrcv->sb_hiwat &&
990 (sbreserve(sbrcv, newsize) == 1)) {
991 sbrcv->sb_idealsize = min(max(sbrcv->sb_idealsize,
992 (idealsize != 0) ? idealsize : newsize), rcvbuf_max);
993
994 /* Again check the limit set by the advertised
995 * window scale
996 */
997 sbrcv->sb_idealsize = min(sbrcv->sb_idealsize,
998 TCP_MAXWIN << tp->rcv_scale);
999 }
1000 }
1001
1002 /*
1003 * This function is used to grow a receive socket buffer. It
1004 * will take into account system-level memory usage and the
1005 * bandwidth available on the link to make a decision.
1006 */
1007 static void
tcp_sbrcv_grow(struct tcpcb * tp,struct sockbuf * sbrcv,struct tcpopt * to,uint32_t pktlen)1008 tcp_sbrcv_grow(struct tcpcb *tp, struct sockbuf *sbrcv,
1009 struct tcpopt *to, uint32_t pktlen)
1010 {
1011 struct socket *so = sbrcv->sb_so;
1012
1013 /*
1014 * Do not grow the receive socket buffer if
1015 * - auto resizing is disabled, globally or on this socket
1016 * - the high water mark already reached the maximum
1017 * - the stream is in background and receive side is being
1018 * throttled
1019 */
1020 if (tcp_do_autorcvbuf == 0 ||
1021 (sbrcv->sb_flags & SB_AUTOSIZE) == 0 ||
1022 sbrcv->sb_hiwat >= tcp_autorcvbuf_max ||
1023 (tp->t_flagsext & TF_RECV_THROTTLE) ||
1024 (so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) ||
1025 (!tcp_autotune_reorder && !LIST_EMPTY(&tp->t_segq))) {
1026 /* Can not resize the socket buffer, just return */
1027 goto out;
1028 }
1029
1030 if (!TSTMP_SUPPORTED(tp)) {
1031 /*
1032 * Timestamp option is not supported on this connection,
1033 * use receiver's RTT. Socket buffer grows based on the
1034 * BDP of the link.
1035 */
1036 if (TSTMP_GEQ(tcp_now,
1037 tp->rfbuf_ts + (tp->rcv_srtt >> TCP_RTT_SHIFT))) {
1038 tp->rfbuf_cnt += pktlen;
1039 if (tp->rfbuf_cnt > tp->rfbuf_space) {
1040 int32_t rcvbuf_inc;
1041 uint32_t idealsize;
1042
1043 /*
1044 * Increase receive-buffer aggressively if we
1045 * received more than 150% of what was received
1046 * in the previous round. Because, that means
1047 * the sender is in TCP slow-start and so
1048 * we need to give it more space to not be
1049 * limiting the sender with a small receive-window.
1050 */
1051 if (tp->rfbuf_cnt > tp->rfbuf_space + (tp->rfbuf_space >> 1)) {
1052 rcvbuf_inc = (tp->rfbuf_cnt << 2) - sbrcv->sb_hiwat;
1053 idealsize = (tp->rfbuf_cnt << 2);
1054 } else {
1055 rcvbuf_inc = (tp->rfbuf_cnt << 1) - sbrcv->sb_hiwat;
1056 idealsize = (tp->rfbuf_cnt << 1);
1057 }
1058
1059 if (rcvbuf_inc > 0) {
1060 rcvbuf_inc =
1061 (rcvbuf_inc / tp->t_maxseg) * tp->t_maxseg;
1062
1063 tcp_sbrcv_reserve(tp, sbrcv,
1064 sbrcv->sb_hiwat + rcvbuf_inc,
1065 idealsize, tcp_autorcvbuf_max);
1066
1067 tp->rfbuf_space = tp->rfbuf_cnt;
1068 }
1069 }
1070 goto out;
1071 } else {
1072 tp->rfbuf_cnt += pktlen;
1073 return;
1074 }
1075 } else if (to->to_tsecr != 0) {
1076 /*
1077 * If the timestamp shows that one RTT has
1078 * completed, we can stop counting the
1079 * bytes. Here we consider increasing
1080 * the socket buffer if the bandwidth measured in
1081 * last rtt, is more than half of sb_hiwat, this will
1082 * help to scale the buffer according to the bandwidth
1083 * on the link.
1084 */
1085 if (TSTMP_GEQ(to->to_tsecr, tp->rfbuf_ts)) {
1086 tp->rfbuf_cnt += pktlen;
1087
1088 if (tp->rfbuf_cnt > tp->rfbuf_space) {
1089 int32_t rcvbuf_inc;
1090 uint32_t idealsize;
1091
1092 if (tp->rfbuf_cnt > tp->rfbuf_space + (tp->rfbuf_space >> 1)) {
1093 rcvbuf_inc = (tp->rfbuf_cnt << 2) - sbrcv->sb_hiwat;
1094 idealsize = (tp->rfbuf_cnt << 2);
1095 } else {
1096 rcvbuf_inc = (tp->rfbuf_cnt << 1) - sbrcv->sb_hiwat;
1097 idealsize = (tp->rfbuf_cnt << 1);
1098 }
1099
1100 tp->rfbuf_space = tp->rfbuf_cnt;
1101
1102 if (rcvbuf_inc > 0) {
1103 rcvbuf_inc =
1104 (rcvbuf_inc / tp->t_maxseg) * tp->t_maxseg;
1105
1106 tcp_sbrcv_reserve(tp, sbrcv,
1107 sbrcv->sb_hiwat + rcvbuf_inc,
1108 idealsize, tcp_autorcvbuf_max);
1109 }
1110 }
1111 /* Measure instantaneous receive bandwidth */
1112 if (tp->t_bwmeas != NULL && tp->rfbuf_cnt > 0 &&
1113 TSTMP_GT(tcp_now, tp->rfbuf_ts)) {
1114 u_int32_t rcv_bw;
1115 rcv_bw = tp->rfbuf_cnt /
1116 (int)(tcp_now - tp->rfbuf_ts);
1117 if (tp->t_bwmeas->bw_rcvbw_max == 0) {
1118 tp->t_bwmeas->bw_rcvbw_max = rcv_bw;
1119 } else {
1120 tp->t_bwmeas->bw_rcvbw_max = max(
1121 tp->t_bwmeas->bw_rcvbw_max, rcv_bw);
1122 }
1123 }
1124 goto out;
1125 } else {
1126 tp->rfbuf_cnt += pktlen;
1127 return;
1128 }
1129 }
1130 out:
1131 /* Restart the measurement */
1132 tp->rfbuf_ts = tcp_now;
1133 tp->rfbuf_cnt = 0;
1134 return;
1135 }
1136
1137 /* This function will trim the excess space added to the socket buffer
1138 * to help a slow-reading app. The ideal-size of a socket buffer depends
1139 * on the link bandwidth or it is set by an application and we aim to
1140 * reach that size.
1141 */
1142 void
tcp_sbrcv_trim(struct tcpcb * tp,struct sockbuf * sbrcv)1143 tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sbrcv)
1144 {
1145 if (tcp_do_autorcvbuf == 1 && sbrcv->sb_idealsize > 0 &&
1146 sbrcv->sb_hiwat > sbrcv->sb_idealsize) {
1147 int32_t trim;
1148 /* compute the difference between ideal and current sizes */
1149 u_int32_t diff = sbrcv->sb_hiwat - sbrcv->sb_idealsize;
1150
1151 /* Compute the maximum advertised window for
1152 * this connection.
1153 */
1154 u_int32_t advwin = tp->rcv_adv - tp->rcv_nxt;
1155
1156 /* How much can we trim the receive socket buffer?
1157 * 1. it can not be trimmed beyond the max rcv win advertised
1158 * 2. if possible, leave 1/16 of bandwidth*delay to
1159 * avoid closing the win completely
1160 */
1161 u_int32_t leave = max(advwin, (sbrcv->sb_idealsize >> 4));
1162
1163 /* Sometimes leave can be zero, in that case leave at least
1164 * a few segments worth of space.
1165 */
1166 if (leave == 0) {
1167 leave = tp->t_maxseg << tcp_autorcvbuf_inc_shift;
1168 }
1169
1170 trim = sbrcv->sb_hiwat - (sbrcv->sb_cc + leave);
1171 trim = imin(trim, (int32_t)diff);
1172
1173 if (trim > 0) {
1174 sbreserve(sbrcv, (sbrcv->sb_hiwat - trim));
1175 }
1176 }
1177 }
1178
1179 /* We may need to trim the send socket buffer size for two reasons:
1180 * 1. if the rtt seen on the connection is climbing up, we do not
1181 * want to fill the buffers any more.
1182 * 2. if the congestion win on the socket backed off, there is no need
1183 * to hold more mbufs for that connection than what the cwnd will allow.
1184 */
1185 void
tcp_sbsnd_trim(struct sockbuf * sbsnd)1186 tcp_sbsnd_trim(struct sockbuf *sbsnd)
1187 {
1188 if (((sbsnd->sb_flags & (SB_AUTOSIZE | SB_TRIM)) ==
1189 (SB_AUTOSIZE | SB_TRIM)) &&
1190 (sbsnd->sb_idealsize > 0) &&
1191 (sbsnd->sb_hiwat > sbsnd->sb_idealsize)) {
1192 u_int32_t trim = 0;
1193 if (sbsnd->sb_cc <= sbsnd->sb_idealsize) {
1194 trim = sbsnd->sb_hiwat - sbsnd->sb_idealsize;
1195 } else {
1196 trim = sbsnd->sb_hiwat - sbsnd->sb_cc;
1197 }
1198 sbreserve(sbsnd, (sbsnd->sb_hiwat - trim));
1199 }
1200 if (sbsnd->sb_hiwat <= sbsnd->sb_idealsize) {
1201 sbsnd->sb_flags &= ~(SB_TRIM);
1202 }
1203 }
1204
1205 /*
1206 * If timestamp option was not negotiated on this connection
1207 * and this connection is on the receiving side of a stream
1208 * then we can not measure the delay on the link accurately.
1209 * Instead of enabling automatic receive socket buffer
1210 * resizing, just give more space to the receive socket buffer.
1211 */
1212 static inline void
tcp_sbrcv_tstmp_check(struct tcpcb * tp)1213 tcp_sbrcv_tstmp_check(struct tcpcb *tp)
1214 {
1215 struct socket *so = tp->t_inpcb->inp_socket;
1216 u_int32_t newsize = 2 * tcp_recvspace;
1217 struct sockbuf *sbrcv = &so->so_rcv;
1218
1219 if ((tp->t_flags & (TF_REQ_TSTMP | TF_RCVD_TSTMP)) !=
1220 (TF_REQ_TSTMP | TF_RCVD_TSTMP) &&
1221 (sbrcv->sb_flags & SB_AUTOSIZE) != 0) {
1222 tcp_sbrcv_reserve(tp, sbrcv, newsize, 0, newsize);
1223 }
1224 }
1225
1226 /* A receiver will evaluate the flow of packets on a connection
1227 * to see if it can reduce ack traffic. The receiver will start
1228 * stretching acks if all of the following conditions are met:
1229 * 1. tcp_delack_enabled is set to 3
1230 * 2. If the bytes received in the last 100ms is greater than a threshold
1231 * defined by maxseg_unacked
1232 * 3. If the connection has not been idle for tcp_maxrcvidle period.
1233 * 4. If the connection has seen enough packets to let the slow-start
1234 * finish after connection establishment or after some packet loss.
1235 *
1236 * The receiver will stop stretching acks if there is congestion/reordering
1237 * as indicated by packets on reassembly queue or an ECN. If the delayed-ack
1238 * timer fires while stretching acks, it means that the packet flow has gone
1239 * below the threshold defined by maxseg_unacked and the receiver will stop
1240 * stretching acks. The receiver gets no indication when slow-start is completed
1241 * or when the connection reaches an idle state. That is why we use
1242 * tcp_rcvsspktcnt to cover slow-start and tcp_maxrcvidle to identify idle
1243 * state.
1244 */
1245 static inline int
tcp_stretch_ack_enable(struct tcpcb * tp,int thflags)1246 tcp_stretch_ack_enable(struct tcpcb *tp, int thflags)
1247 {
1248 if (tp->rcv_by_unackwin >= (maxseg_unacked * tp->t_maxseg) &&
1249 TSTMP_GEQ(tp->rcv_unackwin, tcp_now)) {
1250 tp->t_flags |= TF_STREAMING_ON;
1251 } else {
1252 tp->t_flags &= ~TF_STREAMING_ON;
1253 }
1254
1255 /* If there has been an idle time, reset streaming detection */
1256 if (TSTMP_GT(tcp_now, tp->rcv_unackwin + tcp_maxrcvidle)) {
1257 tp->t_flags &= ~TF_STREAMING_ON;
1258 }
1259
1260 /*
1261 * If there are flags other than TH_ACK set, reset streaming
1262 * detection
1263 */
1264 if (thflags & ~TH_ACK) {
1265 tp->t_flags &= ~TF_STREAMING_ON;
1266 }
1267
1268 if (tp->t_flagsext & TF_DISABLE_STRETCHACK) {
1269 if (tp->rcv_nostrack_pkts >= TCP_STRETCHACK_ENABLE_PKTCNT) {
1270 tp->t_flagsext &= ~TF_DISABLE_STRETCHACK;
1271 tp->rcv_nostrack_pkts = 0;
1272 tp->rcv_nostrack_ts = 0;
1273 } else {
1274 tp->rcv_nostrack_pkts++;
1275 }
1276 }
1277
1278 if (!(tp->t_flagsext & (TF_NOSTRETCHACK | TF_DISABLE_STRETCHACK)) &&
1279 (tp->t_flags & TF_STREAMING_ON) &&
1280 (!(tp->t_flagsext & TF_RCVUNACK_WAITSS) ||
1281 (tp->rcv_waitforss >= tcp_rcvsspktcnt))) {
1282 return 1;
1283 }
1284
1285 return 0;
1286 }
1287
1288 /*
1289 * Reset the state related to stretch-ack algorithm. This will make
1290 * the receiver generate an ack every other packet. The receiver
1291 * will start re-evaluating the rate at which packets come to decide
1292 * if it can benefit by lowering the ack traffic.
1293 */
1294 void
tcp_reset_stretch_ack(struct tcpcb * tp)1295 tcp_reset_stretch_ack(struct tcpcb *tp)
1296 {
1297 tp->t_flags &= ~(TF_STRETCHACK | TF_STREAMING_ON);
1298 tp->rcv_by_unackwin = 0;
1299 tp->rcv_by_unackhalfwin = 0;
1300 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
1301
1302 /*
1303 * When there is packet loss or packet re-ordering or CWR due to
1304 * ECN, the sender's congestion window is reduced. In these states,
1305 * generate an ack for every other packet for some time to allow
1306 * the sender's congestion window to grow.
1307 */
1308 tp->t_flagsext |= TF_RCVUNACK_WAITSS;
1309 tp->rcv_waitforss = 0;
1310 }
1311
1312 /*
1313 * The last packet was a retransmission, check if this ack
1314 * indicates that the retransmission was spurious.
1315 *
1316 * If the connection supports timestamps, we could use it to
1317 * detect if the last retransmit was not needed. Otherwise,
1318 * we check if the ACK arrived within RTT/2 window, then it
1319 * was a mistake to do the retransmit in the first place.
1320 *
1321 * This function will return 1 if it is a spurious retransmit,
1322 * 0 otherwise.
1323 */
1324 int
tcp_detect_bad_rexmt(struct tcpcb * tp,struct tcphdr * th,struct tcpopt * to,u_int32_t rxtime)1325 tcp_detect_bad_rexmt(struct tcpcb *tp, struct tcphdr *th,
1326 struct tcpopt *to, u_int32_t rxtime)
1327 {
1328 int32_t tdiff, bad_rexmt_win;
1329 bad_rexmt_win = (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
1330
1331 /* If the ack has ECN CE bit, then cwnd has to be adjusted */
1332 if ((TCP_ACC_ECN_ON(tp) && tp->t_aecn.t_delta_ce_packets > 0) ||
1333 (TCP_ECN_ENABLED(tp) && (th->th_flags & TH_ECE))) {
1334 return 0;
1335 }
1336 if (TSTMP_SUPPORTED(tp)) {
1337 if (rxtime > 0 && (to->to_flags & TOF_TS) && to->to_tsecr != 0 &&
1338 TSTMP_LT(to->to_tsecr, rxtime)) {
1339 return 1;
1340 }
1341 } else {
1342 if ((tp->t_rxtshift == 1 || (tp->t_flagsext & TF_SENT_TLPROBE)) &&
1343 rxtime > 0) {
1344 tdiff = (int32_t)(tcp_now - rxtime);
1345 if (tdiff < bad_rexmt_win) {
1346 return 1;
1347 }
1348 }
1349 }
1350 return 0;
1351 }
1352
1353
1354 /*
1355 * Restore congestion window state if a spurious timeout
1356 * was detected.
1357 */
1358 static void
tcp_bad_rexmt_restore_state(struct tcpcb * tp,struct tcphdr * th)1359 tcp_bad_rexmt_restore_state(struct tcpcb *tp, struct tcphdr *th)
1360 {
1361 if (TSTMP_SUPPORTED(tp)) {
1362 u_int32_t fsize, acked;
1363 fsize = tp->snd_max - th->th_ack;
1364 acked = BYTES_ACKED(th, tp);
1365
1366 /*
1367 * Implement bad retransmit recovery as
1368 * described in RFC 4015.
1369 */
1370 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1371
1372 /* Initialize cwnd to the initial window */
1373 if (CC_ALGO(tp)->cwnd_init != NULL) {
1374 CC_ALGO(tp)->cwnd_init(tp);
1375 }
1376
1377 tp->snd_cwnd = fsize + min(acked, tp->snd_cwnd);
1378 } else {
1379 tp->snd_cwnd = tp->snd_cwnd_prev;
1380 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1381 if (tp->t_flags & TF_WASFRECOVERY) {
1382 ENTER_FASTRECOVERY(tp);
1383 }
1384
1385 /* Do not use the loss flight size in this case */
1386 tp->t_lossflightsize = 0;
1387 }
1388 tp->snd_cwnd = max(tp->snd_cwnd, tcp_initial_cwnd(tp));
1389 tp->snd_recover = tp->snd_recover_prev;
1390 tp->snd_nxt = tp->snd_max;
1391
1392 /* Fix send socket buffer to reflect the change in cwnd */
1393 tcp_bad_rexmt_fix_sndbuf(tp);
1394
1395 /* Restore rack related state */
1396 if (TCP_RACK_ENABLED(tp)) {
1397 tcp_rack_bad_rexmt_restore(tp);
1398 }
1399
1400 /*
1401 * This RTT might reflect the extra delay induced
1402 * by the network. Skip using this sample for RTO
1403 * calculation and mark the connection so we can
1404 * recompute RTT when the next eligible sample is
1405 * found.
1406 */
1407 tp->t_flagsext |= TF_RECOMPUTE_RTT;
1408 tp->t_badrexmt_time = tcp_now;
1409 tp->t_rtttime = 0;
1410 }
1411
1412 /*
1413 * If the previous packet was sent in retransmission timer, and it was
1414 * not needed, then restore the congestion window to the state before that
1415 * transmission.
1416 *
1417 * If the last packet was sent in tail loss probe timeout, check if that
1418 * recovered the last packet. If so, that will indicate a real loss and
1419 * the congestion window needs to be lowered.
1420 */
1421 static void
tcp_bad_rexmt_check(struct tcpcb * tp,struct tcphdr * th,struct tcpopt * to)1422 tcp_bad_rexmt_check(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
1423 {
1424 if (tp->t_rxtshift > 0 &&
1425 tcp_detect_bad_rexmt(tp, th, to, tp->t_rxtstart)) {
1426 ++tcpstat.tcps_sndrexmitbad;
1427 tcp_bad_rexmt_restore_state(tp, th);
1428 tcp_ccdbg_trace(tp, th, TCP_CC_BAD_REXMT_RECOVERY);
1429 } else if ((tp->t_flagsext & TF_SENT_TLPROBE) && tp->t_tlphighrxt > 0 &&
1430 SEQ_GEQ(th->th_ack, tp->t_tlphighrxt) &&
1431 !tcp_detect_bad_rexmt(tp, th, to, tp->t_tlpstart)) {
1432 /*
1433 * The tail loss probe recovered the last packet and
1434 * we need to adjust the congestion window to take
1435 * this loss into account.
1436 * No need to update rack.reo_wnd_persist for a TLP recovery
1437 */
1438 ++tcpstat.tcps_tlp_recoverlastpkt;
1439 if (!IN_FASTRECOVERY(tp)) {
1440 tcp_enter_fast_recovery(tp);
1441 EXIT_FASTRECOVERY(tp);
1442 }
1443 tcp_ccdbg_trace(tp, th, TCP_CC_TLP_RECOVER_LASTPACKET);
1444 } else if (tcp_rxtseg_detect_bad_rexmt(tp, th->th_ack)) {
1445 /*
1446 * All of the retransmitted segments were duplicated, this
1447 * can be an indication of bad fast retransmit.
1448 */
1449 tcpstat.tcps_dsack_badrexmt++;
1450 tcp_bad_rexmt_restore_state(tp, th);
1451 tcp_ccdbg_trace(tp, th, TCP_CC_DSACK_BAD_REXMT);
1452 tcp_rxtseg_clean(tp);
1453 }
1454 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1455 tp->t_tlphighrxt = 0;
1456 tp->t_tlpstart = 0;
1457
1458 /*
1459 * check if the latest ack was for a segment sent during PMTU
1460 * blackhole detection. If the timestamp on the ack is before
1461 * PMTU blackhole detection, then revert the size of the max
1462 * segment to previous size.
1463 */
1464 if (tp->t_rxtshift > 0 && (tp->t_flags & TF_BLACKHOLE) &&
1465 tp->t_pmtud_start_ts > 0 && TSTMP_SUPPORTED(tp)) {
1466 if ((to->to_flags & TOF_TS) && to->to_tsecr != 0
1467 && TSTMP_LT(to->to_tsecr, tp->t_pmtud_start_ts)) {
1468 tcp_pmtud_revert_segment_size(tp);
1469 }
1470 }
1471 if (tp->t_pmtud_start_ts > 0) {
1472 tp->t_pmtud_start_ts = 0;
1473 }
1474
1475 tp->t_pmtud_lastseg_size = 0;
1476 }
1477
1478 /*
1479 * Check if early retransmit can be attempted according to RFC 5827.
1480 *
1481 * If packet reordering is detected on a connection, fast recovery will
1482 * be delayed until it is clear that the packet was lost and not reordered.
1483 * But reordering detection is done only when SACK is enabled.
1484 *
1485 * On connections that do not support SACK, there is a limit on the number
1486 * of early retransmits that can be done per minute. This limit is needed
1487 * to make sure that too many packets are not retransmitted when there is
1488 * packet reordering.
1489 */
1490 static void
tcp_early_rexmt_check(struct tcpcb * tp,struct tcphdr * th)1491 tcp_early_rexmt_check(struct tcpcb *tp, struct tcphdr *th)
1492 {
1493 u_int32_t obytes, snd_off;
1494 int32_t snd_len;
1495 struct socket *so = tp->t_inpcb->inp_socket;
1496
1497 if ((SACK_ENABLED(tp) || tp->t_early_rexmt_count < TCP_EARLY_REXMT_LIMIT) &&
1498 SEQ_GT(tp->snd_max, tp->snd_una) &&
1499 (tp->t_dupacks == 1 || (SACK_ENABLED(tp) && !TAILQ_EMPTY(&tp->snd_holes)))) {
1500 /*
1501 * If there are only a few outstanding
1502 * segments on the connection, we might need
1503 * to lower the retransmit threshold. This
1504 * will allow us to do Early Retransmit as
1505 * described in RFC 5827.
1506 */
1507 if (TCP_RACK_ENABLED(tp)) {
1508 obytes = tcp_flight_size(tp);
1509 } else if (SACK_ENABLED(tp) &&
1510 !TAILQ_EMPTY(&tp->snd_holes)) {
1511 obytes = tcp_flight_size(tp);
1512 } else {
1513 obytes = (tp->snd_max - tp->snd_una);
1514 }
1515
1516 /*
1517 * In order to lower retransmit threshold the
1518 * following two conditions must be met.
1519 * 1. the amount of outstanding data is less
1520 * than 4*SMSS bytes
1521 * 2. there is no unsent data ready for
1522 * transmission or the advertised window
1523 * will limit sending new segments.
1524 */
1525 snd_off = tp->snd_max - tp->snd_una;
1526 snd_len = min(so->so_snd.sb_cc, tp->snd_wnd) - snd_off;
1527 if (obytes < (tp->t_maxseg << 2) &&
1528 snd_len <= 0) {
1529 u_int32_t osegs;
1530
1531 osegs = obytes / tp->t_maxseg;
1532 if ((osegs * tp->t_maxseg) < obytes) {
1533 osegs++;
1534 }
1535
1536 /*
1537 * By checking for early retransmit after
1538 * receiving some duplicate acks when SACK
1539 * is supported, the connection will
1540 * enter fast recovery even if multiple
1541 * segments are lost in the same window.
1542 */
1543 if (osegs < 4) {
1544 tp->t_rexmtthresh =
1545 ((osegs - 1) > 1) ? ((uint8_t)osegs - 1) : 1;
1546 tp->t_rexmtthresh =
1547 MIN(tp->t_rexmtthresh, tcprexmtthresh);
1548 tp->t_rexmtthresh =
1549 MAX(tp->t_rexmtthresh,
1550 tp->t_dupacks > UINT8_MAX ? UINT8_MAX : (uint8_t)tp->t_dupacks);
1551
1552 if (tp->t_early_rexmt_count == 0) {
1553 tp->t_early_rexmt_win = tcp_now;
1554 }
1555
1556 if (tp->t_flagsext & TF_SENT_TLPROBE) {
1557 tcpstat.tcps_tlp_recovery++;
1558 tcp_ccdbg_trace(tp, th,
1559 TCP_CC_TLP_RECOVERY);
1560 } else {
1561 tcpstat.tcps_early_rexmt++;
1562 tp->t_early_rexmt_count++;
1563 tcp_ccdbg_trace(tp, th,
1564 TCP_CC_EARLY_RETRANSMIT);
1565 }
1566 }
1567 }
1568 }
1569
1570 /*
1571 * If we ever sent a TLP probe, the acknowledgement will trigger
1572 * early retransmit because the value of snd_fack will be close
1573 * to snd_max. This will take care of adjustments to the
1574 * congestion window. So we can reset TF_SENT_PROBE flag.
1575 */
1576 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1577 tp->t_tlphighrxt = 0;
1578 tp->t_tlpstart = 0;
1579 }
1580
1581 static boolean_t
tcp_tfo_syn(struct tcpcb * tp,struct tcpopt * to)1582 tcp_tfo_syn(struct tcpcb *tp, struct tcpopt *to)
1583 {
1584 u_char out[CCAES_BLOCK_SIZE];
1585 unsigned char len;
1586
1587 if (!(to->to_flags & (TOF_TFO | TOF_TFOREQ)) ||
1588 !(tcp_fastopen & TCP_FASTOPEN_SERVER)) {
1589 return FALSE;
1590 }
1591
1592 if ((to->to_flags & TOF_TFOREQ)) {
1593 tp->t_tfo_flags |= TFO_F_OFFER_COOKIE;
1594
1595 tp->t_tfo_stats |= TFO_S_COOKIEREQ_RECV;
1596 tcpstat.tcps_tfo_cookie_req_rcv++;
1597 return FALSE;
1598 }
1599
1600 /* Ok, then it must be an offered cookie. We need to check that ... */
1601 tcp_tfo_gen_cookie(tp->t_inpcb, out, sizeof(out));
1602
1603 len = *to->to_tfo - TCPOLEN_FASTOPEN_REQ;
1604 to->to_tfo++;
1605 if (memcmp(out, to->to_tfo, len)) {
1606 /* Cookies are different! Let's return and offer a new cookie */
1607 tp->t_tfo_flags |= TFO_F_OFFER_COOKIE;
1608
1609 tp->t_tfo_stats |= TFO_S_COOKIE_INVALID;
1610 tcpstat.tcps_tfo_cookie_invalid++;
1611 return FALSE;
1612 }
1613
1614 if (OSIncrementAtomic(&tcp_tfo_halfcnt) >= tcp_tfo_backlog) {
1615 /* Need to decrement again as we just increased it... */
1616 OSDecrementAtomic(&tcp_tfo_halfcnt);
1617 return FALSE;
1618 }
1619
1620 tp->t_tfo_flags |= TFO_F_COOKIE_VALID;
1621
1622 tp->t_tfo_stats |= TFO_S_SYNDATA_RCV;
1623 tcpstat.tcps_tfo_syn_data_rcv++;
1624
1625 return TRUE;
1626 }
1627
1628 static void
tcp_tfo_synack(struct tcpcb * tp,struct tcpopt * to)1629 tcp_tfo_synack(struct tcpcb *tp, struct tcpopt *to)
1630 {
1631 if (to->to_flags & TOF_TFO) {
1632 unsigned char len = *to->to_tfo - TCPOLEN_FASTOPEN_REQ;
1633
1634 /*
1635 * If this happens, things have gone terribly wrong. len should
1636 * have been checked in tcp_dooptions.
1637 */
1638 VERIFY(len <= TFO_COOKIE_LEN_MAX);
1639
1640 to->to_tfo++;
1641
1642 tcp_cache_set_cookie(tp, to->to_tfo, len);
1643 tcp_heuristic_tfo_success(tp);
1644
1645 tp->t_tfo_stats |= TFO_S_COOKIE_RCV;
1646 tcpstat.tcps_tfo_cookie_rcv++;
1647 if (tp->t_tfo_flags & TFO_F_COOKIE_SENT) {
1648 tcpstat.tcps_tfo_cookie_wrong++;
1649 tp->t_tfo_stats |= TFO_S_COOKIE_WRONG;
1650 }
1651 } else {
1652 /*
1653 * Thus, no cookie in the response, but we either asked for one
1654 * or sent SYN+DATA. Now, we need to check whether we had to
1655 * rexmit the SYN. If that's the case, it's better to start
1656 * backing of TFO-cookie requests.
1657 */
1658 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
1659 tp->t_tfo_flags & TFO_F_SYN_LOSS) {
1660 tp->t_tfo_stats |= TFO_S_SYN_LOSS;
1661 tcpstat.tcps_tfo_syn_loss++;
1662
1663 tcp_heuristic_tfo_loss(tp);
1664 } else {
1665 if (tp->t_tfo_flags & TFO_F_COOKIE_REQ) {
1666 tp->t_tfo_stats |= TFO_S_NO_COOKIE_RCV;
1667 tcpstat.tcps_tfo_no_cookie_rcv++;
1668 }
1669
1670 tcp_heuristic_tfo_success(tp);
1671 }
1672 }
1673 }
1674
1675 static void
tcp_tfo_rcv_probe(struct tcpcb * tp,int tlen)1676 tcp_tfo_rcv_probe(struct tcpcb *tp, int tlen)
1677 {
1678 if (tlen != 0) {
1679 return;
1680 }
1681
1682 tp->t_tfo_probe_state = TFO_PROBE_PROBING;
1683
1684 /*
1685 * We send the probe out rather quickly (after one RTO). It does not
1686 * really hurt that much, it's only one additional segment on the wire.
1687 */
1688 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, (TCP_REXMTVAL(tp)));
1689 }
1690
1691 static void
tcp_tfo_rcv_data(struct tcpcb * tp)1692 tcp_tfo_rcv_data(struct tcpcb *tp)
1693 {
1694 /* Transition from PROBING to NONE as data has been received */
1695 if (tp->t_tfo_probe_state >= TFO_PROBE_PROBING) {
1696 tp->t_tfo_probe_state = TFO_PROBE_NONE;
1697 }
1698 }
1699
1700 static void
tcp_tfo_rcv_ack(struct tcpcb * tp,struct tcphdr * th)1701 tcp_tfo_rcv_ack(struct tcpcb *tp, struct tcphdr *th)
1702 {
1703 if (tp->t_tfo_probe_state == TFO_PROBE_PROBING &&
1704 tp->t_tfo_probes > 0) {
1705 if (th->th_seq == tp->rcv_nxt) {
1706 /* No hole, so stop probing */
1707 tp->t_tfo_probe_state = TFO_PROBE_NONE;
1708 } else if (SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1709 /* There is a hole! Wait a bit for data... */
1710 tp->t_tfo_probe_state = TFO_PROBE_WAIT_DATA;
1711 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
1712 TCP_REXMTVAL(tp));
1713 }
1714 }
1715 }
1716
1717 /*
1718 * Update snd_wnd information.
1719 */
1720 static inline bool
tcp_update_window(struct tcpcb * tp,int thflags,struct tcphdr * th,u_int32_t tiwin,int tlen)1721 tcp_update_window(struct tcpcb *tp, int thflags, struct tcphdr * th,
1722 u_int32_t tiwin, int tlen)
1723 {
1724 /* Don't look at the window if there is no ACK flag */
1725 if ((thflags & TH_ACK) &&
1726 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1727 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1728 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1729 /* keep track of pure window updates */
1730 if (tlen == 0 &&
1731 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) {
1732 tcpstat.tcps_rcvwinupd++;
1733 }
1734 tp->snd_wnd = tiwin;
1735 tp->snd_wl1 = th->th_seq;
1736 tp->snd_wl2 = th->th_ack;
1737 if (tp->snd_wnd > tp->max_sndwnd) {
1738 tp->max_sndwnd = tp->snd_wnd;
1739 }
1740
1741 if (tp->t_inpcb->inp_socket->so_flags & SOF_MP_SUBFLOW) {
1742 mptcp_update_window_wakeup(tp);
1743 }
1744 return true;
1745 }
1746 return false;
1747 }
1748
1749 static void
tcp_handle_wakeup(struct socket * so,int read_wakeup,int write_wakeup)1750 tcp_handle_wakeup(struct socket *so, int read_wakeup, int write_wakeup)
1751 {
1752 if (read_wakeup != 0) {
1753 sorwakeup(so);
1754 }
1755 if (write_wakeup != 0) {
1756 sowwakeup(so);
1757 }
1758 }
1759
1760 static void
tcp_update_snd_una(struct tcpcb * tp,uint32_t ack)1761 tcp_update_snd_una(struct tcpcb *tp, uint32_t ack)
1762 {
1763 tp->snd_una = ack;
1764 }
1765
1766 static bool
tcp_syn_data_valid(struct tcpcb * tp,struct tcphdr * tcp_hdr,int tlen)1767 tcp_syn_data_valid(struct tcpcb *tp, struct tcphdr *tcp_hdr, int tlen)
1768 {
1769 /* No data? */
1770 if (tlen <= 0) {
1771 return false;
1772 }
1773
1774 /* Not the right sequence-number? */
1775 if (tcp_hdr->th_seq != tp->irs) {
1776 return false;
1777 }
1778
1779 /* We could have wrapped around, check that */
1780 if (tp->t_inpcb->inp_stat->rxbytes > INT32_MAX) {
1781 return false;
1782 }
1783
1784 return true;
1785 }
1786
1787 /* Process IP-ECN codepoints on received packets and update receive side counters */
1788 static void
tcp_input_ip_ecn(struct tcpcb * tp,struct inpcb * inp,uint32_t tlen,uint32_t segment_count,uint8_t ip_ecn)1789 tcp_input_ip_ecn(struct tcpcb *tp, struct inpcb *inp, uint32_t tlen,
1790 uint32_t segment_count, uint8_t ip_ecn)
1791 {
1792 switch (ip_ecn) {
1793 case IPTOS_ECN_ECT1:
1794 tp->ecn_flags |= TE_ACO_ECT1;
1795 tp->t_aecn.t_rcv_ect1_bytes += tlen;
1796 break;
1797 case IPTOS_ECN_ECT0:
1798 tp->ecn_flags |= TE_ACO_ECT0;
1799 tp->t_aecn.t_rcv_ect0_bytes += tlen;
1800 break;
1801 case IPTOS_ECN_CE:
1802 tp->t_aecn.t_rcv_ce_packets += segment_count;
1803 tp->t_aecn.t_rcv_ce_bytes += tlen;
1804 tp->t_ecn_recv_ce++;
1805 tcpstat.tcps_ecn_recv_ce++;
1806 INP_INC_IFNET_STAT(inp, ecn_recv_ce);
1807 break;
1808 default:
1809 /* No counter for Not-ECT */
1810 break;
1811 }
1812 }
1813
1814 /* Process SYN packet that wishes to negotiate Accurate ECN */
1815 static void
tcp_input_process_accecn_syn(struct tcpcb * tp,int ace_flags,uint8_t ip_ecn)1816 tcp_input_process_accecn_syn(struct tcpcb *tp, int ace_flags, uint8_t ip_ecn)
1817 {
1818 switch (ace_flags) {
1819 case (0 | 0 | 0):
1820 /* No ECN */
1821 tp->t_server_accecn_state = tcp_connection_server_no_ecn_requested;
1822 break;
1823 case (0 | TH_CWR | TH_ECE):
1824 /* Legacy ECN-setup */
1825 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
1826 tp->t_server_accecn_state = tcp_connection_server_classic_ecn_requested;
1827 break;
1828 case (TH_ACE):
1829 /* Accurate ECN */
1830 if (TCP_ACC_ECN_ENABLED(tp)) {
1831 switch (ip_ecn) {
1832 case IPTOS_ECN_NOTECT:
1833 tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
1834 break;
1835 case IPTOS_ECN_ECT1:
1836 tp->ecn_flags |= TE_ACE_SETUP_ECT1;
1837 break;
1838 case IPTOS_ECN_ECT0:
1839 tp->ecn_flags |= TE_ACE_SETUP_ECT0;
1840 break;
1841 case IPTOS_ECN_CE:
1842 tp->ecn_flags |= TE_ACE_SETUP_CE;
1843 break;
1844 }
1845 /*
1846 * We set TE_SENDIPECT when handshake is complete
1847 * for Accurate ECN
1848 */
1849 tp->ecn_flags |= (TE_ACE_SETUPRECEIVED);
1850
1851 /* Initialize ECT byte counter to 1 to distinguish zeroing of options */
1852 tp->t_aecn.t_rcv_ect1_bytes = tp->t_aecn.t_rcv_ect0_bytes = 1;
1853 tp->t_aecn.t_snd_ect1_bytes = tp->t_aecn.t_snd_ect0_bytes = 1;
1854 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_requested;
1855 } else {
1856 /*
1857 * If AccECN is not enabled, ignore
1858 * the TH_AE bit and do Legacy ECN-setup
1859 */
1860 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
1861 }
1862 default:
1863 /* Forward Compatibility */
1864 /* Accurate ECN */
1865 if (TCP_ACC_ECN_ENABLED(tp)) {
1866 switch (ip_ecn) {
1867 case IPTOS_ECN_NOTECT:
1868 tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
1869 break;
1870 case IPTOS_ECN_ECT1:
1871 tp->ecn_flags |= TE_ACE_SETUP_ECT1;
1872 break;
1873 case IPTOS_ECN_ECT0:
1874 tp->ecn_flags |= TE_ACE_SETUP_ECT0;
1875 break;
1876 case IPTOS_ECN_CE:
1877 tp->ecn_flags |= TE_ACE_SETUP_CE;
1878 break;
1879 }
1880 /*
1881 * We are not yet committing to send IP ECT packets when
1882 * Accurate ECN is enabled
1883 */
1884 tp->ecn_flags |= (TE_ACE_SETUPRECEIVED);
1885
1886 /* Initialize ECT byte counter to 1 to distinguish zeroing of options */
1887 tp->t_aecn.t_rcv_ect1_bytes = tp->t_aecn.t_rcv_ect0_bytes = 1;
1888 tp->t_aecn.t_snd_ect1_bytes = tp->t_aecn.t_snd_ect0_bytes = 1;
1889 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_requested;
1890 }
1891 break;
1892 }
1893 }
1894
1895 static uint32_t
tcp_process_ace_field(struct tcpcb * tp,uint32_t pkts_acked,uint64_t old_sceb,uint8_t ace)1896 tcp_process_ace_field(struct tcpcb *tp, uint32_t pkts_acked, uint64_t old_sceb, uint8_t ace)
1897 {
1898 /* Congestion was experienced if delta_cep > 0 */
1899 uint32_t delta = 0, safe_delta = 0;
1900 delta = (ace + TCP_ACE_DIV -
1901 (tp->t_aecn.t_snd_ce_packets & TCP_ACE_MASK)) & TCP_ACE_MASK;
1902 if (pkts_acked <= TCP_ACE_MASK) {
1903 return delta;
1904 }
1905
1906 uint64_t d_ceb = tp->t_aecn.t_snd_ce_bytes - old_sceb;
1907 safe_delta = pkts_acked - ((pkts_acked - delta) & TCP_ACE_MASK);
1908
1909 if (d_ceb == 0 || d_ceb < safe_delta * tp->t_maxseg >> 1) {
1910 return delta;
1911 }
1912
1913 return safe_delta;
1914 }
1915
1916 /* Returns the number of CE marked bytes */
1917 static uint32_t
tcp_process_accecn_options(struct tcpcb * tp,struct tcpopt * to)1918 tcp_process_accecn_options(struct tcpcb *tp, struct tcpopt *to)
1919 {
1920 int delta = 0;
1921 uint32_t ce_bytes = 0;
1922
1923 if (to->to_num_accecn >= 1) {
1924 delta = ntoh24(to->to_accecn + 0);
1925 if (to->to_accecn_order == 0) {
1926 delta = (delta + TCP_ACO_DIV -
1927 (tp->t_aecn.t_snd_ect0_bytes & TCP_ACO_MASK)) & TCP_ACO_MASK;
1928 if (delta < 0) {
1929 os_log_error(OS_LOG_DEFAULT, "delta for AccECN0 options (ECT0 bytes) can't be zero");
1930 }
1931 tp->t_aecn.t_snd_ect0_bytes += delta;
1932 } else {
1933 delta = (delta + TCP_ACO_DIV -
1934 (tp->t_aecn.t_snd_ect1_bytes & TCP_ACO_MASK)) & TCP_ACO_MASK;
1935 if (delta < 0) {
1936 os_log_error(OS_LOG_DEFAULT, "delta for AccECN1 options (ECT1 bytes) can't be zero");
1937 }
1938 tp->t_aecn.t_snd_ect1_bytes += delta;
1939 }
1940 }
1941 if (to->to_num_accecn >= 2) {
1942 delta = ntoh24(to->to_accecn + 1 * TCPOLEN_ACCECN_COUNTER);
1943 delta = (delta + TCP_ACO_DIV -
1944 (tp->t_aecn.t_snd_ce_bytes & TCP_ACO_MASK)) & TCP_ACO_MASK;
1945 if (delta < 0) {
1946 os_log_error(OS_LOG_DEFAULT, "delta for AccECN options (CE bytes) can't be zero");
1947 }
1948 tp->t_aecn.t_snd_ce_bytes += delta;
1949 ce_bytes = delta;
1950 }
1951 if (to->to_num_accecn >= 3) {
1952 delta = ntoh24(to->to_accecn + 2 * TCPOLEN_ACCECN_COUNTER);
1953 if (to->to_accecn_order == 0) {
1954 delta = (delta + TCP_ACO_DIV -
1955 (tp->t_aecn.t_snd_ect1_bytes & TCP_ACO_MASK)) & TCP_ACO_MASK;
1956 if (delta < 0) {
1957 os_log_error(OS_LOG_DEFAULT, "delta for AccECN0 options (ECT1 bytes) can't be zero");
1958 }
1959 tp->t_aecn.t_snd_ect1_bytes += delta;
1960 } else {
1961 delta = (delta + TCP_ACO_DIV -
1962 (tp->t_aecn.t_snd_ect0_bytes & TCP_ACO_MASK)) & TCP_ACO_MASK;
1963 if (delta < 0) {
1964 os_log_error(OS_LOG_DEFAULT, "delta for AccECN1 options (ECT0 bytes) can't be zero");
1965 }
1966 tp->t_aecn.t_snd_ect0_bytes += delta;
1967 }
1968 }
1969
1970 return ce_bytes;
1971 }
1972
1973 static void
tcp_process_accecn(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th,uint32_t pkts_acked,uint8_t ace)1974 tcp_process_accecn(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
1975 uint32_t pkts_acked, uint8_t ace)
1976 {
1977 if (tp->t_aecn.accecn_processed) {
1978 os_log(OS_LOG_DEFAULT, "already processed AccECN field/options for this ACK");
1979 return;
1980 }
1981
1982 uint64_t old_sceb = tp->t_aecn.t_snd_ce_bytes;
1983 uint32_t new_ce_bytes = tcp_process_accecn_options(tp, to);
1984 uint32_t delta = tcp_process_ace_field(tp, pkts_acked, old_sceb, ace);
1985 tp->t_aecn.t_snd_ce_packets += delta;
1986 tp->t_aecn.t_delta_ce_packets = delta;
1987
1988 /* Update the time for this newly acked data or control packet */
1989 if ((to->to_flags & TOF_TS) != 0 && (to->to_tsecr != 0) &&
1990 TSTMP_GEQ(to->to_tsecr, tp->t_last_ack_tsecr)) {
1991 tp->t_last_ack_tsecr = to->to_tsecr;
1992 }
1993
1994 if (delta > 0) {
1995 tp->ecn_flags |= (TE_INRECOVERY);
1996 tp->total_ect_packets_marked += delta;
1997
1998 /* update the stats */
1999 tcpstat.tcps_ecn_ace_recv_ce += tp->t_aecn.t_delta_ce_packets;
2000 /* CE packets counter start at 5 */
2001 tp->t_ecn_capable_packets_marked = tp->t_aecn.t_snd_ce_packets - 5;
2002 tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
2003 }
2004
2005 if (CC_ALGO(tp)->process_ecn != NULL) {
2006 CC_ALGO(tp)->process_ecn(tp, th, new_ce_bytes, tp->total_ect_packets_marked,
2007 tp->total_ect_packets_acked);
2008 }
2009
2010 tp->t_aecn.accecn_processed = 1;
2011 }
2012
2013 void
tcp_input(struct mbuf * m,int off0)2014 tcp_input(struct mbuf *m, int off0)
2015 {
2016 int exiting_fr = 0;
2017 struct tcphdr *th;
2018 struct ip *ip = NULL;
2019 struct inpcb *inp;
2020 u_char *optp = NULL;
2021 int optlen = 0;
2022 int tlen, off;
2023 int drop_hdrlen;
2024 struct tcpcb *tp = 0;
2025 int thflags;
2026 struct socket *so = 0;
2027 int todrop, acked = 0, ourfinisacked, needoutput = 0;
2028 int read_wakeup = 0;
2029 int write_wakeup = 0;
2030 struct in_addr laddr;
2031 struct in6_addr laddr6;
2032 int dropsocket = 0;
2033 int iss = 0, nosock = 0;
2034 uint32_t tiwin, sack_bytes_acked = 0;
2035 uint32_t highest_sacked_seq = 0;
2036 struct tcpopt to; /* options in this segment */
2037 u_char ip_ecn = IPTOS_ECN_NOTECT;
2038 unsigned int ifscope;
2039 uint8_t isconnected, isdisconnected;
2040 struct ifnet *ifp = m->m_pkthdr.rcvif;
2041 int segment_count = m->m_pkthdr.seg_cnt ? : 1;
2042 int win;
2043 u_int16_t pf_tag = 0;
2044 #if MPTCP
2045 struct mptcb *mp_tp = NULL;
2046 #endif /* MPTCP */
2047 stats_functional_type ifnet_count_type = IFNET_COUNT_TYPE(ifp);
2048 boolean_t recvd_dsack = FALSE;
2049 boolean_t dsack_tlp = false;
2050 struct tcp_respond_args tra;
2051 int prev_t_state;
2052 boolean_t check_cfil = cfil_filter_present();
2053 bool findpcb_iterated = false;
2054 bool rack_loss_detected = false;
2055 bool is_th_swapped = false;
2056 /*
2057 * The mbuf may be freed after it has been added to the receive socket
2058 * buffer or the reassembly queue, so we reinitialize th to point to a
2059 * safe copy of the TCP header
2060 */
2061 struct tcphdr saved_tcphdr = {};
2062 /*
2063 * Save copy of the IPv4/IPv6 header.
2064 * Note: use array of uint32_t to silence compiler warning when casting
2065 * to a struct ip6_hdr pointer.
2066 */
2067 #define MAX_IPWORDS ((sizeof(struct ip) + MAX_IPOPTLEN) / sizeof(uint32_t))
2068 uint32_t saved_hdr[MAX_IPWORDS];
2069
2070 #define TCP_INC_VAR(stat, npkts) do { \
2071 stat += npkts; \
2072 } while (0)
2073 drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;
2074
2075 if (tcp_ack_strategy == TCP_ACK_STRATEGY_LEGACY) {
2076 segment_count = 1;
2077 }
2078 TCP_INC_VAR(tcpstat.tcps_rcvtotal, segment_count);
2079
2080 struct ip6_hdr *ip6 = NULL;
2081 int isipv6;
2082 struct proc *kernel_proc = current_proc();
2083
2084 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
2085
2086 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
2087 bzero((char *)&to, sizeof(to));
2088
2089 m_add_crumb(m, PKT_CRUMB_TCP_INPUT);
2090
2091 if (m->m_flags & M_PKTHDR) {
2092 pf_tag = m_pftag(m)->pftag_tag;
2093 }
2094
2095 if (isipv6) {
2096 /*
2097 * Expect 32-bit aligned data pointer on
2098 * strict-align platforms
2099 */
2100 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
2101
2102 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
2103 ip6 = mtod(m, struct ip6_hdr *);
2104 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
2105 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
2106
2107 if (tcp_input_checksum(AF_INET6, m, th, off0, tlen)) {
2108 TCP_LOG_DROP_PKT(ip6, th, ifp, "IPv6 bad tcp checksum");
2109 goto dropnosock;
2110 }
2111
2112 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
2113 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
2114 th->th_seq, th->th_ack, th->th_win);
2115 /*
2116 * Be proactive about unspecified IPv6 address in source.
2117 * As we use all-zero to indicate unbounded/unconnected pcb,
2118 * unspecified IPv6 address can be used to confuse us.
2119 *
2120 * Note that packets with unspecified IPv6 destination is
2121 * already dropped in ip6_input.
2122 */
2123 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
2124 /* XXX stat */
2125 IF_TCP_STATINC(ifp, unspecv6);
2126 TCP_LOG_DROP_PKT(ip6, th, ifp, "src IPv6 address unspecified");
2127 goto dropnosock;
2128 }
2129 DTRACE_TCP5(receive, struct mbuf *, m, struct inpcb *, NULL,
2130 struct ip6_hdr *, ip6, struct tcpcb *, NULL,
2131 struct tcphdr *, th);
2132
2133 ip_ecn = (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
2134 } else {
2135 /*
2136 * Get IP and TCP header together in first mbuf.
2137 * Note: IP leaves IP header in first mbuf.
2138 */
2139 if (off0 > sizeof(struct ip)) {
2140 ip_stripoptions(m);
2141 off0 = sizeof(struct ip);
2142 }
2143 if (m->m_len < sizeof(struct tcpiphdr)) {
2144 if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
2145 tcpstat.tcps_rcvshort++;
2146 return;
2147 }
2148 }
2149
2150 /* Expect 32-bit aligned data pointer on strict-align platforms */
2151 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
2152
2153 ip = mtod(m, struct ip *);
2154 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
2155 tlen = ip->ip_len;
2156
2157 if (tcp_input_checksum(AF_INET, m, th, off0, tlen)) {
2158 TCP_LOG_DROP_PKT(ip, th, ifp, "IPv4 bad tcp checksum");
2159 goto dropnosock;
2160 }
2161
2162 /* Re-initialization for later version check */
2163 ip->ip_v = IPVERSION;
2164 ip_ecn = (ip->ip_tos & IPTOS_ECN_MASK);
2165
2166 DTRACE_TCP5(receive, struct mbuf *, m, struct inpcb *, NULL,
2167 struct ip *, ip, struct tcpcb *, NULL, struct tcphdr *, th);
2168
2169 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
2170 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
2171 th->th_seq, th->th_ack, th->th_win);
2172 }
2173
2174 #define TCP_LOG_HDR (isipv6 ? (void *)ip6 : (void *)ip)
2175
2176 /*
2177 * Check that TCP offset makes sense,
2178 * pull out TCP options and adjust length.
2179 */
2180 off = th->th_off << 2;
2181 if (off < sizeof(struct tcphdr) || off > tlen) {
2182 tcpstat.tcps_rcvbadoff++;
2183 IF_TCP_STATINC(ifp, badformat);
2184 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "bad tcp offset");
2185 goto dropnosock;
2186 }
2187 tlen -= off; /* tlen is used instead of ti->ti_len */
2188 if (off > sizeof(struct tcphdr)) {
2189 if (isipv6) {
2190 IP6_EXTHDR_CHECK(m, off0, off, return );
2191 ip6 = mtod(m, struct ip6_hdr *);
2192 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
2193 } else {
2194 if (m->m_len < sizeof(struct ip) + off) {
2195 if ((m = m_pullup(m, sizeof(struct ip) + off)) == 0) {
2196 tcpstat.tcps_rcvshort++;
2197 return;
2198 }
2199 ip = mtod(m, struct ip *);
2200 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
2201 }
2202 }
2203 optlen = off - sizeof(struct tcphdr);
2204 optp = (u_char *)(th + 1);
2205 /*
2206 * Do quick retrieval of timestamp options ("options
2207 * prediction?"). If timestamp is the only option and it's
2208 * formatted as recommended in RFC 1323 appendix A, we
2209 * quickly get the values now and not bother calling
2210 * tcp_dooptions(), etc.
2211 */
2212 if ((optlen == TCPOLEN_TSTAMP_APPA ||
2213 (optlen > TCPOLEN_TSTAMP_APPA &&
2214 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
2215 *(u_int32_t *)(void *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
2216 (th->th_flags & TH_SYN) == 0) {
2217 to.to_flags |= TOF_TS;
2218 to.to_tsval = ntohl(*(u_int32_t *)(void *)(optp + 4));
2219 to.to_tsecr = ntohl(*(u_int32_t *)(void *)(optp + 8));
2220 optp = NULL; /* we've parsed the options */
2221 }
2222 }
2223 thflags = th->th_flags;
2224
2225 /*
2226 * Drop all packets with both the SYN and FIN bits set.
2227 * This prevents e.g. nmap from identifying the TCP/IP stack.
2228 *
2229 * This is a violation of the TCP specification.
2230 */
2231 if ((thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN)) {
2232 IF_TCP_STATINC(ifp, synfin);
2233 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "drop SYN FIN");
2234 goto dropnosock;
2235 }
2236
2237 /*
2238 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
2239 * until after ip6_savecontrol() is called and before other functions
2240 * which don't want those proto headers.
2241 * Because ip6_savecontrol() is going to parse the mbuf to
2242 * search for data to be passed up to user-land, it wants mbuf
2243 * parameters to be unchanged.
2244 */
2245 drop_hdrlen = off0 + off;
2246
2247 /* Since this is an entry point for input processing of tcp packets, we
2248 * can update the tcp clock here.
2249 */
2250 calculate_tcp_clock();
2251
2252 /*
2253 * Record the interface where this segment arrived on; this does not
2254 * affect normal data output (for non-detached TCP) as it provides a
2255 * hint about which route and interface to use for sending in the
2256 * absence of a PCB, when scoped routing (and thus source interface
2257 * selection) are enabled.
2258 */
2259 if ((m->m_pkthdr.pkt_flags & PKTF_LOOP) || m->m_pkthdr.rcvif == NULL) {
2260 ifscope = IFSCOPE_NONE;
2261 } else {
2262 ifscope = m->m_pkthdr.rcvif->if_index;
2263 }
2264
2265 /*
2266 * Convert TCP protocol specific fields to host format.
2267 */
2268
2269 #if BYTE_ORDER != BIG_ENDIAN
2270 NTOHL(th->th_seq);
2271 NTOHL(th->th_ack);
2272 NTOHS(th->th_win);
2273 NTOHS(th->th_urp);
2274 is_th_swapped = true;
2275 #endif
2276
2277 /*
2278 * Locate pcb for segment.
2279 */
2280 findpcb:
2281
2282 isconnected = FALSE;
2283 isdisconnected = FALSE;
2284
2285 if (isipv6) {
2286 inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_src, th->th_sport, ip6_input_getsrcifscope(m),
2287 &ip6->ip6_dst, th->th_dport, ip6_input_getdstifscope(m), 1,
2288 m->m_pkthdr.rcvif);
2289 } else {
2290 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
2291 ip->ip_dst, th->th_dport, 1, m->m_pkthdr.rcvif);
2292 }
2293
2294 /*
2295 * Use the interface scope information from the PCB for outbound
2296 * segments. If the PCB isn't present and if scoped routing is
2297 * enabled, tcp_respond will use the scope of the interface where
2298 * the segment arrived on.
2299 */
2300 if (inp != NULL && (inp->inp_flags & INP_BOUND_IF)) {
2301 ifscope = inp->inp_boundifp->if_index;
2302 }
2303
2304 /*
2305 * If the state is CLOSED (i.e., TCB does not exist) then
2306 * all data in the incoming segment is discarded.
2307 * If the TCB exists but is in CLOSED state, it is embryonic,
2308 * but should either do a listen or a connect soon.
2309 */
2310 if (inp == NULL) {
2311 if (log_in_vain) {
2312 char dbuf[MAX_IPv6_STR_LEN], sbuf[MAX_IPv6_STR_LEN];
2313
2314 if (isipv6) {
2315 inet_ntop(AF_INET6, &ip6->ip6_dst, dbuf, sizeof(dbuf));
2316 inet_ntop(AF_INET6, &ip6->ip6_src, sbuf, sizeof(sbuf));
2317 } else {
2318 inet_ntop(AF_INET, &ip->ip_dst, dbuf, sizeof(dbuf));
2319 inet_ntop(AF_INET, &ip->ip_src, sbuf, sizeof(sbuf));
2320 }
2321 switch (log_in_vain) {
2322 case 1:
2323 if (thflags & TH_SYN) {
2324 log(LOG_INFO,
2325 "Connection attempt to TCP %s:%d from %s:%d\n",
2326 dbuf, ntohs(th->th_dport),
2327 sbuf,
2328 ntohs(th->th_sport));
2329 }
2330 break;
2331 case 2:
2332 log(LOG_INFO,
2333 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
2334 dbuf, ntohs(th->th_dport), sbuf,
2335 ntohs(th->th_sport), thflags);
2336 break;
2337 case 3:
2338 case 4:
2339 if ((thflags & TH_SYN) && !(thflags & TH_ACK) &&
2340 !(m->m_flags & (M_BCAST | M_MCAST)) &&
2341 ((isipv6 && !in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) ||
2342 (!isipv6 && ip->ip_dst.s_addr != ip->ip_src.s_addr))) {
2343 log_in_vain_log((LOG_INFO,
2344 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
2345 dbuf, ntohs(th->th_dport),
2346 sbuf,
2347 ntohs(th->th_sport)));
2348 }
2349 break;
2350 default:
2351 break;
2352 }
2353 }
2354 if (blackhole) {
2355 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type != IFT_LOOP) {
2356 switch (blackhole) {
2357 case 1:
2358 if (thflags & TH_SYN) {
2359 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "blackhole 1 syn for closed port");
2360 goto dropnosock;
2361 }
2362 break;
2363 case 2:
2364 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "blackhole 2 closed port");
2365 goto dropnosock;
2366 default:
2367 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "blackhole closed port");
2368 goto dropnosock;
2369 }
2370 }
2371 }
2372 IF_TCP_STATINC(ifp, noconnnolist);
2373 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "closed port");
2374 goto dropwithresetnosock;
2375 }
2376 so = inp->inp_socket;
2377 if (so == NULL) {
2378 /* This case shouldn't happen as the socket shouldn't be null
2379 * if inp_state isn't set to INPCB_STATE_DEAD
2380 * But just in case, we pretend we didn't find the socket if we hit this case
2381 * as this isn't cause for a panic (the socket might be leaked however)...
2382 */
2383 inp = NULL;
2384 #if TEMPDEBUG
2385 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp);
2386 #endif
2387 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "inp_socket NULL");
2388 goto dropnosock;
2389 }
2390
2391 socket_lock(so, 1);
2392 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
2393 socket_unlock(so, 1);
2394 inp = NULL; // pretend we didn't find it
2395 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "inp state WNT_STOPUSING");
2396 goto dropnosock;
2397 }
2398
2399 if (!isipv6 && inp->inp_faddr.s_addr != INADDR_ANY) {
2400 if (inp->inp_faddr.s_addr != ip->ip_src.s_addr ||
2401 inp->inp_laddr.s_addr != ip->ip_dst.s_addr ||
2402 inp->inp_fport != th->th_sport ||
2403 inp->inp_lport != th->th_dport) {
2404 os_log_error(OS_LOG_DEFAULT, "%s 5-tuple does not match: %u:%u %u:%u\n",
2405 __func__,
2406 ntohs(inp->inp_fport), ntohs(th->th_sport),
2407 ntohs(inp->inp_lport), ntohs(th->th_dport));
2408 if (findpcb_iterated) {
2409 goto drop;
2410 }
2411 findpcb_iterated = true;
2412 socket_unlock(so, 1);
2413 inp = NULL;
2414 goto findpcb;
2415 }
2416 } else if (isipv6 && !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
2417 if (!in6_are_addr_equal_scoped(&inp->in6p_faddr, &ip6->ip6_src, inp->inp_fifscope, ip6_input_getsrcifscope(m)) ||
2418 !in6_are_addr_equal_scoped(&inp->in6p_laddr, &ip6->ip6_dst, inp->inp_lifscope, ip6_input_getdstifscope(m)) ||
2419 inp->inp_fport != th->th_sport ||
2420 inp->inp_lport != th->th_dport) {
2421 os_log_error(OS_LOG_DEFAULT, "%s 5-tuple does not match: %u:%u %u:%u\n",
2422 __func__,
2423 ntohs(inp->inp_fport), ntohs(th->th_sport),
2424 ntohs(inp->inp_lport), ntohs(th->th_dport));
2425 if (findpcb_iterated) {
2426 goto drop;
2427 }
2428 findpcb_iterated = true;
2429 socket_unlock(so, 1);
2430 inp = NULL;
2431 goto findpcb;
2432 }
2433 }
2434
2435 tp = intotcpcb(inp);
2436 if (tp == NULL) {
2437 IF_TCP_STATINC(ifp, noconnlist);
2438 TCP_LOG_DROP_PKT(TCP_LOG_HDR, th, ifp, "tp is NULL");
2439 goto dropwithreset;
2440 }
2441
2442 /* Now that we found the tcpcb, we can adjust the TCP timestamp */
2443 if (to.to_flags & TOF_TS) {
2444 to.to_tsecr -= tp->t_ts_offset;
2445 }
2446
2447 if (tp->t_state == TCPS_CLOSED) {
2448 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "tp state TCPS_CLOSED");
2449 goto drop;
2450 }
2451
2452 #if NECP
2453 if (so->so_state & SS_ISCONNECTED) {
2454 // Connected TCP sockets have a fully-bound local and remote,
2455 // so the policy check doesn't need to override addresses
2456 if (!necp_socket_is_allowed_to_send_recv(inp, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
2457 TCP_LOG_DROP_NECP(TCP_LOG_HDR, th, intotcpcb(inp), false);
2458 IF_TCP_STATINC(ifp, badformat);
2459 goto drop;
2460 }
2461 } else {
2462 /*
2463 * If the proc_uuid_policy table has been updated since the last use
2464 * of the listening socket (i.e., the proc_uuid_policy_table_gencount
2465 * has been updated), the flags in the socket may be out of date.
2466 * If INP2_WANT_APP_POLICY is stale, inbound packets may
2467 * be dropped by NECP if the socket should now match a per-app
2468 * exception policy.
2469 * In order to avoid this refresh the proc_uuid_policy state to
2470 * potentially recalculate the socket's flags before checking
2471 * with NECP.
2472 */
2473 (void) inp_update_policy(inp);
2474
2475 if (isipv6) {
2476 if (!necp_socket_is_allowed_to_send_recv_v6(inp,
2477 th->th_dport, th->th_sport, &ip6->ip6_dst,
2478 &ip6->ip6_src, ifp, pf_tag, NULL, NULL, NULL, NULL)) {
2479 TCP_LOG_DROP_NECP(TCP_LOG_HDR, th, intotcpcb(inp), false);
2480 IF_TCP_STATINC(ifp, badformat);
2481 goto drop;
2482 }
2483 } else {
2484 if (!necp_socket_is_allowed_to_send_recv_v4(inp,
2485 th->th_dport, th->th_sport, &ip->ip_dst, &ip->ip_src,
2486 ifp, pf_tag, NULL, NULL, NULL, NULL)) {
2487 TCP_LOG_DROP_NECP(TCP_LOG_HDR, th, intotcpcb(inp), false);
2488 IF_TCP_STATINC(ifp, badformat);
2489 goto drop;
2490 }
2491 }
2492 }
2493 #endif /* NECP */
2494
2495 prev_t_state = tp->t_state;
2496
2497 /* If none of the FIN|SYN|RST|ACK flag is set, drop */
2498 if ((thflags & TH_ACCEPT) == 0) {
2499 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 TH_ACCEPT == 0");
2500 goto drop;
2501 }
2502
2503 /* Initialize highest sacked seq to avoid using 0 as initial value */
2504 highest_sacked_seq = th->th_ack;
2505
2506 /* Unscale the window into a 32-bit value. */
2507 if ((thflags & TH_SYN) == 0) {
2508 tiwin = th->th_win << tp->snd_scale;
2509 } else {
2510 tiwin = th->th_win;
2511 }
2512
2513 /* Avoid processing packets while closing a listen socket */
2514 if (tp->t_state == TCPS_LISTEN &&
2515 (so->so_options & SO_ACCEPTCONN) == 0) {
2516 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "closing a listening socket");
2517 goto drop;
2518 }
2519
2520 if ((m->m_flags & M_PKTHDR) && (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
2521 soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_WAKE_PKT);
2522 }
2523
2524 if (so->so_options & (SO_DEBUG | SO_ACCEPTCONN)) {
2525 if (so->so_options & SO_ACCEPTCONN) {
2526 struct tcpcb *tp0 = tp;
2527 struct socket *so2;
2528 struct socket *oso;
2529 struct sockaddr_storage from;
2530 struct sockaddr_storage to2;
2531 struct inpcb *oinp = sotoinpcb(so);
2532 struct ifnet *head_ifscope;
2533 bool head_nocell, head_recvanyif,
2534 head_noexpensive, head_awdl_unrestricted,
2535 head_intcoproc_allowed, head_external_port,
2536 head_noconstrained, head_management_allowed,
2537 head_ultra_constrained_allowed;
2538
2539 /* Get listener's bound-to-interface, if any */
2540 head_ifscope = (inp->inp_flags & INP_BOUND_IF) ?
2541 inp->inp_boundifp : NULL;
2542 /* Get listener's no-cellular information, if any */
2543 head_nocell = INP_NO_CELLULAR(inp);
2544 /* Get listener's recv-any-interface, if any */
2545 head_recvanyif = (inp->inp_flags & INP_RECV_ANYIF);
2546 /* Get listener's no-expensive information, if any */
2547 head_noexpensive = INP_NO_EXPENSIVE(inp);
2548 head_noconstrained = INP_NO_CONSTRAINED(inp);
2549 head_awdl_unrestricted = INP_AWDL_UNRESTRICTED(inp);
2550 head_intcoproc_allowed = INP_INTCOPROC_ALLOWED(inp);
2551 head_external_port = (inp->inp_flags2 & INP2_EXTERNAL_PORT);
2552 head_management_allowed = INP_MANAGEMENT_ALLOWED(inp);
2553 head_ultra_constrained_allowed = INP_ULTRA_CONSTRAINED_ALLOWED(inp);
2554
2555 /*
2556 * If the state is LISTEN then ignore segment if it contains an RST.
2557 * If the segment contains an ACK then it is bad and send a RST.
2558 * If it does not contain a SYN then it is not interesting; drop it.
2559 * If it is from this socket, drop it, it must be forged.
2560 */
2561 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
2562 IF_TCP_STATINC(ifp, listbadsyn);
2563
2564 if (thflags & TH_RST) {
2565 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false,
2566 thflags & TH_SYN ? "ignore SYN with RST" : "ignore RST");
2567 goto drop;
2568 }
2569 if (thflags & TH_ACK) {
2570 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false,
2571 thflags & TH_SYN ? "bad SYN with ACK" : "bad ACK");
2572 tp = NULL;
2573 tcpstat.tcps_badsyn++;
2574 goto dropwithreset;
2575 }
2576
2577 /* We come here if there is no SYN set */
2578 tcpstat.tcps_badsyn++;
2579 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad SYN");
2580 goto drop;
2581 }
2582 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START, 0, 0, 0, 0, 0);
2583 if (th->th_dport == th->th_sport) {
2584 if (isipv6) {
2585 if (in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) {
2586 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad tuple same port");
2587 goto drop;
2588 }
2589 } else if (ip->ip_dst.s_addr == ip->ip_src.s_addr) {
2590 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad tuple same IPv4 address");
2591 goto drop;
2592 }
2593 }
2594 /*
2595 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2596 * in_broadcast() should never return true on a received
2597 * packet with M_BCAST not set.
2598 *
2599 * Packets with a multicast source address should also
2600 * be discarded.
2601 */
2602 if (m->m_flags & (M_BCAST | M_MCAST)) {
2603 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "mbuf M_BCAST | M_MCAST");
2604 goto drop;
2605 }
2606 if (isipv6) {
2607 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2608 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
2609 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "IN6_IS_ADDR_MULTICAST");
2610 goto drop;
2611 }
2612 } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2613 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2614 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2615 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
2616 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "multicast or broadcast address");
2617 goto drop;
2618 }
2619
2620
2621 /*
2622 * If deprecated address is forbidden,
2623 * we do not accept SYN to deprecated interface
2624 * address to prevent any new inbound connection from
2625 * getting established.
2626 * When we do not accept SYN, we send a TCP RST,
2627 * with deprecated source address (instead of dropping
2628 * it). We compromise it as it is much better for peer
2629 * to send a RST, and RST will be the final packet
2630 * for the exchange.
2631 *
2632 * If we do not forbid deprecated addresses, we accept
2633 * the SYN packet. RFC 4862 forbids dropping SYN in
2634 * this case.
2635 */
2636 if (isipv6 && !ip6_use_deprecated) {
2637 uint32_t ia6_flags;
2638
2639 if (ip6_getdstifaddr_info(m, NULL,
2640 &ia6_flags) == 0) {
2641 if (ia6_flags & IN6_IFF_DEPRECATED) {
2642 tp = NULL;
2643 IF_TCP_STATINC(ifp, deprecate6);
2644 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "deprecated IPv6 address");
2645 goto dropwithreset;
2646 }
2647 }
2648 }
2649 if (so->so_filt || check_cfil) {
2650 if (isipv6) {
2651 struct sockaddr_in6 *sin6 = SIN6(&from);
2652
2653 sin6->sin6_len = sizeof(*sin6);
2654 sin6->sin6_family = AF_INET6;
2655 sin6->sin6_port = th->th_sport;
2656 sin6->sin6_flowinfo = 0;
2657 sin6->sin6_addr = ip6->ip6_src;
2658 sin6->sin6_scope_id = 0;
2659
2660 sin6 = SIN6(&to2);
2661
2662 sin6->sin6_len = sizeof(struct sockaddr_in6);
2663 sin6->sin6_family = AF_INET6;
2664 sin6->sin6_port = th->th_dport;
2665 sin6->sin6_flowinfo = 0;
2666 sin6->sin6_addr = ip6->ip6_dst;
2667 sin6->sin6_scope_id = 0;
2668 } else {
2669 struct sockaddr_in *sin = SIN(&from);
2670
2671 sin->sin_len = sizeof(*sin);
2672 sin->sin_family = AF_INET;
2673 sin->sin_port = th->th_sport;
2674 sin->sin_addr = ip->ip_src;
2675
2676 sin = SIN(&to2);
2677
2678 sin->sin_len = sizeof(struct sockaddr_in);
2679 sin->sin_family = AF_INET;
2680 sin->sin_port = th->th_dport;
2681 sin->sin_addr = ip->ip_dst;
2682 }
2683 }
2684
2685 if (so->so_filt) {
2686 so2 = sonewconn(so, 0, SA(&from));
2687 } else {
2688 so2 = sonewconn(so, 0, NULL);
2689 }
2690 if (so2 == 0) {
2691 tcpstat.tcps_listendrop++;
2692 if (tcp_dropdropablreq(so)) {
2693 if (so->so_filt) {
2694 so2 = sonewconn(so, 0, SA(&from));
2695 } else {
2696 so2 = sonewconn(so, 0, NULL);
2697 }
2698 }
2699 if (!so2) {
2700 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " listen drop");
2701 goto drop;
2702 }
2703 }
2704
2705 /* Point "inp" and "tp" in tandem to new socket */
2706 inp = (struct inpcb *)so2->so_pcb;
2707 tp = intotcpcb(inp);
2708
2709 oso = so;
2710 socket_unlock(so, 0); /* Unlock but keep a reference on listener for now */
2711
2712 so = so2;
2713 socket_lock(so, 1);
2714 /*
2715 * Mark socket as temporary until we're
2716 * committed to keeping it. The code at
2717 * ``drop'' and ``dropwithreset'' check the
2718 * flag dropsocket to see if the temporary
2719 * socket created here should be discarded.
2720 * We mark the socket as discardable until
2721 * we're committed to it below in TCPS_LISTEN.
2722 * There are some error conditions in which we
2723 * have to drop the temporary socket.
2724 */
2725 dropsocket++;
2726 /*
2727 * Inherit INP_BOUND_IF from listener; testing if
2728 * head_ifscope is non-NULL is sufficient, since it
2729 * can only be set to a non-zero value earlier if
2730 * the listener has such a flag set.
2731 */
2732 if (head_ifscope != NULL) {
2733 inp->inp_flags |= INP_BOUND_IF;
2734 inp->inp_boundifp = head_ifscope;
2735 } else {
2736 inp->inp_flags &= ~INP_BOUND_IF;
2737 }
2738 /*
2739 * Inherit restrictions from listener.
2740 */
2741 if (head_nocell) {
2742 inp_set_nocellular(inp);
2743 }
2744 if (head_noexpensive) {
2745 inp_set_noexpensive(inp);
2746 }
2747 if (head_noconstrained) {
2748 inp_set_noconstrained(inp);
2749 }
2750 if (head_awdl_unrestricted) {
2751 inp_set_awdl_unrestricted(inp);
2752 }
2753 if (head_intcoproc_allowed) {
2754 inp_set_intcoproc_allowed(inp);
2755 }
2756 if (head_management_allowed) {
2757 inp_set_management_allowed(inp);
2758 }
2759 if (head_ultra_constrained_allowed) {
2760 inp_set_ultra_constrained_allowed(inp);
2761 }
2762 /*
2763 * Inherit {IN,IN6}_RECV_ANYIF from listener.
2764 */
2765 if (head_recvanyif) {
2766 inp->inp_flags |= INP_RECV_ANYIF;
2767 } else {
2768 inp->inp_flags &= ~INP_RECV_ANYIF;
2769 }
2770
2771 if (head_external_port) {
2772 inp->inp_flags2 |= INP2_EXTERNAL_PORT;
2773 }
2774 if (isipv6) {
2775 inp->in6p_laddr = ip6->ip6_dst;
2776 inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
2777 in6_verify_ifscope(&ip6->ip6_dst, inp->inp_lifscope);
2778 } else {
2779 inp->inp_vflag &= ~INP_IPV6;
2780 inp->inp_vflag |= INP_IPV4;
2781 inp->inp_laddr = ip->ip_dst;
2782 }
2783 inp->inp_lport = th->th_dport;
2784 if (in_pcbinshash(inp, SA(&from), 0) != 0) {
2785 /*
2786 * Undo the assignments above if we failed to
2787 * put the PCB on the hash lists.
2788 */
2789 if (isipv6) {
2790 inp->in6p_laddr = in6addr_any;
2791 inp->inp_lifscope = IFSCOPE_NONE;
2792 } else {
2793 inp->inp_laddr.s_addr = INADDR_ANY;
2794 }
2795 #if SKYWALK
2796 netns_release(&inp->inp_netns_token);
2797 #endif /* SKYWALK */
2798 inp->inp_lport = 0;
2799 socket_lock(oso, 0); /* release ref on parent */
2800 socket_unlock(oso, 1);
2801 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " in_pcbinshash failed");
2802 goto drop;
2803 }
2804 socket_lock(oso, 0);
2805 if (isipv6) {
2806 /*
2807 * Inherit socket options from the listening
2808 * socket.
2809 * Note that in6p_inputopts are not (even
2810 * should not be) copied, since it stores
2811 * previously received options and is used to
2812 * detect if each new option is different than
2813 * the previous one and hence should be passed
2814 * to a user.
2815 * If we copied in6p_inputopts, a user would
2816 * not be able to receive options just after
2817 * calling the accept system call.
2818 */
2819 inp->inp_flags |=
2820 oinp->inp_flags & INP_CONTROLOPTS;
2821 if (oinp->in6p_outputopts) {
2822 inp->in6p_outputopts =
2823 ip6_copypktopts(oinp->in6p_outputopts,
2824 Z_NOWAIT);
2825 }
2826 } else {
2827 inp->inp_options = ip_srcroute();
2828 inp->inp_ip_tos = oinp->inp_ip_tos;
2829 }
2830 #if IPSEC
2831 /* copy old policy into new socket's */
2832 if (sotoinpcb(oso)->inp_sp) {
2833 int error = 0;
2834 /* Is it a security hole here to silently fail to copy the policy? */
2835 if (inp->inp_sp == NULL) {
2836 error = ipsec_init_policy(so, &inp->inp_sp);
2837 }
2838 if (error != 0 || ipsec_copy_policy(sotoinpcb(oso)->inp_sp, inp->inp_sp)) {
2839 printf("tcp_input: could not copy policy\n");
2840 }
2841 }
2842 #endif
2843 /* inherit states from the listener */
2844 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
2845 struct tcpcb *, tp, int32_t, TCPS_LISTEN);
2846 TCP_LOG_STATE(tp, TCPS_LISTEN);
2847 tp->t_state = TCPS_LISTEN;
2848 tp->t_flags |= tp0->t_flags & (TF_NOPUSH | TF_NOOPT | TF_NODELAY);
2849 tp->t_flagsext |= (tp0->t_flagsext & (TF_RXTFINDROP | TF_NOTIMEWAIT | TF_FASTOPEN));
2850 tp->t_keepinit = tp0->t_keepinit;
2851 tp->t_keepcnt = tp0->t_keepcnt;
2852 tp->t_keepintvl = tp0->t_keepintvl;
2853 tp->t_adaptive_wtimo = tp0->t_adaptive_wtimo;
2854 tp->t_adaptive_rtimo = tp0->t_adaptive_rtimo;
2855 tp->t_inpcb->inp_ip_ttl = tp0->t_inpcb->inp_ip_ttl;
2856 if ((so->so_flags & SOF_NOTSENT_LOWAT) != 0) {
2857 tp->t_notsent_lowat = tp0->t_notsent_lowat;
2858 }
2859 tp->t_inpcb->inp_flags2 |=
2860 tp0->t_inpcb->inp_flags2 & INP2_KEEPALIVE_OFFLOAD;
2861
2862 /* now drop the reference on the listener */
2863 socket_unlock(oso, 1);
2864
2865 tcp_set_max_rwinscale(tp, so);
2866
2867 #if CONTENT_FILTER
2868 if (check_cfil) {
2869 int error = cfil_sock_attach(so2, SA(&to2), SA(&from), CFS_CONNECTION_DIR_IN);
2870 if (error != 0) {
2871 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " cfil_sock_attach failed");
2872 goto drop;
2873 }
2874 }
2875 #endif /* CONTENT_FILTER */
2876
2877 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END, 0, 0, 0, 0, 0);
2878 }
2879 }
2880 socket_lock_assert_owned(so);
2881
2882 /*
2883 * Packet accounting should not be done on listening socket
2884 */
2885 if (th->th_flags & TH_SYN) {
2886 (void) os_add_overflow(1, tp->t_syn_rcvd, &tp->t_syn_rcvd);
2887 }
2888 if (th->th_flags & TH_FIN) {
2889 (void) os_add_overflow(1, tp->t_fin_rcvd, &tp->t_fin_rcvd);
2890 }
2891 if (th->th_flags & TH_RST) {
2892 (void) os_add_overflow(1, tp->t_rst_rcvd, &tp->t_rst_rcvd);
2893 }
2894 TCP_LOG_TH_FLAGS(TCP_LOG_HDR, th, tp, false, ifp);
2895
2896 if (net_mpklog_enabled && (m->m_pkthdr.rcvif->if_xflags & IFXF_MPK_LOG)) {
2897 MPKL_TCP_INPUT(tcp_mpkl_log_object,
2898 ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
2899 th->th_seq, th->th_ack, tlen, thflags,
2900 so->last_pid, so->so_log_seqn++);
2901 }
2902
2903 if (tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
2904 /*
2905 * Evaluate the rate of arrival of packets to see if the
2906 * receiver can reduce the ack traffic. The algorithm to
2907 * stretch acks will be enabled if the connection meets
2908 * certain criteria defined in tcp_stretch_ack_enable function.
2909 */
2910 if ((tp->t_flagsext & TF_RCVUNACK_WAITSS) != 0) {
2911 TCP_INC_VAR(tp->rcv_waitforss, segment_count);
2912 }
2913 if (tcp_stretch_ack_enable(tp, thflags)) {
2914 tp->t_flags |= TF_STRETCHACK;
2915 tp->t_flagsext &= ~(TF_RCVUNACK_WAITSS);
2916 tp->rcv_waitforss = 0;
2917 } else {
2918 tp->t_flags &= ~(TF_STRETCHACK);
2919 }
2920 if (TSTMP_GT(tp->rcv_unackwin - (tcp_rcvunackwin >> 1), tcp_now)) {
2921 tp->rcv_by_unackhalfwin += (tlen + off);
2922 tp->rcv_by_unackwin += (tlen + off);
2923 } else {
2924 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
2925 tp->rcv_by_unackwin = tp->rcv_by_unackhalfwin + tlen + off;
2926 tp->rcv_by_unackhalfwin = tlen + off;
2927 }
2928 }
2929
2930 if (TCP_L4S_ENABLED(tp) && TCP_ACC_ECN_ON(tp)) {
2931 /* Reset the state used for AccECN processing */
2932 tp->t_aecn.accecn_processed = 0;
2933 }
2934
2935 if (tp->t_state == TCPS_ESTABLISHED && BYTES_ACKED(th, tp) > 0) {
2936 if (CC_ALGO(tp)->set_bytes_acked != NULL) {
2937 CC_ALGO(tp)->set_bytes_acked(tp, BYTES_ACKED(th, tp));
2938 }
2939 if (tp->ecn_flags & TE_SENDIPECT) {
2940 /*
2941 * Data sent with ECT has been acknowledged, calculate
2942 * packets approx. by dividing by MSS. This is done to
2943 * count MSS sized packets in case packets are aggregated
2944 * by GRO/LRO.
2945 */
2946 uint32_t bytes_acked = tcp_round_to(BYTES_ACKED(th, tp), tp->t_maxseg);
2947 tp->t_ecn_capable_packets_acked += max(1, (bytes_acked / tp->t_maxseg));
2948 }
2949 }
2950
2951 /* Accurate ECN has different semantics for TH_CWR. */
2952 if (!TCP_ACC_ECN_ENABLED(tp)) {
2953 /*
2954 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2955 * bother doing extensive checks for state and whatnot.
2956 */
2957 if (thflags & TH_CWR) {
2958 tp->ecn_flags &= ~TE_SENDECE;
2959 tp->t_ecn_recv_cwr++;
2960 }
2961 }
2962
2963 /*
2964 * Accurate ECN feedback for Data Receiver,
2965 * Process IP ECN bits and update r.cep for CE marked pure ACKs
2966 * or valid data packets
2967 */
2968 uint8_t ace = tcp_get_ace(th);
2969 if (TCP_ACC_ECN_ON(tp) && tp->t_state == TCPS_ESTABLISHED) {
2970 /* Update receive side counters */
2971 if (tlen == 0 || (tlen > 0 &&
2972 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2973 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd))) {
2974 tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
2975 }
2976
2977 /* Test for ACE bleaching, initial value of ace should be non-zero */
2978 if (th->th_seq == tp->iss + 1 && ace == 0) {
2979 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_ace_bleaching_detected;
2980 }
2981 } else {
2982 /*
2983 * Explicit Congestion Notification - Flag that we need to send ECE if
2984 * + The IP Congestion experienced flag was set.
2985 * + Socket is in established state
2986 * + We negotiated ECN in the TCP setup
2987 * + This isn't a pure ack (tlen > 0)
2988 * + The data is in the valid window
2989 *
2990 * TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2991 */
2992 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2993 TCP_ECN_ENABLED(tp) && tlen > 0 &&
2994 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2995 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2996 tp->t_ecn_recv_ce++;
2997 tcpstat.tcps_ecn_recv_ce++;
2998 INP_INC_IFNET_STAT(inp, ecn_recv_ce);
2999 /* Mark this connection as it received CE from network */
3000 tp->ecn_flags |= TE_RECV_ECN_CE;
3001 tp->ecn_flags |= TE_SENDECE;
3002 }
3003 }
3004
3005 /*
3006 * If we received an explicit notification of congestion in
3007 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
3008 * the ack-stretching state. We need to handle ECN notification if
3009 * an ECN setup SYN was sent even once.
3010 */
3011 if (tp->t_state == TCPS_ESTABLISHED &&
3012 (tp->ecn_flags & TE_SETUPSENT) &&
3013 (ip_ecn == IPTOS_ECN_CE || (thflags & TH_CWR))) {
3014 tcp_reset_stretch_ack(tp);
3015 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
3016 CLEAR_IAJ_STATE(tp);
3017 }
3018
3019 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
3020 !TCP_ECN_ENABLED(tp) && !(tp->ecn_flags & TE_CEHEURI_SET)) {
3021 tcpstat.tcps_ecn_fallback_ce++;
3022 tcp_heuristic_ecn_aggressive(tp);
3023 tp->ecn_flags |= TE_CEHEURI_SET;
3024 }
3025
3026 if (tp->t_state == TCPS_ESTABLISHED && TCP_ECN_ENABLED(tp) &&
3027 ip_ecn == IPTOS_ECN_CE && !(tp->ecn_flags & TE_CEHEURI_SET)) {
3028 if (inp->inp_stat->rxpackets < ECN_MIN_CE_PROBES) {
3029 tp->t_ecn_recv_ce_pkt++;
3030 } else if (tp->t_ecn_recv_ce_pkt > ECN_MAX_CE_RATIO) {
3031 tcpstat.tcps_ecn_fallback_ce++;
3032 tcp_heuristic_ecn_aggressive(tp);
3033 tp->ecn_flags |= TE_CEHEURI_SET;
3034 INP_INC_IFNET_STAT(inp, ecn_fallback_ce);
3035 } else {
3036 /* We tracked the first ECN_MIN_CE_PROBES segments, we
3037 * now know that the path is good.
3038 */
3039 tp->ecn_flags |= TE_CEHEURI_SET;
3040 }
3041 }
3042
3043 /* Update rcvtime as a new segment was received on the connection */
3044 tp->t_rcvtime = tcp_now;
3045
3046 /*
3047 * Segment received on connection.
3048 * Reset idle time and keep-alive timer.
3049 */
3050 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3051 tcp_keepalive_reset(tp);
3052
3053 if (tp->t_mpsub) {
3054 mptcp_reset_keepalive(tp);
3055 }
3056 }
3057
3058 /*
3059 * Process options if not in LISTEN state,
3060 * else do it below (after getting remote address).
3061 */
3062 if (tp->t_state != TCPS_LISTEN && optp) {
3063 tcp_dooptions(tp, optp, optlen, th, &to);
3064 }
3065 #if MPTCP
3066 if (tp->t_state != TCPS_LISTEN && (so->so_flags & SOF_MP_SUBFLOW)) {
3067 mptcp_insert_rmap(tp, m, th);
3068 }
3069 #endif /* MPTCP */
3070 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
3071 if (!(thflags & TH_ACK) ||
3072 (SEQ_GT(th->th_ack, tp->iss) &&
3073 SEQ_LEQ(th->th_ack, tp->snd_max))) {
3074 tcp_finalize_options(tp, &to, ifscope);
3075 }
3076 }
3077
3078 #if TRAFFIC_MGT
3079 /*
3080 * Compute inter-packet arrival jitter. According to RFC 3550,
3081 * inter-packet arrival jitter is defined as the difference in
3082 * packet spacing at the receiver compared to the sender for a
3083 * pair of packets. When two packets of maximum segment size come
3084 * one after the other with consecutive sequence numbers, we
3085 * consider them as packets sent together at the sender and use
3086 * them as a pair to compute inter-packet arrival jitter. This
3087 * metric indicates the delay induced by the network components due
3088 * to queuing in edge/access routers.
3089 */
3090 if (tp->t_state == TCPS_ESTABLISHED &&
3091 (thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK | TH_ECE | TH_PUSH)) == TH_ACK &&
3092 ((tp->t_flags & TF_NEEDFIN) == 0) &&
3093 ((to.to_flags & TOF_TS) == 0 ||
3094 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
3095 th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
3096 int seg_size = tlen;
3097 if (tp->iaj_pktcnt <= IAJ_IGNORE_PKTCNT) {
3098 TCP_INC_VAR(tp->iaj_pktcnt, segment_count);
3099 }
3100
3101 if (tp->iaj_size == 0 || seg_size > tp->iaj_size ||
3102 (seg_size == tp->iaj_size && tp->iaj_rcv_ts == 0)) {
3103 /*
3104 * State related to inter-arrival jitter is
3105 * uninitialized or we are trying to find a good
3106 * first packet to start computing the metric
3107 */
3108 update_iaj_state(tp, seg_size, 0);
3109 } else {
3110 if (seg_size == tp->iaj_size) {
3111 /*
3112 * Compute inter-arrival jitter taking
3113 * this packet as the second packet
3114 */
3115 compute_iaj(tp);
3116 }
3117 if (seg_size < tp->iaj_size) {
3118 /*
3119 * There is a smaller packet in the stream.
3120 * Some times the maximum size supported
3121 * on a path can change if there is a new
3122 * link with smaller MTU. The receiver will
3123 * not know about this change. If there
3124 * are too many packets smaller than
3125 * iaj_size, we try to learn the iaj_size
3126 * again.
3127 */
3128 TCP_INC_VAR(tp->iaj_small_pkt, segment_count);
3129 if (tp->iaj_small_pkt > RESET_IAJ_SIZE_THRESH) {
3130 update_iaj_state(tp, seg_size, 1);
3131 } else {
3132 CLEAR_IAJ_STATE(tp);
3133 }
3134 } else {
3135 update_iaj_state(tp, seg_size, 0);
3136 }
3137 }
3138 } else {
3139 CLEAR_IAJ_STATE(tp);
3140 }
3141 #endif /* TRAFFIC_MGT */
3142
3143 /*
3144 * Header prediction: check for the two common cases
3145 * of a uni-directional data xfer. If the packet has
3146 * no control flags, is in-sequence, the window didn't
3147 * change and we're not retransmitting, it's a
3148 * candidate. If the length is zero and the ack moved
3149 * forward, we're the sender side of the xfer. Just
3150 * free the data acked & wake any higher level process
3151 * that was blocked waiting for space. If the length
3152 * is non-zero and the ack didn't move, we're the
3153 * receiver side. If we're getting packets in-order
3154 * (the reassembly queue is empty), add the data to
3155 * the socket buffer and note that we need a delayed ack.
3156 * Make sure that the hidden state-flags are also off.
3157 * Since we check for TCPS_ESTABLISHED above, it can only
3158 * be TH_NEEDSYN.
3159 */
3160 if (tp->t_state == TCPS_ESTABLISHED &&
3161 !(so->so_state & SS_CANTRCVMORE) &&
3162 (thflags & TH_FLAGS) == TH_ACK &&
3163 ((tp->t_flags & TF_NEEDFIN) == 0) &&
3164 ((to.to_flags & TOF_TS) == 0 ||
3165 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
3166 th->th_seq == tp->rcv_nxt &&
3167 tiwin && tiwin == tp->snd_wnd &&
3168 tp->snd_nxt == tp->snd_max) {
3169 /*
3170 * If last ACK falls within this segment's sequence numbers,
3171 * record the timestamp.
3172 * NOTE that the test is modified according to the latest
3173 * proposal of the [email protected] list (Braden 1993/04/26).
3174 */
3175 if ((to.to_flags & TOF_TS) != 0 &&
3176 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
3177 tp->ts_recent_age = tcp_now;
3178 tp->ts_recent = to.to_tsval;
3179 }
3180
3181 /*
3182 * We increment t_unacksegs_ce for both data segments
3183 * and pure ACKs for Accurate ECN
3184 */
3185 if (TCP_ACC_ECN_ON(tp) && ip_ecn == IPTOS_ECN_CE) {
3186 TCP_INC_VAR(tp->t_unacksegs_ce, segment_count);
3187 }
3188
3189 if (tlen == 0) {
3190 if (SEQ_GT(th->th_ack, tp->snd_una) &&
3191 SEQ_LEQ(th->th_ack, tp->snd_max) &&
3192 tp->snd_cwnd >= tp->snd_ssthresh &&
3193 (!IN_FASTRECOVERY(tp) &&
3194 ((!(SACK_ENABLED(tp)) &&
3195 tp->t_dupacks < tp->t_rexmtthresh) ||
3196 (SACK_ENABLED(tp) && to.to_nsacks == 0 &&
3197 TAILQ_EMPTY(&tp->snd_holes))))) {
3198 /*
3199 * this is a pure ack for outstanding data.
3200 */
3201 ++tcpstat.tcps_predack;
3202
3203 tcp_bad_rexmt_check(tp, th, &to);
3204
3205 /* Recalculate the RTT */
3206 tcp_compute_rtt(tp, &to, th);
3207
3208 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
3209 acked = BYTES_ACKED(th, tp);
3210 tcpstat.tcps_rcvackpack++;
3211 tcpstat.tcps_rcvackbyte += acked;
3212
3213 /* TE_SENDIPECT is only set when L4S sysctl is enabled */
3214 if (TCP_ACC_ECN_ON(tp) && (tp->ecn_flags & TE_SENDIPECT)) {
3215 if (!TCP_L4S_ENABLED(tp)) {
3216 os_log_error(OS_LOG_DEFAULT, "TE_SENDIPECT flag is set but TCP_L4S_ENABLED is not");
3217 }
3218 uint32_t pkts_acked = tcp_packets_this_ack(tp, acked);
3219 tp->total_ect_packets_acked += pkts_acked;
3220
3221 bool newly_acked_time = false;
3222 if (acked == 0 && (to.to_flags & TOF_TS) != 0 && to.to_tsecr != 0 &&
3223 TSTMP_GT(to.to_tsecr, tp->t_last_ack_tsecr)) {
3224 newly_acked_time = true;
3225 }
3226 if (acked > 0 || newly_acked_time) {
3227 tcp_process_accecn(tp, &to, th, pkts_acked, ace);
3228 }
3229 }
3230
3231 /*
3232 * Process sent segments used for RACK, called after RTT is computed
3233 * RACK reordering window doesn't need to be updated until we process
3234 * DSACK.
3235 */
3236 if (TCP_RACK_ENABLED(tp)) {
3237 tcp_segs_doack(tp, th->th_ack, &to);
3238 if (SEQ_LT(tp->snd_fack, th->th_ack)) {
3239 /*
3240 * We update snd_fack here for RACK only as it is updated
3241 * and used differently for SACK. This should be done after
3242 * ACK processing of segments which checks for reordering.
3243 * Also, we don't compare with highest_sacked_seq here as this
3244 * is the fast path with no SACK blocks.
3245 */
3246 tp->snd_fack = th->th_ack;
3247 }
3248 }
3249
3250 /*
3251 * Handle an ack that is in sequence during
3252 * congestion avoidance phase. The
3253 * calculations in this function
3254 * assume that snd_una is not updated yet.
3255 */
3256 if (CC_ALGO(tp)->congestion_avd != NULL) {
3257 CC_ALGO(tp)->congestion_avd(tp, th);
3258 }
3259 tcp_ccdbg_trace(tp, th, TCP_CC_INSEQ_ACK_RCVD);
3260 sbdrop(&so->so_snd, acked);
3261 tcp_sbsnd_trim(&so->so_snd);
3262
3263 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
3264 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
3265 tp->snd_recover = th->th_ack - 1;
3266 }
3267
3268 tcp_update_snd_una(tp, th->th_ack);
3269
3270 TCP_RESET_REXMT_STATE(tp);
3271
3272 /*
3273 * pull snd_wl2 up to prevent seq wrap relative
3274 * to th_ack.
3275 */
3276 tp->snd_wl2 = th->th_ack;
3277
3278 if (tp->t_dupacks > 0) {
3279 tp->t_dupacks = 0;
3280 tp->t_rexmtthresh = tcprexmtthresh;
3281 }
3282
3283 tp->sackhint.sack_bytes_acked = 0;
3284
3285 /*
3286 * If all outstanding data are acked, stop
3287 * retransmit timer, otherwise restart timer
3288 * using current (possibly backed-off) value.
3289 * If process is waiting for space,
3290 * wakeup/selwakeup/signal. If data
3291 * are ready to send, let tcp_output
3292 * decide between more output or persist.
3293 */
3294 if (tp->snd_una == tp->snd_max) {
3295 tp->t_timer[TCPT_REXMT] = 0;
3296 tp->t_timer[TCPT_PTO] = 0;
3297 tp->t_timer[TCPT_REORDER] = 0;
3298 tcp_rack_reset_segs_retransmitted(tp);
3299 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
3300 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
3301 }
3302 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
3303 !TCP_DSACK_SEQ_IN_WINDOW(tp,
3304 tp->t_dsack_lastuna, tp->snd_una)) {
3305 tcp_rxtseg_clean(tp);
3306 }
3307
3308 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
3309 tp->t_bwmeas != NULL) {
3310 tcp_bwmeas_check(tp);
3311 }
3312
3313 write_wakeup = 1;
3314 if (!SLIST_EMPTY(&tp->t_notify_ack)) {
3315 tcp_notify_acknowledgement(tp, so);
3316 }
3317
3318 if ((so->so_snd.sb_cc) || (tp->t_flags & TF_ACKNOW)) {
3319 (void) tcp_output(tp);
3320 }
3321
3322 tcp_tfo_rcv_ack(tp, th);
3323
3324 m_freem(m);
3325
3326 tcp_check_timer_state(tp);
3327
3328 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3329
3330 socket_unlock(so, 1);
3331 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3332 return;
3333 }
3334 } else if (th->th_ack == tp->snd_una && LIST_EMPTY(&tp->t_segq) &&
3335 tlen <= tcp_sbspace(tp)) {
3336 /*
3337 * this is a pure, in-sequence data packet
3338 * with nothing on the reassembly queue and
3339 * we have enough buffer space to take it.
3340 */
3341
3342 /* Clean receiver SACK report if present */
3343 if (SACK_ENABLED(tp) && tp->rcv_numsacks) {
3344 tcp_clean_sackreport(tp);
3345 }
3346 ++tcpstat.tcps_preddat;
3347 tp->rcv_nxt += tlen;
3348 /* Update highest received sequence and its timestamp */
3349 if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
3350 tp->rcv_high = tp->rcv_nxt;
3351 if (to.to_flags & TOF_TS) {
3352 tp->tsv_high = to.to_tsval;
3353 }
3354 }
3355
3356 /*
3357 * Pull snd_wl1 up to prevent seq wrap relative to
3358 * th_seq.
3359 */
3360 tp->snd_wl1 = th->th_seq;
3361 /*
3362 * Pull rcv_up up to prevent seq wrap relative to
3363 * rcv_nxt.
3364 */
3365 tp->rcv_up = tp->rcv_nxt;
3366 TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
3367 tcpstat.tcps_rcvbyte += tlen;
3368 if (nstat_collect) {
3369 INP_ADD_STAT(inp, ifnet_count_type,
3370 rxpackets, 1);
3371 INP_ADD_STAT(inp, ifnet_count_type, rxbytes,
3372 tlen);
3373 inp_set_activity_bitmap(inp);
3374 }
3375
3376 /* Calculate the RTT on the receiver */
3377 tcp_compute_rcv_rtt(tp, &to, th);
3378
3379 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
3380 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.data_rcvd != NULL) {
3381 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
3382 }
3383
3384 /*
3385 * Add data to socket buffer.
3386 */
3387 so_recv_data_stat(so, m, 0);
3388 m_adj(m, drop_hdrlen); /* delayed header drop */
3389
3390 if (isipv6) {
3391 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
3392 ip6 = (struct ip6_hdr *)&saved_hdr[0];
3393 } else {
3394 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
3395 ip = (struct ip *)&saved_hdr[0];
3396 }
3397 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
3398
3399 if (th->th_flags & TH_PUSH) {
3400 tp->t_flagsext |= TF_LAST_IS_PSH;
3401 } else {
3402 tp->t_flagsext &= ~TF_LAST_IS_PSH;
3403 }
3404
3405 if (sbappendstream_rcvdemux(so, m)) {
3406 mptcp_handle_input(so);
3407 read_wakeup = 1;
3408 }
3409 th = &saved_tcphdr;
3410
3411 if (isipv6) {
3412 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3413 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
3414 th->th_seq, th->th_ack, th->th_win);
3415 } else {
3416 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3417 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
3418 th->th_seq, th->th_ack, th->th_win);
3419 }
3420 TCP_INC_VAR(tp->t_unacksegs, segment_count);
3421 if (DELAY_ACK(tp, th)) {
3422 if ((tp->t_flags & TF_DELACK) == 0) {
3423 tp->t_flags |= TF_DELACK;
3424 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3425 }
3426 } else {
3427 tp->t_flags |= TF_ACKNOW;
3428 tcp_output(tp);
3429 }
3430
3431 tcp_adaptive_rwtimo_check(tp, tlen);
3432
3433 if (tlen > 0) {
3434 tcp_tfo_rcv_data(tp);
3435 }
3436
3437 tcp_check_timer_state(tp);
3438
3439 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3440
3441 socket_unlock(so, 1);
3442 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3443 return;
3444 }
3445 }
3446
3447 /*
3448 * Calculate amount of space in receive window,
3449 * and then do TCP input processing.
3450 * Receive window is amount of space in rcv queue,
3451 * but not less than advertised window.
3452 */
3453 socket_lock_assert_owned(so);
3454 win = tcp_sbspace(tp);
3455 if (win < 0) {
3456 win = 0;
3457 } else { /* clip rcv window to 4K for modems */
3458 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
3459 win = min(win, slowlink_wsize);
3460 }
3461 }
3462 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
3463 #if MPTCP
3464 /*
3465 * Ensure that the subflow receive window isn't greater
3466 * than the connection level receive window.
3467 */
3468 if ((tp->t_mpflags & TMPF_MPTCP_TRUE) && (mp_tp = tptomptp(tp))) {
3469 socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
3470 int64_t recwin_conn = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
3471
3472 VERIFY(recwin_conn < INT32_MAX && recwin_conn > INT32_MIN);
3473 if (recwin_conn > 0 && tp->rcv_wnd > (uint32_t)recwin_conn) {
3474 tp->rcv_wnd = (uint32_t)recwin_conn;
3475 tcpstat.tcps_mp_reducedwin++;
3476 }
3477 }
3478 #endif /* MPTCP */
3479
3480 switch (tp->t_state) {
3481 /*
3482 * Initialize tp->rcv_nxt, and tp->irs, select an initial
3483 * tp->iss, and send a segment:
3484 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3485 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3486 * Fill in remote peer address fields if not previously specified.
3487 * Enter SYN_RECEIVED state, and process any other fields of this
3488 * segment in this state.
3489 */
3490 case TCPS_LISTEN: {
3491 struct sockaddr_in *sin;
3492 struct sockaddr_in6 *sin6;
3493
3494 socket_lock_assert_owned(so);
3495
3496 /* Clear the logging flags inherited from the listening socket */
3497 inp->inp_log_flags = 0;
3498 inp->inp_flags2 |= INP2_LOGGED_SUMMARY;
3499
3500 if (isipv6) {
3501 sin6 = kalloc_type(struct sockaddr_in6, Z_NOWAIT | Z_ZERO);
3502 if (sin6 == NULL) {
3503 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3504 goto drop;
3505 }
3506 sin6->sin6_family = AF_INET6;
3507 sin6->sin6_len = sizeof(*sin6);
3508 sin6->sin6_addr = ip6->ip6_src;
3509 sin6->sin6_port = th->th_sport;
3510 if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3511 sin6->sin6_scope_id = ip6_input_getsrcifscope(m);
3512 }
3513 laddr6 = inp->in6p_laddr;
3514 uint32_t lifscope = inp->inp_lifscope;
3515 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
3516 inp->in6p_laddr = ip6->ip6_dst;
3517 inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
3518 in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3519 }
3520 if (in6_pcbconnect(inp, SA(sin6), kernel_proc)) {
3521 inp->in6p_laddr = laddr6;
3522 kfree_type(struct sockaddr_in6, sin6);
3523 inp->inp_lifscope = lifscope;
3524 in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3525 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in6_pcbconnect failed");
3526 goto drop;
3527 }
3528 kfree_type(struct sockaddr_in6, sin6);
3529 } else {
3530 socket_lock_assert_owned(so);
3531 sin = kalloc_type(struct sockaddr_in, Z_NOWAIT);
3532 if (sin == NULL) {
3533 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3534 goto drop;
3535 }
3536 sin->sin_family = AF_INET;
3537 sin->sin_len = sizeof(*sin);
3538 sin->sin_addr = ip->ip_src;
3539 sin->sin_port = th->th_sport;
3540 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
3541 laddr = inp->inp_laddr;
3542 if (inp->inp_laddr.s_addr == INADDR_ANY) {
3543 inp->inp_laddr = ip->ip_dst;
3544 }
3545 if (in_pcbconnect(inp, SA(sin), kernel_proc, IFSCOPE_NONE, NULL)) {
3546 inp->inp_laddr = laddr;
3547 kfree_type(struct sockaddr_in, sin);
3548 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in_pcbconnect failed");
3549 goto drop;
3550 }
3551 kfree_type(struct sockaddr_in, sin);
3552 }
3553
3554 tcp_dooptions(tp, optp, optlen, th, &to);
3555 tcp_finalize_options(tp, &to, ifscope);
3556
3557 if (TFO_ENABLED(tp) && tcp_tfo_syn(tp, &to)) {
3558 isconnected = TRUE;
3559 }
3560
3561 if (iss) {
3562 tp->iss = iss;
3563 } else {
3564 tp->iss = tcp_new_isn(tp);
3565 }
3566 tp->irs = th->th_seq;
3567 tcp_sendseqinit(tp);
3568 tcp_rcvseqinit(tp);
3569 tp->snd_recover = tp->snd_una;
3570 /*
3571 * Initialization of the tcpcb for transaction;
3572 * set SND.WND = SEG.WND,
3573 * initialize CCsend and CCrecv.
3574 */
3575 tp->snd_wnd = tiwin; /* initial send-window */
3576 tp->max_sndwnd = tp->snd_wnd;
3577 tp->t_flags |= TF_ACKNOW;
3578 tp->t_unacksegs = 0;
3579 tp->t_unacksegs_ce = 0;
3580 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3581 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
3582 TCP_LOG_STATE(tp, TCPS_SYN_RECEIVED);
3583 tp->t_state = TCPS_SYN_RECEIVED;
3584 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
3585 TCP_CONN_KEEPINIT(tp));
3586 tp->t_connect_time = tcp_now;
3587 dropsocket = 0; /* committed to socket */
3588
3589 if (inp->inp_flowhash == 0) {
3590 inp_calc_flowhash(inp);
3591 ASSERT(inp->inp_flowhash != 0);
3592 }
3593 /* update flowinfo - RFC 6437 */
3594 if (inp->inp_flow == 0 &&
3595 inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
3596 inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
3597 inp->inp_flow |=
3598 (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
3599 }
3600
3601 /* reset the incomp processing flag */
3602 so->so_flags &= ~(SOF_INCOMP_INPROGRESS);
3603 tcpstat.tcps_accepts++;
3604
3605 int ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3606 tcp_input_process_accecn_syn(tp, ace_flags, ip_ecn);
3607
3608 /*
3609 * The address and connection state are finalized
3610 */
3611 TCP_LOG_CONNECT(tp, false, 0);
3612
3613 tcp_add_fsw_flow(tp, ifp);
3614
3615 goto trimthenstep6;
3616 }
3617
3618 /*
3619 * If the state is SYN_RECEIVED and the seg contains an ACK,
3620 * but not for our SYN/ACK, send a RST.
3621 */
3622 case TCPS_SYN_RECEIVED:
3623 if ((thflags & TH_ACK) &&
3624 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
3625 SEQ_GT(th->th_ack, tp->snd_max))) {
3626 IF_TCP_STATINC(ifp, ooopacket);
3627 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad ACK");
3628 goto dropwithreset;
3629 }
3630
3631 /*
3632 * In SYN_RECEIVED state, if we recv some SYNS with
3633 * window scale and others without, window scaling should
3634 * be disabled. Otherwise the window advertised will be
3635 * lower if we assume scaling and the other end does not.
3636 */
3637 if ((thflags & TH_SYN) &&
3638 (tp->irs == th->th_seq) &&
3639 !(to.to_flags & TOF_SCALE)) {
3640 tp->t_flags &= ~TF_RCVD_SCALE;
3641 }
3642 break;
3643
3644 /*
3645 * If the state is SYN_SENT:
3646 * if seg contains an ACK, but not for our SYN, drop the input.
3647 * if seg contains a RST, then drop the connection.
3648 * if seg does not contain SYN, then drop it.
3649 * Otherwise this is an acceptable SYN segment
3650 * initialize tp->rcv_nxt and tp->irs
3651 * if seg contains ack then advance tp->snd_una
3652 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3653 * arrange for segment to be acked (eventually)
3654 * continue processing rest of data/controls, beginning with URG
3655 */
3656 case TCPS_SYN_SENT:
3657 if ((thflags & TH_ACK) &&
3658 (SEQ_LEQ(th->th_ack, tp->iss) ||
3659 SEQ_GT(th->th_ack, tp->snd_max))) {
3660 IF_TCP_STATINC(ifp, ooopacket);
3661 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT bad ACK");
3662 goto dropwithreset;
3663 }
3664 if (thflags & TH_RST) {
3665 if ((thflags & TH_ACK) != 0) {
3666 if (TFO_ENABLED(tp) &&
3667 !(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE)) {
3668 tcp_heuristic_tfo_rst(tp);
3669 }
3670 if ((tp->ecn_flags & (TE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_SETUPSENT ||
3671 (tp->ecn_flags & (TE_ACE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_ACE_SETUPSENT) {
3672 /*
3673 * On local connections, send
3674 * non-ECN syn one time before
3675 * dropping the connection
3676 */
3677 if (tp->t_flags & TF_LOCAL) {
3678 tp->ecn_flags |= TE_RCVD_SYN_RST;
3679 drop_reason = DROP_REASON_TCP_RST;
3680 goto drop;
3681 } else {
3682 tcp_heuristic_ecn_synrst(tp);
3683 }
3684 }
3685 soevent(so,
3686 (SO_FILT_HINT_LOCKED |
3687 SO_FILT_HINT_CONNRESET));
3688 tp = tcp_drop(tp, ECONNREFUSED);
3689 }
3690 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT got RST");
3691 drop_reason = DROP_REASON_TCP_RST;
3692 goto drop;
3693 }
3694 if ((thflags & TH_SYN) == 0) {
3695 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT no SYN");
3696 goto drop;
3697 }
3698 tp->snd_wnd = th->th_win; /* initial send window */
3699 tp->max_sndwnd = tp->snd_wnd;
3700
3701 tp->irs = th->th_seq;
3702 tcp_rcvseqinit(tp);
3703 if (thflags & TH_ACK) {
3704 /* Client processes SYN-ACK */
3705 tcpstat.tcps_connects++;
3706
3707 const uint32_t ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3708
3709 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE)) {
3710 /* Receiving Any|0|1 is classic ECN-setup SYN-ACK */
3711 tp->ecn_flags |= TE_SETUPRECEIVED;
3712 if (TCP_ECN_ENABLED(tp)) {
3713 tcp_heuristic_ecn_success(tp);
3714 tcpstat.tcps_ecn_client_success++;
3715 }
3716
3717 if (tp->ecn_flags & TE_ACE_SETUPSENT) {
3718 /*
3719 * Sent AccECN SYN but received classic ECN SYN-ACK
3720 * Set classic ECN related flags
3721 */
3722 tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
3723 tp->ecn_flags &= ~TE_ACE_SETUPSENT;
3724 if (tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_enabled) {
3725 tp->t_client_accecn_state = tcp_connection_client_classic_ecn_available;
3726 }
3727 }
3728 } else if (TCP_ACC_ECN_ENABLED(tp) && ace_flags != 0 &&
3729 ace_flags != TH_ACE) {
3730 /* Initialize sender side packet & byte counters */
3731 tp->t_aecn.t_snd_ce_packets = 5;
3732 tp->t_aecn.t_snd_ect1_bytes = tp->t_aecn.t_snd_ect0_bytes = 1;
3733 tp->t_aecn.t_snd_ce_bytes = 0;
3734 tp->ecn_flags |= TE_ACE_FINAL_ACK_3WHS;
3735 /*
3736 * Client received AccECN SYN-ACK that reflects the state (ECN)
3737 * in which SYN packet was delivered. This helps to detect if
3738 * there was mangling of the SYN packet on the path. Currently, we
3739 * only send Not-ECT on SYN packets. So, we should set Not-ECT in
3740 * all packets if we receive any encoding other than 0|TH_CWR|0.
3741 * If 0|0|0 and 1|1|1 were received, fail Accurate ECN negotiation
3742 * by not setting TE_ACE_SETUPRECEIVED.
3743 */
3744 uint32_t ecn_flags = TE_ACE_SETUPRECEIVED;
3745 if (TCP_L4S_ENABLED(tp)) {
3746 ecn_flags |= TE_SENDIPECT;
3747 }
3748 switch (ace_flags) {
3749 case (0 | TH_CWR | 0):
3750 /* Non-ECT SYN was delivered */
3751 tp->ecn_flags |= ecn_flags;
3752 tcpstat.tcps_ecn_ace_syn_not_ect++;
3753 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success;
3754 break;
3755 case (0 | TH_CWR | TH_ECE):
3756 /* ECT1 SYN was delivered */
3757 tp->ecn_flags |= ecn_flags;
3758 /* Mangling detected, set Non-ECT on outgoing packets */
3759 tp->ecn_flags &= ~TE_SENDIPECT;
3760 tcpstat.tcps_ecn_ace_syn_ect1++;
3761 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success_ect_mangling_detected;
3762 break;
3763 case (TH_AE | 0 | 0):
3764 /* ECT0 SYN was delivered */
3765 tp->ecn_flags |= ecn_flags;
3766 /* Mangling detected, set Non-ECT on outgoing packets */
3767 tp->ecn_flags &= ~TE_SENDIPECT;
3768 tcpstat.tcps_ecn_ace_syn_ect0++;
3769 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success_ect_mangling_detected;
3770 break;
3771 case (TH_AE | TH_CWR | 0):
3772 /* CE SYN was delivered */
3773 tp->ecn_flags |= ecn_flags;
3774 /* Mangling detected, set Non-ECT on outgoing packets */
3775 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success_ect_mangling_detected;
3776 tp->ecn_flags &= ~TE_SENDIPECT;
3777 /*
3778 * Although we don't send ECT SYN yet, it is possible that
3779 * a network element changed Not-ECT to ECT and later there
3780 * was congestion at another network element that set it to CE.
3781 * To keep it simple, we will consider this as a congestion event
3782 * for the congestion controller.
3783 * If a TCP client in AccECN mode receives CE feedback in the TCP
3784 * flags of a SYN/ACK, it MUST NOT increment s.cep.
3785 */
3786 tp->snd_cwnd = 2 * tp->t_maxseg;
3787 tcpstat.tcps_ecn_ace_syn_ce++;
3788 break;
3789 default:
3790 break;
3791 }
3792 if (TCP_ECN_ENABLED(tp)) {
3793 tcp_heuristic_ecn_success(tp);
3794 tcpstat.tcps_ecn_client_success++;
3795 }
3796 /*
3797 * A TCP client in AccECN mode MUST feed back which of the 4
3798 * possible values of the IP-ECN field that was received in the
3799 * SYN/ACK. Set the setup flag for final ACK accordingly.
3800 * We will initialize r.cep, r.e1b, r.e0b first and then increment
3801 * if CE was set on the IP-ECN field of the SYN-ACK.
3802 */
3803 tp->t_aecn.t_rcv_ce_packets = 5;
3804 tp->t_aecn.t_rcv_ect0_bytes = tp->t_aecn.t_rcv_ect1_bytes = 1;
3805 tp->t_aecn.t_rcv_ce_bytes = 0;
3806
3807 /* Increment packet & byte counters based on IP-ECN */
3808 tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
3809
3810 switch (ip_ecn) {
3811 case IPTOS_ECN_NOTECT:
3812 /* Not-ECT SYN-ACK was received */
3813 tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
3814 break;
3815 case IPTOS_ECN_ECT1:
3816 /* ECT1 SYN-ACK was received */
3817 tp->ecn_flags |= TE_ACE_SETUP_ECT1;
3818 break;
3819 case IPTOS_ECN_ECT0:
3820 /* ECT0 SYN-ACK was received */
3821 tp->ecn_flags |= TE_ACE_SETUP_ECT0;
3822 break;
3823 case IPTOS_ECN_CE:
3824 tp->ecn_flags |= TE_ACE_SETUP_CE;
3825 break;
3826 }
3827 /* Update the time for this newly SYN-ACK packet */
3828 if ((to.to_flags & TOF_TS) != 0 && (to.to_tsecr != 0) &&
3829 (tp->t_last_ack_tsecr == 0 || TSTMP_GEQ(to.to_tsecr, tp->t_last_ack_tsecr))) {
3830 tp->t_last_ack_tsecr = to.to_tsecr;
3831 }
3832 } else {
3833 if ((tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) &&
3834 tp->t_rxtshift == 0) {
3835 tcp_heuristic_ecn_success(tp);
3836 tcpstat.tcps_ecn_not_supported++;
3837 }
3838 if ((tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) &&
3839 tp->t_rxtshift > 0) {
3840 tcp_heuristic_ecn_loss(tp);
3841 }
3842
3843 /* non-ECN-setup SYN-ACK */
3844 tp->ecn_flags &= ~TE_SENDIPECT;
3845 /*
3846 * If Accurate ECN SYN was retransmitted twice and non-ECN SYN-ACK
3847 * was received, then we consider it as Accurate ECN blackholing
3848 */
3849 if ((tp->ecn_flags & TE_LOST_SYN) && tp->t_rxtshift <= 2 &&
3850 tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_enabled) {
3851 tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_blackholed;
3852 }
3853 /*
3854 * If SYN wasn't retransmitted twice yet, the server supports neither classic nor
3855 * accurate ECN SYN-ACK. Accurate ECN should already be disabled for both half connections
3856 * as TE_ACE_SETUPRECEIVED flag is not set.
3857 */
3858 if (tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_enabled) {
3859 tp->t_client_accecn_state = tcp_connection_client_ecn_not_available;
3860 }
3861 }
3862
3863 /* Do window scaling on this connection? */
3864 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
3865 tp->snd_scale = tp->requested_s_scale;
3866 tp->rcv_scale = tp->request_r_scale;
3867 }
3868
3869 uint32_t recwin = min(tp->rcv_wnd, TCP_MAXWIN << tp->rcv_scale);
3870 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.get_rlwin != NULL) {
3871 /* For a LBE receiver, also use rledbat_win */
3872 uint32_t rledbat_win = tcp_cc_rledbat.get_rlwin(tp);
3873 if (rledbat_win > 0) {
3874 recwin = min(recwin, rledbat_win);
3875 }
3876 }
3877 tp->rcv_adv += recwin;
3878
3879 tp->snd_una++; /* SYN is acked */
3880 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
3881 tp->snd_nxt = tp->snd_una;
3882 }
3883
3884 /*
3885 * We have sent more in the SYN than what is being
3886 * acked. (e.g., TFO)
3887 * We should restart the sending from what the receiver
3888 * has acknowledged immediately.
3889 */
3890 if (SEQ_GT(tp->snd_nxt, th->th_ack)) {
3891 /*
3892 * rdar://problem/33214601
3893 * There is a middlebox that acks all but one
3894 * byte and still drops the data.
3895 */
3896 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
3897 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3898 tp->snd_max == th->th_ack + 1 &&
3899 tp->snd_max > tp->snd_una + 1) {
3900 tcp_heuristic_tfo_middlebox(tp);
3901
3902 so->so_error = ENODATA;
3903 soevent(so,
3904 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
3905
3906 tp->t_tfo_stats |= TFO_S_ONE_BYTE_PROXY;
3907 }
3908
3909 tp->snd_max = tp->snd_nxt = th->th_ack;
3910 }
3911
3912 /*
3913 * If there's data, delay ACK; if there's also a FIN
3914 * ACKNOW will be turned on later.
3915 */
3916 TCP_INC_VAR(tp->t_unacksegs, segment_count);
3917 if (TCP_ACC_ECN_ON(tp) && ip_ecn == IPTOS_ECN_CE) {
3918 TCP_INC_VAR(tp->t_unacksegs_ce, segment_count);
3919 }
3920 if (DELAY_ACK(tp, th) && tlen != 0) {
3921 if ((tp->t_flags & TF_DELACK) == 0) {
3922 tp->t_flags |= TF_DELACK;
3923 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3924 }
3925 } else {
3926 tp->t_flags |= TF_ACKNOW;
3927 }
3928 /*
3929 * Received <SYN,ACK> in SYN_SENT[*] state.
3930 * Transitions:
3931 * SYN_SENT --> ESTABLISHED
3932 * SYN_SENT* --> FIN_WAIT_1
3933 */
3934 tp->t_starttime = tcp_now;
3935 tcp_sbrcv_tstmp_check(tp);
3936 if (tp->t_flags & TF_NEEDFIN) {
3937 DTRACE_TCP4(state__change, void, NULL,
3938 struct inpcb *, inp,
3939 struct tcpcb *, tp, int32_t,
3940 TCPS_FIN_WAIT_1);
3941 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
3942 tp->t_state = TCPS_FIN_WAIT_1;
3943 tp->t_flags &= ~TF_NEEDFIN;
3944 thflags &= ~TH_SYN;
3945
3946 TCP_LOG_CONNECTION_SUMMARY(tp);
3947 } else {
3948 DTRACE_TCP4(state__change, void, NULL,
3949 struct inpcb *, inp, struct tcpcb *,
3950 tp, int32_t, TCPS_ESTABLISHED);
3951 TCP_LOG_STATE(tp, TCPS_ESTABLISHED);
3952 tp->t_state = TCPS_ESTABLISHED;
3953 tp->t_timer[TCPT_KEEP] =
3954 OFFSET_FROM_START(tp,
3955 TCP_CONN_KEEPIDLE(tp));
3956 if (nstat_collect) {
3957 nstat_route_connect_success(
3958 inp->inp_route.ro_rt);
3959 }
3960 TCP_LOG_CONNECTED(tp, 0);
3961 /*
3962 * The SYN is acknowledged but una is not
3963 * updated yet. So pass the value of
3964 * ack to compute sndbytes correctly
3965 */
3966 inp_count_sndbytes(inp, th->th_ack);
3967 }
3968 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
3969 #if MPTCP
3970 /*
3971 * Do not send the connect notification for additional
3972 * subflows until ACK for 3-way handshake arrives.
3973 */
3974 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
3975 (tp->t_mpflags & TMPF_SENT_JOIN)) {
3976 isconnected = FALSE;
3977 } else
3978 #endif /* MPTCP */
3979 isconnected = TRUE;
3980
3981 if ((tp->t_tfo_flags & (TFO_F_COOKIE_REQ | TFO_F_COOKIE_SENT)) ||
3982 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT)) {
3983 tcp_tfo_synack(tp, &to);
3984
3985 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3986 SEQ_LT(tp->snd_una, th->th_ack)) {
3987 tp->t_tfo_stats |= TFO_S_SYN_DATA_ACKED;
3988 tcpstat.tcps_tfo_syn_data_acked++;
3989 #if MPTCP
3990 if (so->so_flags & SOF_MP_SUBFLOW) {
3991 so->so_flags1 |= SOF1_TFO_REWIND;
3992 }
3993 #endif
3994 tcp_tfo_rcv_probe(tp, tlen);
3995 }
3996 }
3997 } else {
3998 /*
3999 * Received initial SYN in SYN-SENT[*] state => simul-
4000 * taneous open.
4001 * Do 3-way handshake:
4002 * SYN-SENT -> SYN-RECEIVED
4003 * SYN-SENT* -> SYN-RECEIVED*
4004 */
4005 tp->t_flags |= TF_ACKNOW;
4006 tp->t_timer[TCPT_REXMT] = 0;
4007 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
4008 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
4009 TCP_LOG_STATE(tp, TCPS_SYN_RECEIVED);
4010 tp->t_state = TCPS_SYN_RECEIVED;
4011
4012 /*
4013 * During simultaneous open, TFO should not be used.
4014 * So, we disable it here, to prevent that data gets
4015 * sent on the SYN/ACK.
4016 */
4017 tcp_disable_tfo(tp);
4018 }
4019
4020 trimthenstep6:
4021 /*
4022 * Advance th->th_seq to correspond to first data byte.
4023 * If data, trim to stay within window,
4024 * dropping FIN if necessary.
4025 */
4026 th->th_seq++;
4027 if (tlen > tp->rcv_wnd) {
4028 todrop = tlen - tp->rcv_wnd;
4029 m_adj(m, -todrop);
4030 tlen = tp->rcv_wnd;
4031 thflags &= ~TH_FIN;
4032 tcpstat.tcps_rcvpackafterwin++;
4033 tcpstat.tcps_rcvbyteafterwin += todrop;
4034 }
4035 tp->snd_wl1 = th->th_seq - 1;
4036 tp->rcv_up = th->th_seq;
4037 /*
4038 * Client side of transaction: already sent SYN and data.
4039 * If the remote host used T/TCP to validate the SYN,
4040 * our data will be ACK'd; if so, enter normal data segment
4041 * processing in the middle of step 5, ack processing.
4042 * Otherwise, goto step 6.
4043 */
4044 if (thflags & TH_ACK) {
4045 goto process_ACK;
4046 }
4047 goto step6;
4048 /*
4049 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
4050 * do normal processing.
4051 *
4052 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
4053 */
4054 case TCPS_LAST_ACK:
4055 case TCPS_CLOSING:
4056 case TCPS_TIME_WAIT:
4057 break; /* continue normal processing */
4058
4059 /* Received a SYN while connection is already established.
4060 * This is a "half open connection and other anomalies" described
4061 * in RFC793 page 34, send an ACK so the remote reset the connection
4062 * or recovers by adjusting its sequence numbering. Sending an ACK is
4063 * in accordance with RFC 5961 Section 4.2
4064 *
4065 * For Accurate ECN, if we receive a packet with SYN in ESTABLISHED
4066 * state, we don't send the handshake encoding.
4067 */
4068 case TCPS_ESTABLISHED:
4069 if (thflags & TH_SYN && tlen <= 0) {
4070 /* Drop the packet silently if we have reached the limit */
4071 if (tcp_is_ack_ratelimited(tp)) {
4072 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
4073 goto drop;
4074 } else {
4075 /* Send challenge ACK */
4076 tcpstat.tcps_synchallenge++;
4077 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
4078 goto dropafterack;
4079 }
4080 }
4081 break;
4082 }
4083
4084 /*
4085 * States other than LISTEN or SYN_SENT.
4086 * First check the RST flag and sequence number since reset segments
4087 * are exempt from the timestamp and connection count tests. This
4088 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
4089 * below which allowed reset segments in half the sequence space
4090 * to fall though and be processed (which gives forged reset
4091 * segments with a random sequence number a 50 percent chance of
4092 * killing a connection).
4093 * Then check timestamp, if present.
4094 * Then check the connection count, if present.
4095 * Then check that at least some bytes of segment are within
4096 * receive window. If segment begins before rcv_nxt,
4097 * drop leading data (and SYN); if nothing left, just ack.
4098 *
4099 *
4100 * If the RST bit is set, check the sequence number to see
4101 * if this is a valid reset segment.
4102 * RFC 793 page 37:
4103 * In all states except SYN-SENT, all reset (RST) segments
4104 * are validated by checking their SEQ-fields. A reset is
4105 * valid if its sequence number is in the window.
4106 * Note: this does not take into account delayed ACKs, so
4107 * we should test against last_ack_sent instead of rcv_nxt.
4108 * The sequence number in the reset segment is normally an
4109 * echo of our outgoing acknowlegement numbers, but some hosts
4110 * send a reset with the sequence number at the rightmost edge
4111 * of our receive window, and we have to handle this case.
4112 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
4113 * that brute force RST attacks are possible. To combat this,
4114 * we use a much stricter check while in the ESTABLISHED state,
4115 * only accepting RSTs where the sequence number is equal to
4116 * last_ack_sent. In all other states (the states in which a
4117 * RST is more likely), the more permissive check is used.
4118 * RFC 5961 Section 3.2: if the RST bit is set, sequence # is
4119 * within the receive window and last_ack_sent == seq,
4120 * then reset the connection. Otherwise if the seq doesn't
4121 * match last_ack_sent, TCP must send challenge ACK. Perform
4122 * rate limitation when sending the challenge ACK.
4123 * If we have multiple segments in flight, the intial reset
4124 * segment sequence numbers will be to the left of last_ack_sent,
4125 * but they will eventually catch up.
4126 * In any case, it never made sense to trim reset segments to
4127 * fit the receive window since RFC 1122 says:
4128 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
4129 *
4130 * A TCP SHOULD allow a received RST segment to include data.
4131 *
4132 * DISCUSSION
4133 * It has been suggested that a RST segment could contain
4134 * ASCII text that encoded and explained the cause of the
4135 * RST. No standard has yet been established for such
4136 * data.
4137 *
4138 * If the reset segment passes the sequence number test examine
4139 * the state:
4140 * SYN_RECEIVED STATE:
4141 * If passive open, return to LISTEN state.
4142 * If active open, inform user that connection was refused.
4143 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
4144 * Inform user that connection was reset, and close tcb.
4145 * CLOSING, LAST_ACK STATES:
4146 * Close the tcb.
4147 * TIME_WAIT STATE:
4148 * Drop the segment - see Stevens, vol. 2, p. 964 and
4149 * RFC 1337.
4150 *
4151 * Radar 4803931: Allows for the case where we ACKed the FIN but
4152 * there is already a RST in flight from the peer.
4153 * In that case, accept the RST for non-established
4154 * state if it's one off from last_ack_sent.
4155 *
4156 */
4157 if (thflags & TH_RST) {
4158 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
4159 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
4160 (tp->rcv_wnd == 0 &&
4161 ((tp->last_ack_sent == th->th_seq) ||
4162 ((tp->last_ack_sent - 1) == th->th_seq)))) {
4163 if (tp->last_ack_sent == th->th_seq) {
4164 switch (tp->t_state) {
4165 case TCPS_SYN_RECEIVED:
4166 IF_TCP_STATINC(ifp, rstinsynrcv);
4167 so->so_error = ECONNREFUSED;
4168 goto close;
4169
4170 case TCPS_ESTABLISHED:
4171 if ((TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) &&
4172 tp->snd_una == tp->iss + 1 &&
4173 SEQ_GT(tp->snd_max, tp->snd_una)) {
4174 /*
4175 * If the first data packet on an
4176 * ECN connection, receives a RST
4177 * increment the heuristic
4178 */
4179 tcp_heuristic_ecn_droprst(tp);
4180 }
4181 OS_FALLTHROUGH;
4182 case TCPS_FIN_WAIT_1:
4183 case TCPS_CLOSE_WAIT:
4184 case TCPS_FIN_WAIT_2:
4185 so->so_error = ECONNRESET;
4186 close:
4187 soevent(so,
4188 (SO_FILT_HINT_LOCKED |
4189 SO_FILT_HINT_CONNRESET));
4190
4191 tcpstat.tcps_drops++;
4192 tp = tcp_close(tp);
4193 break;
4194
4195 case TCPS_CLOSING:
4196 case TCPS_LAST_ACK:
4197 tp = tcp_close(tp);
4198 break;
4199
4200 case TCPS_TIME_WAIT:
4201 break;
4202 }
4203 } else {
4204 tcpstat.tcps_badrst++;
4205 /* Drop if we have reached the ACK limit */
4206 if (tcp_is_ack_ratelimited(tp)) {
4207 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
4208 goto drop;
4209 } else {
4210 /* Send challenge ACK */
4211 tcpstat.tcps_rstchallenge++;
4212 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
4213 goto dropafterack;
4214 }
4215 }
4216 }
4217 goto drop;
4218 }
4219
4220 /*
4221 * RFC 1323 PAWS: If we have a timestamp reply on this segment
4222 * and it's less than ts_recent, drop it.
4223 */
4224 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
4225 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
4226 /* Check to see if ts_recent is over 24 days old. */
4227 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
4228 /*
4229 * Invalidate ts_recent. If this segment updates
4230 * ts_recent, the age will be reset later and ts_recent
4231 * will get a valid value. If it does not, setting
4232 * ts_recent to zero will at least satisfy the
4233 * requirement that zero be placed in the timestamp
4234 * echo reply when ts_recent isn't valid. The
4235 * age isn't reset until we get a valid ts_recent
4236 * because we don't want out-of-order segments to be
4237 * dropped when ts_recent is old.
4238 */
4239 tp->ts_recent = 0;
4240 } else {
4241 tcpstat.tcps_rcvduppack++;
4242 tcpstat.tcps_rcvdupbyte += tlen;
4243 tp->t_pawsdrop++;
4244 tcpstat.tcps_pawsdrop++;
4245
4246 /*
4247 * PAWS-drop when ECN is being used? That indicates
4248 * that ECT-marked packets take a different path, with
4249 * different congestion-characteristics.
4250 *
4251 * Only fallback when we did send less than 2GB as PAWS
4252 * really has no reason to kick in earlier.
4253 */
4254 if ((TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) &&
4255 inp->inp_stat->rxbytes < 2147483648) {
4256 INP_INC_IFNET_STAT(inp, ecn_fallback_reorder);
4257 tcpstat.tcps_ecn_fallback_reorder++;
4258 tcp_heuristic_ecn_aggressive(tp);
4259 }
4260
4261 if (nstat_collect) {
4262 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt,
4263 1, tlen, NSTAT_RX_FLAG_DUPLICATE);
4264 INP_ADD_STAT(inp, ifnet_count_type,
4265 rxpackets, 1);
4266 INP_ADD_STAT(inp, ifnet_count_type,
4267 rxbytes, tlen);
4268 tp->t_stat.rxduplicatebytes += tlen;
4269 inp_set_activity_bitmap(inp);
4270 }
4271 if (tlen > 0) {
4272 goto dropafterack;
4273 }
4274 goto drop;
4275 }
4276 }
4277
4278 /*
4279 * In the SYN-RECEIVED state, validate that the packet belongs to
4280 * this connection before trimming the data to fit the receive
4281 * window. Check the sequence number versus IRS since we know
4282 * the sequence numbers haven't wrapped. This is a partial fix
4283 * for the "LAND" DoS attack.
4284 */
4285 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
4286 IF_TCP_STATINC(ifp, dospacket);
4287 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad SEQ");
4288 goto dropwithreset;
4289 }
4290
4291 /*
4292 * Check if there is old data at the beginning of the window
4293 * i.e. the sequence number is before rcv_nxt
4294 */
4295 todrop = tp->rcv_nxt - th->th_seq;
4296 if (todrop > 0) {
4297 boolean_t is_syn_set = FALSE;
4298
4299 if (thflags & TH_SYN) {
4300 is_syn_set = TRUE;
4301 thflags &= ~TH_SYN;
4302 th->th_seq++;
4303 if (th->th_urp > 1) {
4304 th->th_urp--;
4305 } else {
4306 thflags &= ~TH_URG;
4307 }
4308 todrop--;
4309 }
4310 /*
4311 * Following if statement from Stevens, vol. 2, p. 960.
4312 * The amount of duplicate data is greater than or equal
4313 * to the size of the segment - entire segment is duplicate
4314 */
4315 if (todrop > tlen
4316 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
4317 /*
4318 * Any valid FIN must be to the left of the window.
4319 * At this point the FIN must be a duplicate or out
4320 * of sequence; drop it.
4321 */
4322 thflags &= ~TH_FIN;
4323
4324 /*
4325 * Send an ACK to resynchronize and drop any data.
4326 * But keep on processing for RST or ACK.
4327 *
4328 * If the SYN bit was originally set, then only send
4329 * an ACK if we are not rate-limiting this connection.
4330 */
4331 if (is_syn_set) {
4332 if (!tcp_is_ack_ratelimited(tp)) {
4333 tcpstat.tcps_synchallenge++;
4334 tp->t_flags |= TF_ACKNOW;
4335 }
4336 } else {
4337 tp->t_flags |= TF_ACKNOW;
4338 }
4339
4340 if (todrop == 1) {
4341 /* This could be a keepalive */
4342 soevent(so, SO_FILT_HINT_LOCKED |
4343 SO_FILT_HINT_KEEPALIVE);
4344 }
4345 todrop = tlen;
4346 tcpstat.tcps_rcvduppack++;
4347 tcpstat.tcps_rcvdupbyte += todrop;
4348 } else {
4349 tcpstat.tcps_rcvpartduppack++;
4350 tcpstat.tcps_rcvpartdupbyte += todrop;
4351 }
4352
4353 if (todrop > 1) {
4354 /*
4355 * Note the duplicate data sequence space so that
4356 * it can be reported in DSACK option.
4357 */
4358 tp->t_dsack_lseq = th->th_seq;
4359 tp->t_dsack_rseq = th->th_seq + todrop;
4360 tp->t_flags |= TF_ACKNOW;
4361 }
4362 if (nstat_collect) {
4363 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt, 1,
4364 todrop, NSTAT_RX_FLAG_DUPLICATE);
4365 INP_ADD_STAT(inp, ifnet_count_type, rxpackets, 1);
4366 INP_ADD_STAT(inp, ifnet_count_type, rxbytes, todrop);
4367 tp->t_stat.rxduplicatebytes += todrop;
4368 inp_set_activity_bitmap(inp);
4369 }
4370 drop_hdrlen += todrop; /* drop from the top afterwards */
4371 th->th_seq += todrop;
4372 tlen -= todrop;
4373 if (th->th_urp > todrop) {
4374 th->th_urp -= todrop;
4375 } else {
4376 thflags &= ~TH_URG;
4377 th->th_urp = 0;
4378 }
4379 }
4380
4381 /*
4382 * If new data are received on a connection after the user
4383 * processes are gone, then RST the other end.
4384 * Send also a RST when we received a data segment after we've
4385 * sent our FIN when the socket is defunct.
4386 * Note that an MPTCP subflow socket would have SS_NOFDREF set
4387 * by default. So, if it's an MPTCP-subflow we rather check the
4388 * MPTCP-level's socket state for SS_NOFDREF.
4389 */
4390 if (tlen) {
4391 boolean_t close_it = FALSE;
4392
4393 if (!(so->so_flags & SOF_MP_SUBFLOW) && (so->so_state & SS_NOFDREF) &&
4394 tp->t_state > TCPS_CLOSE_WAIT) {
4395 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_NOFDREF");
4396 close_it = TRUE;
4397 }
4398
4399 if ((so->so_flags & SOF_MP_SUBFLOW) && (mptetoso(tptomptp(tp)->mpt_mpte)->so_state & SS_NOFDREF) &&
4400 tp->t_state > TCPS_CLOSE_WAIT) {
4401 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_MP_SUBFLOW SS_NOFDREF");
4402 close_it = TRUE;
4403 }
4404
4405 if ((so->so_flags & SOF_DEFUNCT) && tp->t_state > TCPS_FIN_WAIT_1) {
4406 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_DEFUNCT");
4407 close_it = TRUE;
4408 }
4409
4410 if (so->so_state & SS_CANTRCVMORE) {
4411 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_CANTRCVMORE");
4412 close_it = TRUE;
4413 }
4414
4415 if (close_it) {
4416 tp = tcp_close(tp);
4417 tcpstat.tcps_rcvafterclose++;
4418 IF_TCP_STATINC(ifp, cleanup);
4419 goto dropwithreset;
4420 }
4421 }
4422
4423 /*
4424 * If segment ends after window, drop trailing data
4425 * (and PUSH and FIN); if nothing left, just ACK.
4426 */
4427 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
4428 if (todrop > 0) {
4429 tcpstat.tcps_rcvpackafterwin++;
4430 if (todrop >= tlen) {
4431 tcpstat.tcps_rcvbyteafterwin += tlen;
4432 /*
4433 * If a new connection request is received
4434 * while in TIME_WAIT, drop the old connection
4435 * and start over if the sequence numbers
4436 * are above the previous ones.
4437 */
4438 if (thflags & TH_SYN &&
4439 tp->t_state == TCPS_TIME_WAIT &&
4440 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
4441 iss = tcp_new_isn(tp);
4442 tp = tcp_close(tp);
4443 socket_unlock(so, 1);
4444 goto findpcb;
4445 }
4446 /*
4447 * If window is closed can only take segments at
4448 * window edge, and have to drop data and PUSH from
4449 * incoming segments. Continue processing, but
4450 * remember to ack. Otherwise, drop segment
4451 * and ack.
4452 */
4453 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
4454 tp->t_flags |= TF_ACKNOW;
4455 tcpstat.tcps_rcvwinprobe++;
4456 } else {
4457 goto dropafterack;
4458 }
4459 } else {
4460 tcpstat.tcps_rcvbyteafterwin += todrop;
4461 }
4462 m_adj(m, -todrop);
4463 tlen -= todrop;
4464 thflags &= ~(TH_PUSH | TH_FIN);
4465 }
4466
4467 /*
4468 * If last ACK falls within this segment's sequence numbers,
4469 * record its timestamp.
4470 * NOTE:
4471 * 1) That the test incorporates suggestions from the latest
4472 * proposal of the [email protected] list (Braden 1993/04/26).
4473 * 2) That updating only on newer timestamps interferes with
4474 * our earlier PAWS tests, so this check should be solely
4475 * predicated on the sequence space of this segment.
4476 * 3) That we modify the segment boundary check to be
4477 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
4478 * instead of RFC1323's
4479 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
4480 * This modified check allows us to overcome RFC1323's
4481 * limitations as described in Stevens TCP/IP Illustrated
4482 * Vol. 2 p.869. In such cases, we can still calculate the
4483 * RTT correctly when RCV.NXT == Last.ACK.Sent.
4484 */
4485 if ((to.to_flags & TOF_TS) != 0 &&
4486 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
4487 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
4488 ((thflags & (TH_SYN | TH_FIN)) != 0))) {
4489 tp->ts_recent_age = tcp_now;
4490 tp->ts_recent = to.to_tsval;
4491 }
4492
4493 /*
4494 * Stevens: If a SYN is in the window, then this is an
4495 * error and we send an RST and drop the connection.
4496 *
4497 * RFC 5961 Section 4.2
4498 * Send challenge ACK for any SYN in synchronized state
4499 * Perform rate limitation in doing so.
4500 */
4501 if (thflags & TH_SYN) {
4502 if (!tcp_syn_data_valid(tp, th, tlen)) {
4503 tcpstat.tcps_badsyn++;
4504 /* Drop if we have reached ACK limit */
4505 if (tcp_is_ack_ratelimited(tp)) {
4506 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN rate limited");
4507 goto drop;
4508 } else {
4509 /* Send challenge ACK */
4510 tcpstat.tcps_synchallenge++;
4511 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN challenge ack");
4512 goto dropafterack;
4513 }
4514 } else {
4515 /*
4516 * Received SYN (/ACK) with data.
4517 * Move sequence number along to process the data.
4518 */
4519 th->th_seq++;
4520 thflags &= ~TH_SYN;
4521 }
4522 }
4523
4524 /*
4525 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
4526 * flag is on (half-synchronized state), then queue data for
4527 * later processing; else drop segment and return.
4528 */
4529 if ((thflags & TH_ACK) == 0) {
4530 if (tp->t_state == TCPS_SYN_RECEIVED) {
4531 if ((TFO_ENABLED(tp))) {
4532 /*
4533 * So, we received a valid segment while in
4534 * SYN-RECEIVED.
4535 * As this cannot be an RST (see that if a bit
4536 * higher), and it does not have the ACK-flag
4537 * set, we want to retransmit the SYN/ACK.
4538 * Thus, we have to reset snd_nxt to snd_una to
4539 * trigger the going back to sending of the
4540 * SYN/ACK. This is more consistent with the
4541 * behavior of tcp_output(), which expects
4542 * to send the segment that is pointed to by
4543 * snd_nxt.
4544 */
4545 tp->snd_nxt = tp->snd_una;
4546
4547 /*
4548 * We need to make absolutely sure that we are
4549 * going to reply upon a duplicate SYN-segment.
4550 */
4551 if (th->th_flags & TH_SYN) {
4552 needoutput = 1;
4553 }
4554 }
4555 /* Process this same as newly received Accurate ECN SYN */
4556 int ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
4557 tcp_input_process_accecn_syn(tp, ace_flags, ip_ecn);
4558
4559 goto step6;
4560 } else if (tp->t_flags & TF_ACKNOW) {
4561 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4562 goto dropafterack;
4563 } else {
4564 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4565 goto drop;
4566 }
4567 }
4568
4569 /*
4570 * Ack processing.
4571 */
4572
4573 switch (tp->t_state) {
4574 /*
4575 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
4576 * ESTABLISHED state and continue processing.
4577 * The ACK was checked above.
4578 */
4579 case TCPS_SYN_RECEIVED:
4580
4581 tcpstat.tcps_connects++;
4582
4583 /* Do window scaling? */
4584 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
4585 tp->snd_scale = tp->requested_s_scale;
4586 tp->rcv_scale = tp->request_r_scale;
4587 tp->snd_wnd = th->th_win << tp->snd_scale;
4588 tp->max_sndwnd = tp->snd_wnd;
4589 tiwin = tp->snd_wnd;
4590 }
4591 /*
4592 * Make transitions:
4593 * SYN-RECEIVED -> ESTABLISHED
4594 * SYN-RECEIVED* -> FIN-WAIT-1
4595 */
4596 tp->t_starttime = tcp_now;
4597 tcp_sbrcv_tstmp_check(tp);
4598 if (tp->t_flags & TF_NEEDFIN) {
4599 DTRACE_TCP4(state__change, void, NULL,
4600 struct inpcb *, inp,
4601 struct tcpcb *, tp, int32_t, TCPS_FIN_WAIT_1);
4602 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
4603 tp->t_state = TCPS_FIN_WAIT_1;
4604 tp->t_flags &= ~TF_NEEDFIN;
4605
4606 TCP_LOG_CONNECTION_SUMMARY(tp);
4607 } else {
4608 DTRACE_TCP4(state__change, void, NULL,
4609 struct inpcb *, inp,
4610 struct tcpcb *, tp, int32_t, TCPS_ESTABLISHED);
4611 TCP_LOG_STATE(tp, TCPS_ESTABLISHED);
4612 tp->t_state = TCPS_ESTABLISHED;
4613 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
4614 TCP_CONN_KEEPIDLE(tp));
4615 if (nstat_collect) {
4616 nstat_route_connect_success(
4617 tp->t_inpcb->inp_route.ro_rt);
4618 }
4619 TCP_LOG_CONNECTED(tp, 0);
4620 /*
4621 * The SYN is acknowledged but una is not updated
4622 * yet. So pass the value of ack to compute
4623 * sndbytes correctly
4624 */
4625 inp_count_sndbytes(inp, th->th_ack);
4626 }
4627 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
4628
4629 VERIFY(LIST_EMPTY(&tp->t_segq));
4630 tp->snd_wl1 = th->th_seq - 1;
4631
4632 /*
4633 * AccECN server in SYN-RCVD state received an ACK with
4634 * SYN=0, process handshake encoding present in the ACK for SYN-ACK
4635 * and update receive side counters.
4636 */
4637 if (TCP_ACC_ECN_ON(tp) && (thflags & (TH_SYN | TH_ACK)) == TH_ACK) {
4638 const uint32_t ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
4639 if (tlen == 0 && to.to_nsacks == 0) {
4640 /*
4641 * ACK for SYN-ACK reflects the state (ECN) in which SYN-ACK packet
4642 * was delivered. Use Table 4 of Accurate ECN draft to decode only
4643 * when a pure ACK with no SACK block is received.
4644 * 0|0|0 will fail Accurate ECN negotiation and disable ECN.
4645 */
4646 switch (ace_flags) {
4647 case (0 | TH_CWR | 0):
4648 /* Non-ECT SYN-ACK was delivered */
4649 tp->t_aecn.t_snd_ce_packets = 5;
4650 if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4651 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success;
4652 }
4653 break;
4654 case (0 | TH_CWR | TH_ECE):
4655 /* ECT1 SYN-ACK was delivered, mangling detected */
4656 OS_FALLTHROUGH;
4657 case (TH_AE | 0 | 0):
4658 /* ECT0 SYN-ACK was delivered, mangling detected */
4659 tp->t_aecn.t_snd_ce_packets = 5;
4660 if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4661 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success_ect_mangling_detected;
4662 }
4663 break;
4664 case (TH_AE | TH_CWR | 0):
4665 /*
4666 * CE SYN-ACK was delivered, even though mangling happened,
4667 * CE could indicate congestion at a node after mangling occured.
4668 * Set cwnd to 2 segments
4669 */
4670 tp->t_aecn.t_snd_ce_packets = 6;
4671 tp->snd_cwnd = 2 * tp->t_maxseg;
4672 if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4673 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success_ect_mangling_detected;
4674 }
4675 break;
4676 case (0 | 0 | 0):
4677 /* Disable ECN, as ACE fields were zeroed */
4678 tp->ecn_flags &= ~(TE_SETUPRECEIVED | TE_SENDIPECT |
4679 TE_SENDCWR | TE_ACE_SETUPRECEIVED);
4680 /*
4681 * Since last ACK has no ECN flag set and TE_LOST_SYNACK is set, this is in response
4682 * to the second (non-ECN setup) SYN-ACK retransmission. In such a case, we assume
4683 * that AccECN SYN-ACK was blackholed.
4684 */
4685 if ((tp->ecn_flags & TE_LOST_SYNACK) && tp->t_rxtshift <= 2 &&
4686 (tp->t_server_accecn_state == tcp_connection_server_classic_ecn_requested ||
4687 tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested)) {
4688 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_blackholed;
4689 }
4690 /*
4691 * SYN-ACK hasn't been retransmitted twice yet, so this could likely mean bleaching of ACE
4692 * on the path from client to server on last ACK.
4693 */
4694 if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4695 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_ace_bleaching_detected;
4696 }
4697 break;
4698 default:
4699 /* Unused values for forward compatibility */
4700 tp->t_aecn.t_snd_ce_packets = 5;
4701 break;
4702 }
4703 /* Update the time for this newly received last ACK */
4704 if ((to.to_flags & TOF_TS) != 0 && (to.to_tsecr != 0) &&
4705 (tp->t_last_ack_tsecr == 0 || TSTMP_GEQ(to.to_tsecr, tp->t_last_ack_tsecr))) {
4706 tp->t_last_ack_tsecr = to.to_tsecr;
4707 }
4708 } else if (to.to_nsacks == 0) {
4709 /*
4710 * If 3rd ACK is lost, we won't receive the last ACK
4711 * encoding. We will move the server to AccECN mode
4712 * regardless.
4713 */
4714 tp->t_aecn.t_snd_ce_packets = 5;
4715 if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4716 tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success;
4717 }
4718 }
4719 /* Increment receive side counters based on IP-ECN */
4720 tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
4721 }
4722
4723 #if MPTCP
4724 /*
4725 * Do not send the connect notification for additional subflows
4726 * until ACK for 3-way handshake arrives.
4727 */
4728 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
4729 (tp->t_mpflags & TMPF_SENT_JOIN)) {
4730 isconnected = FALSE;
4731 } else
4732 #endif /* MPTCP */
4733 isconnected = TRUE;
4734 if ((tp->t_tfo_flags & TFO_F_COOKIE_VALID)) {
4735 /* Done this when receiving the SYN */
4736 isconnected = FALSE;
4737
4738 OSDecrementAtomic(&tcp_tfo_halfcnt);
4739
4740 /* Panic if something has gone terribly wrong. */
4741 VERIFY(tcp_tfo_halfcnt >= 0);
4742
4743 tp->t_tfo_flags &= ~TFO_F_COOKIE_VALID;
4744 }
4745
4746 /*
4747 * In case there is data in the send-queue (e.g., TFO is being
4748 * used, or connectx+data has been done), then if we would
4749 * "FALLTHROUGH", we would handle this ACK as if data has been
4750 * acknowledged. But, we have to prevent this. And this
4751 * can be prevented by increasing snd_una by 1, so that the
4752 * SYN is not considered as data (snd_una++ is actually also
4753 * done in SYN_SENT-state as part of the regular TCP stack).
4754 *
4755 * In case there is data on this ack as well, the data will be
4756 * handled by the label "dodata" right after step6.
4757 */
4758 if (so->so_snd.sb_cc) {
4759 tp->snd_una++; /* SYN is acked */
4760 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4761 tp->snd_nxt = tp->snd_una;
4762 }
4763
4764 /*
4765 * No duplicate-ACK handling is needed. So, we
4766 * directly advance to processing the ACK (aka,
4767 * updating the RTT estimation,...)
4768 *
4769 * But, we first need to handle eventual SACKs,
4770 * because TFO will start sending data with the
4771 * SYN/ACK, so it might be that the client
4772 * includes a SACK with its ACK.
4773 */
4774 if (SACK_ENABLED(tp) &&
4775 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4776 tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &highest_sacked_seq);
4777 }
4778
4779 goto process_ACK;
4780 }
4781
4782 OS_FALLTHROUGH;
4783
4784 /*
4785 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4786 * ACKs. If the ack is in the range
4787 * tp->snd_una < th->th_ack <= tp->snd_max
4788 * then advance tp->snd_una to th->th_ack and drop
4789 * data from the retransmission queue. If this ACK reflects
4790 * more up to date window information we update our window information.
4791 */
4792 case TCPS_ESTABLISHED:
4793 case TCPS_FIN_WAIT_1:
4794 case TCPS_FIN_WAIT_2:
4795 case TCPS_CLOSE_WAIT:
4796 case TCPS_CLOSING:
4797 case TCPS_LAST_ACK:
4798 case TCPS_TIME_WAIT:
4799 if (SEQ_GT(th->th_ack, tp->snd_max)) {
4800 tcpstat.tcps_rcvacktoomuch++;
4801 if (tcp_is_ack_ratelimited(tp)) {
4802 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 rcvacktoomuch");
4803 goto drop;
4804 } else {
4805 goto dropafterack;
4806 }
4807 }
4808 if (SEQ_LT(th->th_ack, tp->snd_una - tp->max_sndwnd)) {
4809 if (tcp_is_ack_ratelimited(tp)) {
4810 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad ACK");
4811 goto drop;
4812 } else {
4813 goto dropafterack;
4814 }
4815 }
4816 if (SACK_ENABLED(tp) && to.to_nsacks > 0) {
4817 recvd_dsack = tcp_sack_process_dsack(tp, &to, th, &dsack_tlp);
4818 /*
4819 * If DSACK is received and this packet has no
4820 * other SACK information, it can be dropped.
4821 * We do not want to treat it as a duplicate ack.
4822 */
4823 if (recvd_dsack &&
4824 SEQ_LEQ(th->th_ack, tp->snd_una) &&
4825 to.to_nsacks == 0) {
4826 tcp_bad_rexmt_check(tp, th, &to);
4827 goto drop;
4828 }
4829 }
4830
4831 if (SACK_ENABLED(tp) &&
4832 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4833 tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &highest_sacked_seq);
4834 }
4835
4836 if (TCP_RACK_ENABLED(tp)) {
4837 /* If DSACK was received (not due to TLP), then update the reordering window */
4838 if (recvd_dsack && !dsack_tlp) {
4839 tp->rack.dsack_round_seen = 1;
4840 }
4841 tcp_rack_update_reordering_window(tp, th->th_ack);
4842 }
4843
4844 #if MPTCP
4845 if (tp->t_mpuna && SEQ_GEQ(th->th_ack, tp->t_mpuna)) {
4846 if (tp->t_mpflags & TMPF_PREESTABLISHED) {
4847 /* MP TCP establishment succeeded */
4848 tp->t_mpuna = 0;
4849 if (tp->t_mpflags & TMPF_JOINED_FLOW) {
4850 if (tp->t_mpflags & TMPF_SENT_JOIN) {
4851 tp->t_mpflags &=
4852 ~TMPF_PREESTABLISHED;
4853 tp->t_mpflags |=
4854 TMPF_MPTCP_TRUE;
4855
4856 tp->t_timer[TCPT_JACK_RXMT] = 0;
4857 tp->t_mprxtshift = 0;
4858 isconnected = TRUE;
4859 } else {
4860 isconnected = FALSE;
4861 }
4862 } else {
4863 isconnected = TRUE;
4864 }
4865 }
4866 }
4867 #endif /* MPTCP */
4868
4869 tcp_tfo_rcv_ack(tp, th);
4870
4871 /*
4872 * If we have outstanding data (other than
4873 * a window probe), this is a completely
4874 * duplicate ack and the ack is the biggest we've seen.
4875 *
4876 * Need to accommodate a change in window on duplicate acks
4877 * to allow operating systems that update window during
4878 * recovery with SACK
4879 */
4880 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
4881 /*
4882 * Update snd_fack when new SACK blocks are received
4883 * without advancing the ACK
4884 */
4885 if (TCP_RACK_ENABLED(tp) && sack_bytes_acked > 0 &&
4886 SEQ_LT(tp->snd_fack, highest_sacked_seq)) {
4887 tp->snd_fack = highest_sacked_seq;
4888 }
4889
4890 /*
4891 * Process AccECN feedback here for control packets
4892 * that don't have s/acked bytes
4893 */
4894 if (TCP_ACC_ECN_ON(tp) && (tp->ecn_flags & TE_SENDIPECT) &&
4895 (sack_bytes_acked == 0)) {
4896 tp->total_ect_packets_acked += 1;
4897
4898 bool newly_acked_time = false;
4899 if (acked == 0 && (to.to_flags & TOF_TS) != 0 && to.to_tsecr != 0 &&
4900 TSTMP_GT(to.to_tsecr, tp->t_last_ack_tsecr)) {
4901 newly_acked_time = true;
4902 }
4903 if (newly_acked_time) {
4904 tcp_process_accecn(tp, &to, th, 1, ace);
4905 }
4906 }
4907
4908 if (tlen == 0 && (tiwin == tp->snd_wnd ||
4909 (to.to_nsacks > 0 && sack_bytes_acked > 0))) {
4910 uint32_t old_dupacks;
4911 /*
4912 * If both ends send FIN at the same time,
4913 * then the ack will be a duplicate ack
4914 * but we have to process the FIN. Check
4915 * for this condition and process the FIN
4916 * instead of the dupack
4917 */
4918 if ((thflags & TH_FIN) &&
4919 !TCPS_HAVERCVDFIN(tp->t_state)) {
4920 break;
4921 }
4922 process_dupack:
4923 old_dupacks = tp->t_dupacks;
4924 #if MPTCP
4925 /*
4926 * MPTCP options that are ignored must
4927 * not be treated as duplicate ACKs.
4928 */
4929 if (to.to_flags & TOF_MPTCP) {
4930 goto drop;
4931 }
4932
4933 if ((isconnected) && (tp->t_mpflags & TMPF_JOINED_FLOW)) {
4934 break;
4935 }
4936 #endif /* MPTCP */
4937 /*
4938 * If a duplicate acknowledgement was seen
4939 * after ECN, it indicates packet loss in
4940 * addition to ECN. Reset INRECOVERY flag
4941 * so that we can process partial acks
4942 * correctly
4943 */
4944 if (tp->ecn_flags & TE_INRECOVERY) {
4945 tp->ecn_flags &= ~TE_INRECOVERY;
4946 }
4947
4948 tcpstat.tcps_rcvdupack++;
4949 if (SACK_ENABLED(tp)) {
4950 tp->t_dupacks += max(1, sack_bytes_acked / tp->t_maxseg);
4951 } else {
4952 ++tp->t_dupacks;
4953 }
4954
4955 tp->sackhint.sack_bytes_acked += sack_bytes_acked;
4956
4957 if (sack_bytes_acked > 0 && TCP_ACC_ECN_ON(tp) &&
4958 (tp->ecn_flags & TE_SENDIPECT) && tp->t_state == TCPS_ESTABLISHED) {
4959 uint32_t pkts_sacked = tcp_packets_this_ack(tp, sack_bytes_acked);
4960 tp->total_ect_packets_acked += pkts_sacked;
4961 tcp_process_accecn(tp, &to, th, pkts_sacked, ace);
4962 }
4963 /*
4964 * Check if we need to reset the limit on
4965 * early retransmit
4966 */
4967 if (tp->t_early_rexmt_count > 0 &&
4968 TSTMP_GEQ(tcp_now,
4969 (tp->t_early_rexmt_win +
4970 TCP_EARLY_REXMT_WIN))) {
4971 tp->t_early_rexmt_count = 0;
4972 }
4973
4974 /*
4975 * Is early retransmit needed? We check for
4976 * this when the connection is waiting for
4977 * duplicate acks to enter fast recovery.
4978 */
4979 if (!IN_FASTRECOVERY(tp)) {
4980 tcp_early_rexmt_check(tp, th);
4981 }
4982
4983 /*
4984 * Detect loss based on RACK during dupACK processing to mark lost
4985 * segments before tcp_output is called for retransmission
4986 */
4987 if (TCP_RACK_ENABLED(tp) && tcp_rack_detect_loss_and_arm_timer(tp, tp->t_dupacks)) {
4988 rack_loss_detected = true;
4989 }
4990 /*
4991 * Below are four different processing of (dup) ACKs,
4992 * 1. Not a valid dup ACK
4993 * 2. More than 3 dup ACKs but already in Fast Recovery
4994 * 3. Entered Fast Recovery for the first time
4995 * 4. Received less than 3 dup ACKs, evaluate if we can do Limited Transmit
4996 */
4997 if (tp->t_timer[TCPT_REXMT] == 0 ||
4998 (th->th_ack != tp->snd_una && sack_bytes_acked == 0)) {
4999 /*
5000 * No outstanding data and ACK is not a duplicate as it is
5001 * less than snd_una but not equal to it.
5002 */
5003 tp->t_dupacks = 0;
5004 tp->t_rexmtthresh = tcprexmtthresh;
5005 } else if ((!TCP_RACK_ENABLED(tp) && tp->t_dupacks > tp->t_rexmtthresh && old_dupacks >= tp->t_rexmtthresh) ||
5006 IN_FASTRECOVERY(tp)) {
5007 /*
5008 * We are already in Fast Recovery and t_dupacks is greater than retransmit threshold.
5009 * Increase the cwnd by 1MSS if allowed
5010 */
5011
5012 /*
5013 * If this connection was seeing packet
5014 * reordering, then recovery might be
5015 * delayed to disambiguate between
5016 * reordering and loss
5017 */
5018 if (SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
5019 (tp->t_flagsext &
5020 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) ==
5021 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
5022 /*
5023 * Since the SACK information is already
5024 * updated, this ACK will be dropped
5025 */
5026 break;
5027 }
5028
5029 /*
5030 * Dup acks mean that packets have left the
5031 * network (they're now cached at the receiver)
5032 * so bump cwnd by the amount in the receiver
5033 * to keep a constant cwnd packets in the
5034 * network.
5035 */
5036 if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp)) {
5037 int awnd;
5038
5039 /*
5040 * Compute the amount of data in flight first.
5041 * We can inject new data into the pipe iff
5042 * we have less than snd_ssthres worth of data in
5043 * flight.
5044 */
5045 awnd = (tp->snd_nxt - tp->snd_fack) + tp->sackhint.sack_bytes_rexmit;
5046 if (awnd < tp->snd_ssthresh) {
5047 tp->snd_cwnd += tp->t_maxseg;
5048 if (tp->snd_cwnd > tp->snd_ssthresh) {
5049 tp->snd_cwnd = tp->snd_ssthresh;
5050 }
5051 }
5052 } else {
5053 tp->snd_cwnd += tp->t_maxseg;
5054 }
5055
5056 /* Process any window updates */
5057 if (tiwin > tp->snd_wnd) {
5058 tcp_update_window(tp, thflags,
5059 th, tiwin, tlen);
5060 }
5061 tcp_ccdbg_trace(tp, th,
5062 TCP_CC_IN_FASTRECOVERY);
5063
5064 (void) tcp_output(tp);
5065
5066 goto drop;
5067 } else if (rack_loss_detected || (!TCP_RACK_ENABLED(tp) && tp->t_dupacks >= tp->t_rexmtthresh)) {
5068 /*
5069 * Currently not in Fast Recovery and received 3 or more dupacks.
5070 * Enter Fast Recovery, retransmit segment and set
5071 * cwnd to sshthresh if SACK is enabled.
5072 */
5073 tcp_seq onxt = tp->snd_nxt;
5074
5075 /*
5076 * If we're doing sack, check to
5077 * see if we're already in sack
5078 * recovery. If we're not doing sack,
5079 * check to see if we're in newreno
5080 * recovery.
5081 */
5082 if (SACK_ENABLED(tp)) {
5083 if (IN_FASTRECOVERY(tp)) {
5084 tp->t_dupacks = 0;
5085 break;
5086 } else if (tp->t_flagsext & TF_DELAY_RECOVERY) {
5087 break;
5088 }
5089 } else {
5090 if (SEQ_LEQ(th->th_ack, tp->snd_recover)) {
5091 tp->t_dupacks = 0;
5092 break;
5093 }
5094 }
5095 if (tp->t_flags & TF_SENTFIN) {
5096 tp->snd_recover = tp->snd_max - 1;
5097 } else {
5098 tp->snd_recover = tp->snd_max;
5099 }
5100 tp->t_timer[TCPT_PTO] = 0;
5101 tp->t_rtttime = 0;
5102
5103 /*
5104 * If the connection has seen pkt
5105 * reordering, delay recovery until
5106 * it is clear that the packet
5107 * was lost.
5108 */
5109 if (SACK_ENABLED(tp) &&
5110 (tp->t_flagsext &
5111 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
5112 == TF_PKTS_REORDERED &&
5113 !IN_FASTRECOVERY(tp) &&
5114 tp->t_reorderwin > 0 &&
5115 (tp->t_state == TCPS_ESTABLISHED ||
5116 tp->t_state == TCPS_FIN_WAIT_1)) {
5117 tp->t_timer[TCPT_DELAYFR] =
5118 OFFSET_FROM_START(tp,
5119 tp->t_reorderwin);
5120 tp->t_flagsext |= TF_DELAY_RECOVERY;
5121 tcpstat.tcps_delay_recovery++;
5122 tcp_ccdbg_trace(tp, th,
5123 TCP_CC_DELAY_FASTRECOVERY);
5124 break;
5125 }
5126
5127 tcp_rexmt_save_state(tp);
5128 /*
5129 * If the current tcp cc module has
5130 * defined a hook for tasks to run
5131 * before entering FR, call it
5132 */
5133 if (CC_ALGO(tp)->pre_fr != NULL) {
5134 CC_ALGO(tp)->pre_fr(tp);
5135 }
5136 ENTER_FASTRECOVERY(tp);
5137 tp->t_timer[TCPT_REXMT] = 0;
5138 if (!TCP_ACC_ECN_ON(tp) && TCP_ECN_ENABLED(tp)) {
5139 tp->ecn_flags |= TE_SENDCWR;
5140 }
5141
5142 if (SACK_ENABLED(tp)) {
5143 if (TCP_RACK_ENABLED(tp)) {
5144 tcpstat.tcps_rack_recovery_episode++;
5145 tp->t_rack_recovery_episode++;
5146 } else {
5147 tcpstat.tcps_sack_recovery_episode++;
5148 tp->t_sack_recovery_episode++;
5149 }
5150
5151 tp->snd_cwnd = tp->snd_ssthresh;
5152 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
5153
5154 /* Process any window updates */
5155 if (tiwin > tp->snd_wnd) {
5156 tcp_update_window(tp, thflags, th, tiwin, tlen);
5157 }
5158
5159 tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
5160 (void) tcp_output(tp);
5161 goto drop;
5162 }
5163 tp->snd_nxt = th->th_ack;
5164 tp->snd_cwnd = tp->t_maxseg;
5165
5166 /* cwnd is validated after pre_fr() */
5167 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
5168
5169 /* Process any window updates */
5170 if (tiwin > tp->snd_wnd) {
5171 tcp_update_window(tp, thflags, th, tiwin, tlen);
5172 }
5173
5174 (void) tcp_output(tp);
5175 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
5176 tcp_cc_adjust_nonvalidated_cwnd(tp);
5177 } else {
5178 tp->snd_cwnd = tp->snd_ssthresh + tp->t_maxseg * tp->t_dupacks;
5179 }
5180 if (SEQ_GT(onxt, tp->snd_nxt)) {
5181 tp->snd_nxt = onxt;
5182 }
5183
5184 tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
5185 goto drop;
5186 } else if (ALLOW_LIMITED_TRANSMIT(tp) &&
5187 (!(SACK_ENABLED(tp)) || sack_bytes_acked > 0) &&
5188 (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)) > 0) {
5189 u_int32_t incr = (tp->t_maxseg * tp->t_dupacks);
5190
5191 /* Use Limited Transmit algorithm on the first two
5192 * duplicate acks when there is new data to transmit
5193 */
5194 tp->snd_cwnd += incr;
5195 tcpstat.tcps_limited_txt++;
5196 (void) tcp_output(tp);
5197
5198 tcp_ccdbg_trace(tp, th, TCP_CC_LIMITED_TRANSMIT);
5199
5200 /* Reset snd_cwnd back to normal */
5201 tp->snd_cwnd -= incr;
5202 }
5203 }
5204 break;
5205 }
5206 /*
5207 * If the congestion window was inflated to account
5208 * for the other side's cached packets, retract it.
5209 */
5210 if (IN_FASTRECOVERY(tp)) {
5211 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
5212 /*
5213 * If we received an ECE and entered
5214 * recovery, the subsequent ACKs should
5215 * not be treated as partial acks.
5216 */
5217 if (tp->ecn_flags & TE_INRECOVERY) {
5218 goto process_ACK;
5219 }
5220 /* RACK doesn't require inflating cwnd */
5221 if (!TCP_RACK_ENABLED(tp)) {
5222 if (SACK_ENABLED(tp)) {
5223 tcp_sack_partialack(tp, th);
5224 } else {
5225 tcp_newreno_partial_ack(tp, th);
5226 }
5227 tcp_ccdbg_trace(tp, th, TCP_CC_PARTIAL_ACK);
5228 }
5229 } else {
5230 if (tcp_cubic_minor_fixes) {
5231 exiting_fr = 1;
5232 }
5233 EXIT_FASTRECOVERY(tp);
5234 if (CC_ALGO(tp)->post_fr != NULL) {
5235 CC_ALGO(tp)->post_fr(tp, th);
5236 }
5237
5238 if (TCP_RACK_ENABLED(tp)) {
5239 tcp_rack_update_reordering_win_persist(tp);
5240 }
5241
5242 tp->t_pipeack = 0;
5243 tcp_clear_pipeack_state(tp);
5244 tcp_ccdbg_trace(tp, th,
5245 TCP_CC_EXIT_FASTRECOVERY);
5246 }
5247 } else if ((tp->t_flagsext &
5248 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
5249 == (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
5250 /*
5251 * If the ack acknowledges upto snd_recover or if
5252 * it acknowledges all the snd holes, exit
5253 * recovery and cancel the timer. Otherwise,
5254 * this is a partial ack. Wait for recovery timer
5255 * to enter recovery. The snd_holes have already
5256 * been updated.
5257 */
5258 if (SEQ_GEQ(th->th_ack, tp->snd_recover) ||
5259 TAILQ_EMPTY(&tp->snd_holes)) {
5260 tp->t_timer[TCPT_DELAYFR] = 0;
5261 tp->t_flagsext &= ~TF_DELAY_RECOVERY;
5262 EXIT_FASTRECOVERY(tp);
5263 tcp_ccdbg_trace(tp, th,
5264 TCP_CC_EXIT_FASTRECOVERY);
5265 }
5266 } else {
5267 /*
5268 * We were not in fast recovery. Reset the
5269 * duplicate ack counter.
5270 */
5271 tp->t_dupacks = 0;
5272 tp->t_rexmtthresh = tcprexmtthresh;
5273 }
5274
5275 process_ACK:
5276 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
5277 acked = BYTES_ACKED(th, tp);
5278 tcpstat.tcps_rcvackpack++;
5279 tcpstat.tcps_rcvackbyte += acked;
5280
5281 /*
5282 * If the last packet was a retransmit, make sure
5283 * it was not spurious.
5284 *
5285 * This will also take care of congestion window
5286 * adjustment if a last packet was recovered due to a
5287 * tail loss probe.
5288 */
5289 tcp_bad_rexmt_check(tp, th, &to);
5290
5291 /* Recalculate the RTT */
5292 tcp_compute_rtt(tp, &to, th);
5293
5294 /*
5295 * If all outstanding data is acked, stop retransmit
5296 * timer and remember to restart (more output or persist).
5297 * If there is more data to be acked, restart retransmit
5298 * timer, using current (possibly backed-off) value.
5299 */
5300 TCP_RESET_REXMT_STATE(tp);
5301 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
5302 tp->t_rttmin, TCPTV_REXMTMAX,
5303 TCP_ADD_REXMTSLOP(tp));
5304 if (th->th_ack == tp->snd_max) {
5305 tp->t_timer[TCPT_REXMT] = 0;
5306 tp->t_timer[TCPT_PTO] = 0;
5307 tp->t_timer[TCPT_REORDER] = 0;
5308 tcp_rack_reset_segs_retransmitted(tp);
5309 needoutput = 1;
5310 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
5311 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
5312 tp->t_rxtcur);
5313 }
5314
5315 if ((prev_t_state == TCPS_SYN_SENT ||
5316 prev_t_state == TCPS_SYN_RECEIVED) &&
5317 tp->t_state == TCPS_ESTABLISHED) {
5318 TCP_LOG_RTT_INFO(tp);
5319 }
5320
5321 /*
5322 * If no data (only SYN) was ACK'd, skip rest of ACK
5323 * processing.
5324 */
5325 if (acked == 0) {
5326 goto step6;
5327 }
5328
5329 /*
5330 * Process sent segments used for RACK as we need to update
5331 * RACK state before loss detection. Update snd_fack only
5332 * after ACK processing which performs reordering detection.
5333 */
5334 if (TCP_RACK_ENABLED(tp)) {
5335 tcp_segs_doack(tp, th->th_ack, &to);
5336 if (SEQ_LT(tp->snd_fack, highest_sacked_seq)) {
5337 tp->snd_fack = highest_sacked_seq;
5338 }
5339 if (SEQ_LT(tp->snd_fack, th->th_ack)) {
5340 tp->snd_fack = th->th_ack;
5341 }
5342 }
5343 /*
5344 * When outgoing data has been acked (except the SYN+data), we
5345 * mark this connection as "sending good" for TFO.
5346 */
5347 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
5348 !(tp->t_tfo_flags & TFO_F_NO_SNDPROBING) &&
5349 !(th->th_flags & TH_SYN)) {
5350 tp->t_tfo_flags |= TFO_F_NO_SNDPROBING;
5351 }
5352
5353 if ((tp->ecn_flags & TE_SENDIPECT)) {
5354 /*
5355 * draft-ietf-tcpm-accurate-ecn-28
5356 * Accurate ECN feedback processing for data sender,
5357 * Process peer's feedback in received TCP thflags and update s.cep
5358 * Since SYN-ACK has a special encoding, exclude it from below.
5359 * Only perform it before CC is called and snd_una is updated.
5360 */
5361 if (TCP_ACC_ECN_ON(tp) && !(thflags & TH_SYN)) {
5362 /*
5363 * For a server in SYN_RECEIVED state (that switched to
5364 * ESTABLISHED in this ACK, exclude processing the last ACK
5365 */
5366 if (th->th_ack == tp->iss + 1) {
5367 acked = 0;
5368 }
5369 uint32_t pkts_acked = tcp_packets_this_ack(tp, acked);
5370 tp->total_ect_packets_acked += pkts_acked;
5371 /*
5372 * Calculate newly_acked_time used for AccECN feedback parsing
5373 * for data sender if ACK acknowledges packets without data
5374 * if reordering happens and certain packets have same TS.
5375 * Right now, we consider that new time was ACKed if the TS
5376 * was GT previous value, but we need to think about how to
5377 * differentiate between reordering and wrapping when TS is same
5378 * as previous value.
5379 */
5380 bool newly_acked_time = false;
5381 if (acked == 0 && sack_bytes_acked == 0 &&
5382 (to.to_flags & TOF_TS) != 0 && to.to_tsecr != 0 &&
5383 (tp->t_last_ack_tsecr == 0 || TSTMP_GT(to.to_tsecr, tp->t_last_ack_tsecr))) {
5384 newly_acked_time = true;
5385 }
5386 /*
5387 * Update s.cep if bytes have been newly S/ACKed
5388 * otherwise, this ACK has already been superseded.
5389 */
5390 if (acked > 0 || sack_bytes_acked > 0 || newly_acked_time) {
5391 tcp_process_accecn(tp, &to, th, pkts_acked, ace);
5392 }
5393 } else if (TCP_ECN_ENABLED(tp) && (thflags & TH_ECE)) {
5394 /*
5395 * For classic ECN, congestion event is receiving TH_ECE.
5396 * Reduce the congestion window if we haven't
5397 * done so.
5398 */
5399 if (!IN_FASTRECOVERY(tp)) {
5400 /*
5401 * Although we enter Fast Recovery in the below function
5402 * we exit it immediately below as th_ack >= snd_recover
5403 */
5404 tcp_enter_fast_recovery(tp);
5405 tp->ecn_flags |= (TE_INRECOVERY | TE_SENDCWR);
5406 /*
5407 * Also note that the connection received
5408 * ECE atleast once. We increment
5409 * t_ecn_capable_packets_marked when we first
5410 * enter fast recovery.
5411 */
5412 tp->ecn_flags |= TE_RECV_ECN_ECE;
5413 INP_INC_IFNET_STAT(inp, ecn_recv_ece);
5414 tcpstat.tcps_ecn_recv_ece++;
5415 tp->t_ecn_capable_packets_marked++;
5416 tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
5417 }
5418 }
5419 }
5420
5421 /*
5422 * When new data is acked, open the congestion window.
5423 * The specifics of how this is achieved are up to the
5424 * congestion control algorithm in use for this connection.
5425 *
5426 * The calculations in this function assume that snd_una is
5427 * not updated yet.
5428 */
5429 if (!IN_FASTRECOVERY(tp) && !exiting_fr) {
5430 if (CC_ALGO(tp)->ack_rcvd != NULL) {
5431 CC_ALGO(tp)->ack_rcvd(tp, th);
5432 }
5433 tcp_ccdbg_trace(tp, th, TCP_CC_ACK_RCVD);
5434 }
5435 if (acked > so->so_snd.sb_cc) {
5436 tp->snd_wnd -= so->so_snd.sb_cc;
5437 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
5438 ourfinisacked = 1;
5439 } else {
5440 sbdrop(&so->so_snd, acked);
5441 tcp_sbsnd_trim(&so->so_snd);
5442 tp->snd_wnd -= acked;
5443 ourfinisacked = 0;
5444 }
5445 /* detect una wraparound */
5446 if (!IN_FASTRECOVERY(tp) &&
5447 SEQ_GT(tp->snd_una, tp->snd_recover) &&
5448 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
5449 tp->snd_recover = th->th_ack - 1;
5450 }
5451
5452 if (IN_FASTRECOVERY(tp) &&
5453 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
5454 EXIT_FASTRECOVERY(tp);
5455 if (TCP_RACK_ENABLED(tp)) {
5456 tcp_rack_update_reordering_win_persist(tp);
5457 }
5458 }
5459
5460 tcp_update_snd_una(tp, th->th_ack);
5461
5462 if (SACK_ENABLED(tp)) {
5463 if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
5464 tp->snd_recover = tp->snd_una;
5465 }
5466 }
5467 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
5468 tp->snd_nxt = tp->snd_una;
5469 }
5470
5471 /*
5472 * Detect loss based on RACK during ACK processing to mark lost
5473 * segments and call tcp_output. Rest of the ACK processing can
5474 * continue after that.
5475 */
5476 if (TCP_RACK_ENABLED(tp) && tcp_rack_detect_loss_and_arm_timer(tp, 0)) {
5477 if (!IN_FASTRECOVERY(tp)) {
5478 tcp_enter_fast_recovery(tp);
5479 tcpstat.tcps_rack_recovery_episode++;
5480 tp->t_rack_recovery_episode++;
5481 }
5482 tcp_output(tp);
5483 }
5484
5485 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
5486 !TCP_DSACK_SEQ_IN_WINDOW(tp, tp->t_dsack_lastuna,
5487 tp->snd_una)) {
5488 tcp_rxtseg_clean(tp);
5489 }
5490 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
5491 tp->t_bwmeas != NULL) {
5492 tcp_bwmeas_check(tp);
5493 }
5494
5495 write_wakeup = 1;
5496
5497 if (!SLIST_EMPTY(&tp->t_notify_ack)) {
5498 tcp_notify_acknowledgement(tp, so);
5499 }
5500
5501 switch (tp->t_state) {
5502 /*
5503 * In FIN_WAIT_1 STATE in addition to the processing
5504 * for the ESTABLISHED state if our FIN is now acknowledged
5505 * then enter FIN_WAIT_2.
5506 */
5507 case TCPS_FIN_WAIT_1:
5508 if (ourfinisacked) {
5509 /*
5510 * If we can't receive any more
5511 * data, then closing user can proceed.
5512 * Starting the TCPT_2MSL timer is contrary to the
5513 * specification, but if we don't get a FIN
5514 * we'll hang forever.
5515 */
5516 DTRACE_TCP4(state__change, void, NULL,
5517 struct inpcb *, inp,
5518 struct tcpcb *, tp,
5519 int32_t, TCPS_FIN_WAIT_2);
5520 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_2);
5521 tp->t_state = TCPS_FIN_WAIT_2;
5522 if (so->so_state & SS_CANTRCVMORE) {
5523 isconnected = FALSE;
5524 isdisconnected = TRUE;
5525 tcp_set_finwait_timeout(tp);
5526 }
5527 /*
5528 * fall through and make sure we also recognize
5529 * data ACKed with the FIN
5530 */
5531 }
5532 break;
5533
5534 /*
5535 * In CLOSING STATE in addition to the processing for
5536 * the ESTABLISHED state if the ACK acknowledges our FIN
5537 * then enter the TIME-WAIT state, otherwise ignore
5538 * the segment.
5539 */
5540 case TCPS_CLOSING:
5541 if (ourfinisacked) {
5542 DTRACE_TCP4(state__change, void, NULL,
5543 struct inpcb *, inp,
5544 struct tcpcb *, tp,
5545 int32_t, TCPS_TIME_WAIT);
5546 TCP_LOG_STATE(tp, TCPS_TIME_WAIT);
5547 tp->t_state = TCPS_TIME_WAIT;
5548 tcp_canceltimers(tp);
5549 if (tp->t_flagsext & TF_NOTIMEWAIT) {
5550 tp->t_flags |= TF_CLOSING;
5551 } else {
5552 add_to_time_wait(tp, 2 * tcp_msl);
5553 }
5554 isconnected = FALSE;
5555 isdisconnected = TRUE;
5556 }
5557 break;
5558
5559 /*
5560 * In LAST_ACK, we may still be waiting for data to drain
5561 * and/or to be acked, as well as for the ack of our FIN.
5562 * If our FIN is now acknowledged, delete the TCB,
5563 * enter the closed state and return.
5564 */
5565 case TCPS_LAST_ACK:
5566 if (ourfinisacked) {
5567 tp = tcp_close(tp);
5568 goto drop;
5569 }
5570 break;
5571
5572 /*
5573 * In TIME_WAIT state the only thing that should arrive
5574 * is a retransmission of the remote FIN. Acknowledge
5575 * it and restart the finack timer.
5576 */
5577 case TCPS_TIME_WAIT:
5578 add_to_time_wait(tp, 2 * tcp_msl);
5579 goto dropafterack;
5580 }
5581
5582 /*
5583 * If there is a SACK option on the ACK and we
5584 * haven't seen any duplicate acks before, count
5585 * it as a duplicate ack even if the cumulative
5586 * ack is advanced. If the receiver delayed an
5587 * ack and detected loss afterwards, then the ack
5588 * will advance cumulative ack and will also have
5589 * a SACK option. So counting it as one duplicate
5590 * ack is ok.
5591 */
5592 if (tp->t_state == TCPS_ESTABLISHED &&
5593 SACK_ENABLED(tp) && sack_bytes_acked > 0 &&
5594 to.to_nsacks > 0 && tp->t_dupacks == 0 &&
5595 SEQ_LEQ(th->th_ack, tp->snd_una) && tlen == 0 &&
5596 !(tp->t_flagsext & TF_PKTS_REORDERED)) {
5597 tcpstat.tcps_sack_ackadv++;
5598 goto process_dupack;
5599 }
5600 }
5601
5602 step6:
5603 /*
5604 * Update window information.
5605 */
5606 if (tcp_update_window(tp, thflags, th, tiwin, tlen)) {
5607 needoutput = 1;
5608 }
5609
5610 /*
5611 * Process segments with URG.
5612 */
5613 if ((thflags & TH_URG) && th->th_urp &&
5614 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5615 /*
5616 * This is a kludge, but if we receive and accept
5617 * random urgent pointers, we'll crash in
5618 * soreceive. It's hard to imagine someone
5619 * actually wanting to send this much urgent data.
5620 */
5621 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
5622 th->th_urp = 0; /* XXX */
5623 thflags &= ~TH_URG; /* XXX */
5624 goto dodata; /* XXX */
5625 }
5626 /*
5627 * If this segment advances the known urgent pointer,
5628 * then mark the data stream. This should not happen
5629 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
5630 * a FIN has been received from the remote side.
5631 * In these states we ignore the URG.
5632 *
5633 * According to RFC961 (Assigned Protocols),
5634 * the urgent pointer points to the last octet
5635 * of urgent data. We continue, however,
5636 * to consider it to indicate the first octet
5637 * of data past the urgent section as the original
5638 * spec states (in one of two places).
5639 */
5640 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
5641 tp->rcv_up = th->th_seq + th->th_urp;
5642 so->so_oobmark = so->so_rcv.sb_cc +
5643 (tp->rcv_up - tp->rcv_nxt) - 1;
5644 if (so->so_oobmark == 0) {
5645 so->so_state |= SS_RCVATMARK;
5646 }
5647 sohasoutofband(so);
5648 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
5649 }
5650 /*
5651 * Remove out of band data so doesn't get presented to user.
5652 * This can happen independent of advancing the URG pointer,
5653 * but if two URG's are pending at once, some out-of-band
5654 * data may creep in... ick.
5655 */
5656 if (th->th_urp <= (u_int32_t)tlen
5657 #if SO_OOBINLINE
5658 && (so->so_options & SO_OOBINLINE) == 0
5659 #endif
5660 ) {
5661 tcp_pulloutofband(so, th, m,
5662 drop_hdrlen); /* hdr drop is delayed */
5663 }
5664 } else {
5665 /*
5666 * If no out of band data is expected,
5667 * pull receive urgent pointer along
5668 * with the receive window.
5669 */
5670 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) {
5671 tp->rcv_up = tp->rcv_nxt;
5672 }
5673 }
5674 dodata:
5675
5676 /* Set socket's connect or disconnect state correcly before doing data.
5677 * The following might unlock the socket if there is an upcall or a socket
5678 * filter.
5679 */
5680 if (isconnected) {
5681 soisconnected(so);
5682 } else if (isdisconnected) {
5683 soisdisconnected(so);
5684 }
5685
5686 /* Let's check the state of pcb just to make sure that it did not get closed
5687 * when we unlocked above
5688 */
5689 if (inp->inp_state == INPCB_STATE_DEAD) {
5690 /* Just drop the packet that we are processing and return */
5691 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "INPCB_STATE_DEAD");
5692 goto drop;
5693 }
5694
5695 /*
5696 * Process the segment text, merging it into the TCP sequencing queue,
5697 * and arranging for acknowledgment of receipt if necessary.
5698 * This process logically involves adjusting tp->rcv_wnd as data
5699 * is presented to the user (this happens in tcp_usrreq.c,
5700 * case PRU_RCVD). If a FIN has already been received on this
5701 * connection then we just ignore the text.
5702 *
5703 * If we are in SYN-received state and got a valid TFO cookie, we want
5704 * to process the data.
5705 */
5706 if ((tlen || (thflags & TH_FIN)) &&
5707 TCPS_HAVERCVDFIN(tp->t_state) == 0 &&
5708 (TCPS_HAVEESTABLISHED(tp->t_state) ||
5709 (tp->t_state == TCPS_SYN_RECEIVED &&
5710 (tp->t_tfo_flags & TFO_F_COOKIE_VALID)))) {
5711 tcp_seq save_start = th->th_seq;
5712 tcp_seq save_end = th->th_seq + tlen;
5713 m_adj(m, drop_hdrlen); /* delayed header drop */
5714 /*
5715 * Insert segment which includes th into TCP reassembly queue
5716 * with control block tp. Set thflags to whether reassembly now
5717 * includes a segment with FIN. This handles the common case
5718 * inline (segment is the next to be received on an established
5719 * connection, and the queue is empty), avoiding linkage into
5720 * and removal from the queue and repetition of various
5721 * conversions.
5722 * Set DELACK for segments received in order, but ack
5723 * immediately when segments are out of order (so
5724 * fast retransmit can work).
5725 */
5726 if (th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
5727 TCP_INC_VAR(tp->t_unacksegs, segment_count);
5728
5729 /* Calculate the RTT on the receiver */
5730 tcp_compute_rcv_rtt(tp, &to, th);
5731
5732 if (DELAY_ACK(tp, th) &&
5733 ((tp->t_flags & TF_ACKNOW) == 0)) {
5734 if ((tp->t_flags & TF_DELACK) == 0) {
5735 tp->t_flags |= TF_DELACK;
5736 tp->t_timer[TCPT_DELACK] =
5737 OFFSET_FROM_START(tp, tcp_delack);
5738 }
5739 } else {
5740 tp->t_flags |= TF_ACKNOW;
5741 }
5742 tp->rcv_nxt += tlen;
5743 /* Update highest received sequence and its timestamp */
5744 if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
5745 tp->rcv_high = tp->rcv_nxt;
5746 if (to.to_flags & TOF_TS) {
5747 tp->tsv_high = to.to_tsval;
5748 }
5749 }
5750
5751 thflags = th->th_flags & TH_FIN;
5752 TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
5753 tcpstat.tcps_rcvbyte += tlen;
5754 if (nstat_collect) {
5755 INP_ADD_STAT(inp, ifnet_count_type,
5756 rxpackets, 1);
5757 INP_ADD_STAT(inp, ifnet_count_type,
5758 rxbytes, tlen);
5759 inp_set_activity_bitmap(inp);
5760 }
5761 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5762 if (TCP_USE_RLEDBAT(tp, so) &&
5763 tcp_cc_rledbat.data_rcvd != NULL) {
5764 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5765 }
5766
5767 so_recv_data_stat(so, m, drop_hdrlen);
5768
5769 if (isipv6) {
5770 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5771 ip6 = (struct ip6_hdr *)&saved_hdr[0];
5772 } else {
5773 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5774 ip = (struct ip *)&saved_hdr[0];
5775 }
5776 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5777
5778 if (th->th_flags & TH_PUSH) {
5779 tp->t_flagsext |= TF_LAST_IS_PSH;
5780 } else {
5781 tp->t_flagsext &= ~TF_LAST_IS_PSH;
5782 }
5783
5784 if (sbappendstream_rcvdemux(so, m)) {
5785 read_wakeup = 1;
5786 }
5787 th = &saved_tcphdr;
5788 } else {
5789 if (isipv6) {
5790 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5791 ip6 = (struct ip6_hdr *)&saved_hdr[0];
5792 } else {
5793 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5794 ip = (struct ip *)&saved_hdr[0];
5795 }
5796
5797 /* Update highest received sequence and its timestamp */
5798 if (SEQ_LT(tp->rcv_high, th->th_seq + tlen)) {
5799 tp->rcv_high = th->th_seq + tlen;
5800 if (to.to_flags & TOF_TS) {
5801 tp->tsv_high = to.to_tsval;
5802 }
5803 }
5804
5805 /*
5806 * Calculate the RTT on the receiver,
5807 * even if OOO segment is received.
5808 */
5809 tcp_compute_rcv_rtt(tp, &to, th);
5810
5811 if (tcp_autotune_reorder) {
5812 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5813 }
5814 if (TCP_USE_RLEDBAT(tp, so) &&
5815 tcp_cc_rledbat.data_rcvd != NULL) {
5816 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5817 }
5818
5819 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5820 thflags = tcp_reass(tp, th, &tlen, m, ifp, &read_wakeup);
5821 th = &saved_tcphdr;
5822 tp->t_flags |= TF_ACKNOW;
5823 }
5824
5825 if ((tlen > 0 || (th->th_flags & TH_FIN)) && SACK_ENABLED(tp)) {
5826 if (th->th_flags & TH_FIN) {
5827 save_end++;
5828 }
5829 tcp_update_sack_list(tp, save_start, save_end);
5830 }
5831
5832 tcp_adaptive_rwtimo_check(tp, tlen);
5833
5834 if (tlen > 0) {
5835 tcp_tfo_rcv_data(tp);
5836 }
5837
5838 if (tp->t_flags & TF_DELACK) {
5839 if (isipv6) {
5840 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5841 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
5842 th->th_seq, th->th_ack, th->th_win);
5843 } else {
5844 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5845 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
5846 th->th_seq, th->th_ack, th->th_win);
5847 }
5848 }
5849 } else {
5850 if ((so->so_flags & SOF_MP_SUBFLOW) && tlen == 0 &&
5851 (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN) &&
5852 (m->m_pkthdr.pkt_flags & PKTF_MPTCP)) {
5853 m_adj(m, drop_hdrlen); /* delayed header drop */
5854 /*
5855 * 0-length DATA_FIN. The rlen is actually 0. We special-case the
5856 * byte consumed by the dfin in mptcp_input and mptcp_reass_present
5857 */
5858 m->m_pkthdr.mp_rlen = 0;
5859 mptcp_input(tptomptp(tp)->mpt_mpte, m);
5860 tp->t_flags |= TF_ACKNOW;
5861 } else {
5862 m_freem(m);
5863 }
5864 thflags &= ~TH_FIN;
5865 }
5866 /*
5867 * We increment t_unacksegs_ce for both data segments and pure ACKs
5868 * No need to increment if a FIN has already been received.
5869 */
5870 if (TCP_ACC_ECN_ON(tp) && TCPS_HAVEESTABLISHED(tp->t_state) &&
5871 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5872 if (ip_ecn == IPTOS_ECN_CE) {
5873 TCP_INC_VAR(tp->t_unacksegs_ce, segment_count);
5874 }
5875 /*
5876 * Send an ACK immediately if there is a change in IP ECN
5877 * from non-CE to CE.
5878 * If new data is delivered, then ACK for every 2 CE marks,
5879 * otherwise ACK for every 3 CE marks
5880 */
5881 if ((ip_ecn == IPTOS_ECN_CE && ip_ecn != tp->t_prev_ip_ecn) ||
5882 (tp->t_unacksegs_ce >= 2 && tp->last_ack_sent != tp->rcv_nxt) ||
5883 tp->t_unacksegs_ce >= 3) {
5884 tp->t_flags |= TF_ACKNOW;
5885 }
5886 tp->t_prev_ip_ecn = ip_ecn;
5887 }
5888 /*
5889 * If FIN is received ACK the FIN and let the user know
5890 * that the connection is closing.
5891 */
5892 if (thflags & TH_FIN) {
5893 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5894 socantrcvmore(so);
5895 /*
5896 * If connection is half-synchronized
5897 * (ie NEEDSYN flag on) then delay ACK,
5898 * so it may be piggybacked when SYN is sent.
5899 * Otherwise, since we received a FIN then no
5900 * more input can be expected, send ACK now.
5901 */
5902 TCP_INC_VAR(tp->t_unacksegs, segment_count);
5903 tp->t_flags |= TF_ACKNOW;
5904 tp->rcv_nxt++;
5905 }
5906 switch (tp->t_state) {
5907 /*
5908 * In SYN_RECEIVED and ESTABLISHED STATES
5909 * enter the CLOSE_WAIT state.
5910 */
5911 case TCPS_SYN_RECEIVED:
5912 tp->t_starttime = tcp_now;
5913 OS_FALLTHROUGH;
5914 case TCPS_ESTABLISHED:
5915 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5916 struct tcpcb *, tp, int32_t, TCPS_CLOSE_WAIT);
5917 TCP_LOG_STATE(tp, TCPS_CLOSE_WAIT);
5918 tp->t_state = TCPS_CLOSE_WAIT;
5919 break;
5920
5921 /*
5922 * If still in FIN_WAIT_1 STATE FIN has not been acked so
5923 * enter the CLOSING state.
5924 */
5925 case TCPS_FIN_WAIT_1:
5926 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5927 struct tcpcb *, tp, int32_t, TCPS_CLOSING);
5928 TCP_LOG_STATE(tp, TCPS_CLOSING);
5929 tp->t_state = TCPS_CLOSING;
5930 break;
5931
5932 /*
5933 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5934 * starting the time-wait timer, turning off the other
5935 * standard timers.
5936 */
5937 case TCPS_FIN_WAIT_2:
5938 DTRACE_TCP4(state__change, void, NULL,
5939 struct inpcb *, inp,
5940 struct tcpcb *, tp,
5941 int32_t, TCPS_TIME_WAIT);
5942 TCP_LOG_STATE(tp, TCPS_TIME_WAIT);
5943 tp->t_state = TCPS_TIME_WAIT;
5944 tcp_canceltimers(tp);
5945 tp->t_flags |= TF_ACKNOW;
5946 if (tp->t_flagsext & TF_NOTIMEWAIT) {
5947 tp->t_flags |= TF_CLOSING;
5948 } else {
5949 add_to_time_wait(tp, 2 * tcp_msl);
5950 }
5951 soisdisconnected(so);
5952 break;
5953
5954 /*
5955 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5956 */
5957 case TCPS_TIME_WAIT:
5958 add_to_time_wait(tp, 2 * tcp_msl);
5959 break;
5960 }
5961 }
5962 if (read_wakeup) {
5963 mptcp_handle_input(so);
5964 }
5965
5966 /*
5967 * Return any desired output.
5968 */
5969 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
5970 (void) tcp_output(tp);
5971 }
5972
5973 tcp_check_timer_state(tp);
5974
5975 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5976
5977 socket_unlock(so, 1);
5978 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5979 return;
5980
5981 dropafterack:
5982 /*
5983 * Generate an ACK dropping incoming segment if it occupies
5984 * sequence space, where the ACK reflects our state.
5985 *
5986 * We can now skip the test for the RST flag since all
5987 * paths to this code happen after packets containing
5988 * RST have been dropped.
5989 *
5990 * In the SYN-RECEIVED state, don't send an ACK unless the
5991 * segment we received passes the SYN-RECEIVED ACK test.
5992 * If it fails send a RST. This breaks the loop in the
5993 * "LAND" DoS attack, and also prevents an ACK storm
5994 * between two listening ports that have been sent forged
5995 * SYN segments, each with the source address of the other.
5996 */
5997 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
5998 (SEQ_GT(tp->snd_una, th->th_ack) ||
5999 SEQ_GT(th->th_ack, tp->snd_max))) {
6000 IF_TCP_STATINC(ifp, dospacket);
6001 goto dropwithreset;
6002 }
6003 m_freem(m);
6004 tp->t_flags |= TF_ACKNOW;
6005
6006 (void) tcp_output(tp);
6007
6008 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
6009
6010 /* Don't need to check timer state as we should have done it during tcp_output */
6011 socket_unlock(so, 1);
6012 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
6013 return;
6014 dropwithresetnosock:
6015 nosock = 1;
6016 dropwithreset:
6017 /*
6018 * Generate a RST, dropping incoming segment.
6019 * Make ACK acceptable to originator of segment.
6020 * Don't bother to respond if destination was broadcast/multicast.
6021 */
6022 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST)) {
6023 goto drop;
6024 }
6025 if (isipv6) {
6026 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
6027 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
6028 goto drop;
6029 }
6030 } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
6031 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
6032 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
6033 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
6034 goto drop;
6035 }
6036 /* IPv6 anycast check is done at tcp6_input() */
6037
6038 bzero(&tra, sizeof(tra));
6039 tra.ifscope = ifscope;
6040 tra.awdl_unrestricted = 1;
6041 tra.intcoproc_allowed = 1;
6042 tra.management_allowed = 1;
6043 if (thflags & TH_ACK) {
6044 /* mtod() below is safe as long as hdr dropping is delayed */
6045 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
6046 TH_RST, &tra);
6047 } else {
6048 if (thflags & TH_SYN) {
6049 tlen++;
6050 }
6051 /* mtod() below is safe as long as hdr dropping is delayed */
6052 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
6053 (tcp_seq)0, TH_RST | TH_ACK, &tra);
6054 }
6055 /* destroy temporarily created socket */
6056 if (dropsocket) {
6057 (void) soabort(so);
6058 socket_unlock(so, 1);
6059 } else if ((inp != NULL) && (nosock == 0)) {
6060 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
6061
6062 socket_unlock(so, 1);
6063 }
6064 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
6065 return;
6066 dropnosock:
6067 nosock = 1;
6068 drop:
6069 /*
6070 * Drop space held by incoming segment and return.
6071 */
6072 if (isipv6 == 0) {
6073 if (ip == NULL) {
6074 ip = mtod(m, struct ip *);
6075 }
6076 /* add back the header length */
6077 ip->ip_len += (ip->ip_hl << 2);
6078 HTONS(ip->ip_len);
6079 HTONS(ip->ip_off);
6080
6081 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
6082 } else if (ip6 == NULL) {
6083 ip6 = mtod(m, struct ip6_hdr *);
6084
6085 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
6086 }
6087 if (is_th_swapped) {
6088 HTONL(th->th_seq);
6089 HTONL(th->th_ack);
6090 HTONS(th->th_win);
6091 HTONS(th->th_urp);
6092 }
6093 m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
6094 /* destroy temporarily created socket */
6095 if (dropsocket) {
6096 (void) soabort(so);
6097 socket_unlock(so, 1);
6098 } else if (nosock == 0) {
6099 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
6100
6101 socket_unlock(so, 1);
6102 }
6103 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
6104 return;
6105 }
6106
6107 /*
6108 * Parse TCP options and place in tcpopt.
6109 */
6110 static void
tcp_dooptions(struct tcpcb * tp,u_char * cp,int cnt,struct tcphdr * th,struct tcpopt * to)6111 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
6112 struct tcpopt *to)
6113 {
6114 u_short mss = 0;
6115 uint8_t opt, optlen;
6116
6117 for (; cnt > 0; cnt -= optlen, cp += optlen) {
6118 opt = cp[0];
6119 if (opt == TCPOPT_EOL) {
6120 break;
6121 }
6122 if (opt == TCPOPT_NOP) {
6123 optlen = 1;
6124 } else {
6125 if (cnt < 2) {
6126 break;
6127 }
6128 optlen = cp[1];
6129 if (optlen < 2 || optlen > cnt) {
6130 break;
6131 }
6132 }
6133 switch (opt) {
6134 default:
6135 continue;
6136
6137 case TCPOPT_MAXSEG:
6138 if (optlen != TCPOLEN_MAXSEG) {
6139 continue;
6140 }
6141 if (!(th->th_flags & TH_SYN)) {
6142 continue;
6143 }
6144 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
6145 NTOHS(mss);
6146 to->to_mss = mss;
6147 to->to_flags |= TOF_MSS;
6148 break;
6149
6150 case TCPOPT_WINDOW:
6151 if (optlen != TCPOLEN_WINDOW) {
6152 continue;
6153 }
6154 if (!(th->th_flags & TH_SYN)) {
6155 continue;
6156 }
6157 to->to_flags |= TOF_SCALE;
6158 to->to_requested_s_scale = MIN(cp[2], TCP_MAX_WINSHIFT);
6159 break;
6160
6161 case TCPOPT_TIMESTAMP:
6162 if (optlen != TCPOLEN_TIMESTAMP) {
6163 continue;
6164 }
6165 to->to_flags |= TOF_TS;
6166 bcopy((char *)cp + 2,
6167 (char *)&to->to_tsval, sizeof(to->to_tsval));
6168 NTOHL(to->to_tsval);
6169 bcopy((char *)cp + 6,
6170 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
6171 NTOHL(to->to_tsecr);
6172 to->to_tsecr -= tp->t_ts_offset;
6173 /* Re-enable sending Timestamps if we received them */
6174 if (!(tp->t_flags & TF_REQ_TSTMP) && tcp_do_timestamps) {
6175 tp->t_flags |= TF_REQ_TSTMP;
6176 }
6177 break;
6178 case TCPOPT_SACK_PERMITTED:
6179 if (optlen != TCPOLEN_SACK_PERMITTED) {
6180 continue;
6181 }
6182 if (th->th_flags & TH_SYN) {
6183 to->to_flags |= TOF_SACK;
6184 }
6185 break;
6186 case TCPOPT_SACK:
6187 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) {
6188 continue;
6189 }
6190 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
6191 to->to_sacks = cp + 2;
6192 tcpstat.tcps_sack_rcv_blocks++;
6193
6194 break;
6195 case TCPOPT_FASTOPEN:
6196 if (optlen == TCPOLEN_FASTOPEN_REQ) {
6197 if (tp->t_state != TCPS_LISTEN) {
6198 continue;
6199 }
6200
6201 to->to_flags |= TOF_TFOREQ;
6202 } else {
6203 if (optlen < TCPOLEN_FASTOPEN_REQ ||
6204 (optlen - TCPOLEN_FASTOPEN_REQ) > TFO_COOKIE_LEN_MAX ||
6205 (optlen - TCPOLEN_FASTOPEN_REQ) < TFO_COOKIE_LEN_MIN) {
6206 continue;
6207 }
6208 if (tp->t_state != TCPS_LISTEN &&
6209 tp->t_state != TCPS_SYN_SENT) {
6210 continue;
6211 }
6212
6213 to->to_flags |= TOF_TFO;
6214 to->to_tfo = cp + 1;
6215 }
6216
6217 break;
6218 case TCPOPT_ACCECN0:
6219 case TCPOPT_ACCECN1:
6220 if (optlen < (TCPOLEN_ACCECN_EMPTY + 1 * TCPOLEN_ACCECN_COUNTER) ||
6221 (optlen - 2) % TCPOLEN_ACCECN_COUNTER != 0) {
6222 continue;
6223 }
6224 to->to_num_accecn = (optlen - 2) / TCPOLEN_ACCECN_COUNTER;
6225 to->to_accecn = cp + 2;
6226 if (opt == TCPOPT_ACCECN0) {
6227 to->to_accecn_order = 0;
6228 } else if (opt == TCPOPT_ACCECN1) {
6229 to->to_accecn_order = 1;
6230 }
6231 break;
6232
6233 #if MPTCP
6234 case TCPOPT_MULTIPATH:
6235 tcp_do_mptcp_options(tp, cp, th, to, optlen);
6236 break;
6237 #endif /* MPTCP */
6238 }
6239 }
6240 }
6241
6242 static void
tcp_finalize_options(struct tcpcb * tp,struct tcpopt * to,unsigned int ifscope)6243 tcp_finalize_options(struct tcpcb *tp, struct tcpopt *to, unsigned int ifscope)
6244 {
6245 if (to->to_flags & TOF_TS) {
6246 tp->t_flags |= TF_RCVD_TSTMP;
6247 tp->ts_recent = to->to_tsval;
6248 tp->ts_recent_age = tcp_now;
6249 }
6250 if (to->to_flags & TOF_MSS) {
6251 tcp_mss(tp, to->to_mss, ifscope);
6252 }
6253 if (SACK_ENABLED(tp)) {
6254 if (!(to->to_flags & TOF_SACK)) {
6255 tp->t_flagsext &= ~(TF_SACK_ENABLE);
6256 } else {
6257 tp->t_flags |= TF_SACK_PERMIT;
6258 }
6259 }
6260 if (to->to_flags & TOF_SCALE) {
6261 tp->t_flags |= TF_RCVD_SCALE;
6262 tp->requested_s_scale = to->to_requested_s_scale;
6263
6264 /* Re-enable window scaling, if the option is received */
6265 if (tp->request_r_scale > 0) {
6266 tp->t_flags |= TF_REQ_SCALE;
6267 }
6268 }
6269 }
6270
6271 /*
6272 * Pull out of band byte out of a segment so
6273 * it doesn't appear in the user's data queue.
6274 * It is still reflected in the segment length for
6275 * sequencing purposes.
6276 *
6277 * @param off delayed to be droped hdrlen
6278 */
6279 static void
tcp_pulloutofband(struct socket * so,struct tcphdr * th,struct mbuf * m,int off)6280 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
6281 {
6282 int cnt = off + th->th_urp - 1;
6283
6284 while (cnt >= 0) {
6285 if (m->m_len > cnt) {
6286 char *cp = mtod(m, caddr_t) + cnt;
6287 struct tcpcb *tp = sototcpcb(so);
6288
6289 tp->t_iobc = *cp;
6290 tp->t_oobflags |= TCPOOB_HAVEDATA;
6291 bcopy(cp + 1, cp, (unsigned)(m->m_len - cnt - 1));
6292 m->m_len--;
6293 if (m->m_flags & M_PKTHDR) {
6294 m->m_pkthdr.len--;
6295 }
6296 return;
6297 }
6298 cnt -= m->m_len;
6299 m = m->m_next;
6300 if (m == 0) {
6301 break;
6302 }
6303 }
6304 panic("tcp_pulloutofband");
6305 }
6306
6307 uint32_t
get_base_rtt(struct tcpcb * tp)6308 get_base_rtt(struct tcpcb *tp)
6309 {
6310 struct rtentry *rt = tp->t_inpcb->inp_route.ro_rt;
6311 return (rt == NULL) ? 0 : rt->rtt_min;
6312 }
6313
6314 static void
update_curr_rtt(struct tcpcb * tp,uint32_t rtt)6315 update_curr_rtt(struct tcpcb * tp, uint32_t rtt)
6316 {
6317 tp->curr_rtt_index = (tp->curr_rtt_index + 1) % NCURR_RTT_HIST;
6318 tp->curr_rtt_hist[tp->curr_rtt_index] = rtt;
6319
6320 /* forget the old value and update minimum */
6321 tp->curr_rtt_min = 0;
6322 for (int i = 0; i < NCURR_RTT_HIST; ++i) {
6323 if (tp->curr_rtt_hist[i] != 0 && (tp->curr_rtt_min == 0 ||
6324 tp->curr_rtt_hist[i] < tp->curr_rtt_min)) {
6325 tp->curr_rtt_min = tp->curr_rtt_hist[i];
6326 }
6327 }
6328 }
6329
6330 /* Each value of RTT base represents the minimum RTT seen in a minute.
6331 * We keep upto N_RTT_BASE minutes worth of history.
6332 */
6333 void
update_base_rtt(struct tcpcb * tp,uint32_t rtt)6334 update_base_rtt(struct tcpcb *tp, uint32_t rtt)
6335 {
6336 u_int32_t base_rtt, i;
6337 struct rtentry *rt;
6338
6339 if ((rt = tp->t_inpcb->inp_route.ro_rt) == NULL) {
6340 return;
6341 }
6342 if (rt->rtt_expire_ts == 0) {
6343 RT_LOCK_SPIN(rt);
6344 if (rt->rtt_expire_ts != 0) {
6345 RT_UNLOCK(rt);
6346 goto update;
6347 }
6348 rt->rtt_expire_ts = tcp_now;
6349 rt->rtt_index = 0;
6350 rt->rtt_hist[0] = rtt;
6351 rt->rtt_min = rtt;
6352 RT_UNLOCK(rt);
6353
6354 tp->curr_rtt_index = 0;
6355 tp->curr_rtt_hist[0] = rtt;
6356 tp->curr_rtt_min = rtt;
6357 return;
6358 }
6359 update:
6360 #if TRAFFIC_MGT
6361 /*
6362 * If the recv side is being throttled, check if the
6363 * current RTT is closer to the base RTT seen in
6364 * first (recent) two slots. If so, unthrottle the stream.
6365 */
6366 if ((tp->t_flagsext & TF_RECV_THROTTLE) &&
6367 (int)(tcp_now - tp->t_recv_throttle_ts) >= TCP_RECV_THROTTLE_WIN) {
6368 base_rtt = rt->rtt_min;
6369 if (tp->t_rttcur <= (base_rtt + target_qdelay)) {
6370 tp->t_flagsext &= ~TF_RECV_THROTTLE;
6371 tp->t_recv_throttle_ts = 0;
6372 }
6373 }
6374 #endif /* TRAFFIC_MGT */
6375
6376 /* Update the next current RTT sample */
6377 update_curr_rtt(tp, rtt);
6378
6379 if ((int)(tcp_now - rt->rtt_expire_ts) >=
6380 TCP_RTT_HISTORY_EXPIRE_TIME) {
6381 RT_LOCK_SPIN(rt);
6382 /* check the condition again to avoid race */
6383 if ((int)(tcp_now - rt->rtt_expire_ts) >=
6384 TCP_RTT_HISTORY_EXPIRE_TIME) {
6385 /* Set the base rtt to 0 for idle periods */
6386 uint32_t times = MIN((tcp_now - rt->rtt_expire_ts) /
6387 TCP_RTT_HISTORY_EXPIRE_TIME, NRTT_HIST + 1);
6388
6389 for (i = rt->rtt_index + 1; i < rt->rtt_index + times; i++) {
6390 rt->rtt_hist[i % NRTT_HIST] = 0;
6391 }
6392
6393 rt->rtt_index = i % NRTT_HIST;
6394 rt->rtt_hist[rt->rtt_index] = rtt;
6395 rt->rtt_expire_ts = tcp_now;
6396 } else {
6397 rt->rtt_hist[rt->rtt_index] =
6398 min(rt->rtt_hist[rt->rtt_index], rtt);
6399 }
6400 /* forget the old value and update minimum */
6401 rt->rtt_min = 0;
6402 for (i = 0; i < NRTT_HIST; ++i) {
6403 if (rt->rtt_hist[i] != 0 &&
6404 (rt->rtt_min == 0 ||
6405 rt->rtt_hist[i] < rt->rtt_min)) {
6406 rt->rtt_min = rt->rtt_hist[i];
6407 }
6408 }
6409 RT_UNLOCK(rt);
6410 } else {
6411 rt->rtt_hist[rt->rtt_index] =
6412 min(rt->rtt_hist[rt->rtt_index], rtt);
6413 if (rt->rtt_min == 0) {
6414 rt->rtt_min = rtt;
6415 } else {
6416 rt->rtt_min = min(rt->rtt_min, rtt);
6417 }
6418 }
6419 }
6420
6421 /*
6422 * If we have a timestamp reply, update smoothed RTT. If no timestamp is
6423 * present but transmit timer is running and timed sequence number was
6424 * acked, update smoothed RTT.
6425 *
6426 * If timestamps are supported, a receiver can update RTT even if
6427 * there is no outstanding data.
6428 *
6429 * Some boxes send broken timestamp replies during the SYN+ACK phase,
6430 * ignore timestamps of 0or we could calculate a huge RTT and blow up
6431 * the retransmit timer.
6432 */
6433 static void
tcp_compute_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)6434 tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
6435 {
6436 int rtt = 0;
6437 VERIFY(to != NULL && th != NULL);
6438 if (tp->t_rtttime != 0 && SEQ_GT(th->th_ack, tp->t_rtseq)) {
6439 u_int32_t pipe_ack_val;
6440 rtt = tcp_now - tp->t_rtttime;
6441 if (rtt == 0) {
6442 /*
6443 * Make adjustment for sub ms RTT when
6444 * timestamps are not used.
6445 */
6446 rtt = 1;
6447 }
6448 /*
6449 * Compute pipe ack -- the amount of data acknowledged
6450 * in the last RTT -- only works for sender
6451 */
6452 if (SEQ_GT(th->th_ack, tp->t_pipeack_lastuna)) {
6453 pipe_ack_val = th->th_ack - tp->t_pipeack_lastuna;
6454 /* Update the sample */
6455 tp->t_pipeack_sample[tp->t_pipeack_ind++] =
6456 pipe_ack_val;
6457 tp->t_pipeack_ind %= TCP_PIPEACK_SAMPLE_COUNT;
6458
6459 /* Compute the max of the pipeack samples */
6460 pipe_ack_val = tcp_get_max_pipeack(tp);
6461 tp->t_pipeack = (pipe_ack_val >
6462 tcp_initial_cwnd(tp)) ?
6463 pipe_ack_val : 0;
6464 }
6465 /* start another measurement */
6466 tp->t_rtttime = 0;
6467 }
6468 if (((to->to_flags & TOF_TS) != 0) &&
6469 (to->to_tsecr != 0) &&
6470 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
6471 tcp_xmit_timer(tp, (tcp_now - to->to_tsecr),
6472 to->to_tsecr, th->th_ack);
6473 } else if (rtt > 0) {
6474 tcp_xmit_timer(tp, rtt, 0, th->th_ack);
6475 }
6476 }
6477
6478 static void
tcp_compute_rcv_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)6479 tcp_compute_rcv_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
6480 {
6481 uint32_t rtt = 0, delta = 0;
6482 VERIFY(to != NULL && th != NULL);
6483
6484 /* Calculate RTT */
6485 if (((to->to_flags & TOF_TS) != 0) && (to->to_tsecr != 0) &&
6486 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
6487 /* Timestamp is supported */
6488 rtt = tcp_now - to->to_tsecr;
6489 if (rtt == 0) {
6490 /* Make adjustment for sub ms RTT */
6491 rtt = 1;
6492 }
6493 } else if ((to->to_flags & TOF_TS) == 0) {
6494 /*
6495 * Timestamp is not supported, 1RTT is roughly
6496 * the time to receive one full window of data
6497 * Currently, RTT calculated this way is only used
6498 * for auto-tuning.
6499 */
6500 if (tp->rcv_rtt_est_ts != 0) {
6501 if (SEQ_LT(tp->rcv_nxt, tp->rcv_rtt_est_seq)) {
6502 /* Haven't received a full window yet */
6503 return;
6504 } else {
6505 rtt = tcp_now - tp->rcv_rtt_est_ts;
6506 if (rtt == 0) {
6507 /* Make adjustment for sub ms RTT */
6508 rtt = 1;
6509 }
6510 }
6511 } else {
6512 /* Use default value when no RTT measurement */
6513 rtt = TCPTV_RCVNOTS_QUANTUM;
6514 }
6515 /* Restart the measurement */
6516 tp->rcv_rtt_est_ts = tcp_now;
6517 tp->rcv_rtt_est_seq = tp->rcv_nxt + tp->rcv_wnd;
6518 }
6519
6520 /* Update receiver's SRTT */
6521 if (tp->rcv_srtt != 0) {
6522 /*
6523 * Use the smoothed rtt formula,
6524 * (srtt = rtt/8 + srtt*7/8) in fixed point
6525 */
6526 delta = (rtt << TCP_DELTA_SHIFT)
6527 - (tp->rcv_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6528
6529 if ((tp->rcv_srtt += delta) <= 0) {
6530 tp->rcv_srtt = 1;
6531 }
6532 } else {
6533 /* No previous measurement */
6534 tp->rcv_srtt = rtt << TCP_RTT_SHIFT;
6535 }
6536
6537 /*
6538 * For current RTT, base RTT and current RTT over k samples,
6539 * we are using the same state for both sender and receiver
6540 * as the most recent sample is always updated before any
6541 * other processing, i.e. the sender will not end up with
6542 * a high RTT due to the receiver.
6543 */
6544 tp->t_rttcur = rtt;
6545 update_base_rtt(tp, rtt);
6546 }
6547
6548 /*
6549 * Collect new round-trip time estimate and update averages and
6550 * current timeout.
6551 */
6552 static void
tcp_xmit_timer(struct tcpcb * tp,int rtt,u_int32_t tsecr,tcp_seq th_ack)6553 tcp_xmit_timer(struct tcpcb *tp, int rtt,
6554 u_int32_t tsecr, tcp_seq th_ack)
6555 {
6556 VERIFY(rtt >= 0);
6557 int delta;
6558 int old_srtt = tp->t_srtt;
6559 int old_rttvar = tp->t_rttvar;
6560 bool log_rtt = false;
6561
6562 if (rtt == 0) {
6563 /*
6564 * As rtt has millisecond precision,
6565 * make adjustment for sub ms RTT
6566 */
6567 rtt = 1;
6568 }
6569
6570 if (rtt > 4 * TCPTV_MSL) {
6571 TCP_LOG(tp, "%s: rtt is %d - maxing it at 4 x MSL\n", __func__, rtt);
6572 /*
6573 * We compute RTT either based on the time-to-ACK a packet,
6574 * if TSval is disabled or based on the TSecr value.
6575 * If there is a middlebox messing up the TSecr value, we can
6576 * end up having HUGE rtt values, causing all kinds of problems.
6577 * Let's protect against this by capping RTT to 4*MSL
6578 * (60seconds).
6579 */
6580 rtt = 4 * TCPTV_MSL;
6581 }
6582
6583 /*
6584 * On AWDL interface, the initial RTT measurement on SYN
6585 * can be wrong due to peer caching. Avoid the first RTT
6586 * measurement as it might skew up the RTO.
6587 * <rdar://problem/28739046>
6588 */
6589 if (tp->t_inpcb->inp_last_outifp != NULL &&
6590 (tp->t_inpcb->inp_last_outifp->if_eflags & IFEF_AWDL) &&
6591 th_ack == tp->iss + 1) {
6592 return;
6593 }
6594
6595 if (tp->t_flagsext & TF_RECOMPUTE_RTT) {
6596 if (SEQ_GT(th_ack, tp->snd_una) &&
6597 SEQ_LEQ(th_ack, tp->snd_max) &&
6598 (tsecr == 0 ||
6599 TSTMP_GEQ(tsecr, tp->t_badrexmt_time))) {
6600 /*
6601 * We received a new ACK after a
6602 * spurious timeout. Adapt retransmission
6603 * timer as described in rfc 4015.
6604 */
6605 tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
6606 tp->t_badrexmt_time = 0;
6607 tp->t_srtt = max(tp->t_srtt_prev, rtt);
6608 tp->t_srtt = tp->t_srtt << TCP_RTT_SHIFT;
6609 tp->t_rttvar = max(tp->t_rttvar_prev, (rtt >> 1));
6610 tp->t_rttvar = tp->t_rttvar << TCP_RTTVAR_SHIFT;
6611
6612 if (tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6613 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6614 }
6615
6616 goto compute_rto;
6617 } else {
6618 return;
6619 }
6620 }
6621
6622 tcpstat.tcps_rttupdated++;
6623 tp->t_rttupdated++;
6624
6625 tp->t_rttcur = rtt;
6626 update_base_rtt(tp, rtt);
6627
6628 if (tp->t_srtt != 0) {
6629 /*
6630 * srtt is stored as fixed point with 5 bits after the
6631 * binary point (i.e., scaled by 32). The following magic
6632 * is equivalent to the smoothing algorithm in rfc793 with
6633 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
6634 * point).
6635 *
6636 * Freebsd adjusts rtt to origin 0 by subtracting 1
6637 * from the provided rtt value. This was required because
6638 * of the way t_rtttime was initiailised to 1 before.
6639 * Since we changed t_rtttime to be based on
6640 * tcp_now, this extra adjustment is not needed.
6641 */
6642 delta = (rtt << TCP_DELTA_SHIFT)
6643 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6644
6645 if ((tp->t_srtt += delta) <= 0) {
6646 tp->t_srtt = 1;
6647 }
6648
6649 /*
6650 * We accumulate a smoothed rtt variance (actually, a
6651 * smoothed mean difference), then set the retransmit
6652 * timer to smoothed rtt + 4 times the smoothed variance.
6653 * rttvar is stored as fixed point with 4 bits after the
6654 * binary point (scaled by 16). The following is
6655 * equivalent to rfc793 smoothing with an alpha of .75
6656 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
6657 * rfc793's wired-in beta.
6658 */
6659 if (delta < 0) {
6660 delta = -delta;
6661 }
6662 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6663 if ((tp->t_rttvar += delta) <= 0) {
6664 tp->t_rttvar = 1;
6665 }
6666 if (tp->t_rttbest == 0 ||
6667 tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6668 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6669 }
6670 } else {
6671 /*
6672 * No rtt measurement yet - use the unsmoothed rtt.
6673 * Set the variance to half the rtt (so our first
6674 * retransmit happens at 3*rtt).
6675 */
6676 tp->t_srtt = rtt << TCP_RTT_SHIFT;
6677 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
6678 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6679
6680 /* Initialize the receive SRTT */
6681 if (tp->rcv_srtt == 0) {
6682 tp->rcv_srtt = tp->t_srtt;
6683 }
6684 }
6685
6686 compute_rto:
6687 nstat_route_rtt(tp->t_inpcb->inp_route.ro_rt, tp->t_srtt,
6688 tp->t_rttvar);
6689
6690 /*
6691 * the retransmit should happen at rtt + 4 * rttvar.
6692 * Because of the way we do the smoothing, srtt and rttvar
6693 * will each average +1/2 tick of bias. When we compute
6694 * the retransmit timer, we want 1/2 tick of rounding and
6695 * 1 extra tick because of +-1/2 tick uncertainty in the
6696 * firing of the timer. The bias will give us exactly the
6697 * 1.5 tick we need. But, because the bias is
6698 * statistical, we have to test that we don't drop below
6699 * the minimum feasible timer (which is 2 ticks).
6700 */
6701 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6702 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX,
6703 TCP_ADD_REXMTSLOP(tp));
6704
6705 /*
6706 * We received an ack for a packet that wasn't retransmitted;
6707 * it is probably safe to discard any error indications we've
6708 * received recently. This isn't quite right, but close enough
6709 * for now (a route might have failed after we sent a segment,
6710 * and the return path might not be symmetrical).
6711 */
6712 tp->t_softerror = 0;
6713
6714 if (log_rtt) {
6715 TCP_LOG_RTT_INFO(tp);
6716 }
6717
6718 TCP_LOG_RTT_CHANGE(tp, old_srtt, old_rttvar);
6719 }
6720
6721 static inline unsigned int
tcp_maxmtu(struct rtentry * rt)6722 tcp_maxmtu(struct rtentry *rt)
6723 {
6724 unsigned int maxmtu;
6725 int interface_mtu = 0;
6726
6727 RT_LOCK_ASSERT_HELD(rt);
6728 interface_mtu = rt->rt_ifp->if_mtu;
6729
6730 if (rt_key(rt)->sa_family == AF_INET &&
6731 INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
6732 interface_mtu = IN6_LINKMTU(rt->rt_ifp);
6733 /* Further adjust the size for CLAT46 expansion */
6734 interface_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
6735 }
6736
6737 if (rt->rt_rmx.rmx_mtu == 0) {
6738 maxmtu = interface_mtu;
6739 } else {
6740 maxmtu = MIN(rt->rt_rmx.rmx_mtu, interface_mtu);
6741 }
6742
6743 return maxmtu;
6744 }
6745
6746 static inline unsigned int
tcp_maxmtu6(struct rtentry * rt)6747 tcp_maxmtu6(struct rtentry *rt)
6748 {
6749 unsigned int maxmtu;
6750 struct nd_ifinfo *ndi = NULL;
6751
6752 RT_LOCK_ASSERT_HELD(rt);
6753 if ((ndi = ND_IFINFO(rt->rt_ifp)) != NULL && !ndi->initialized) {
6754 ndi = NULL;
6755 }
6756 if (ndi != NULL) {
6757 lck_mtx_lock(&ndi->lock);
6758 }
6759 if (rt->rt_rmx.rmx_mtu == 0) {
6760 maxmtu = IN6_LINKMTU(rt->rt_ifp);
6761 } else {
6762 maxmtu = MIN(rt->rt_rmx.rmx_mtu, IN6_LINKMTU(rt->rt_ifp));
6763 }
6764 if (ndi != NULL) {
6765 lck_mtx_unlock(&ndi->lock);
6766 }
6767
6768 return maxmtu;
6769 }
6770
6771 unsigned int
get_maxmtu(struct rtentry * rt)6772 get_maxmtu(struct rtentry *rt)
6773 {
6774 unsigned int maxmtu = 0;
6775
6776 RT_LOCK_ASSERT_NOTHELD(rt);
6777
6778 RT_LOCK(rt);
6779
6780 if (rt_key(rt)->sa_family == AF_INET6) {
6781 maxmtu = tcp_maxmtu6(rt);
6782 } else {
6783 maxmtu = tcp_maxmtu(rt);
6784 }
6785
6786 RT_UNLOCK(rt);
6787
6788 return maxmtu;
6789 }
6790
6791 /*
6792 * Determine a reasonable value for maxseg size.
6793 * If the route is known, check route for mtu.
6794 * If none, use an mss that can be handled on the outgoing
6795 * interface without forcing IP to fragment; if bigger than
6796 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
6797 * to utilize large mbufs. If no route is found, route has no mtu,
6798 * or the destination isn't local, use a default, hopefully conservative
6799 * size (usually 512 or the default IP max size, but no more than the mtu
6800 * of the interface), as we can't discover anything about intervening
6801 * gateways or networks. We also initialize the congestion/slow start
6802 * window. While looking at the routing entry, we also initialize
6803 * other path-dependent parameters from pre-set or cached values
6804 * in the routing entry.
6805 *
6806 * Also take into account the space needed for options that we
6807 * send regularly. Make maxseg shorter by that amount to assure
6808 * that we can send maxseg amount of data even when the options
6809 * are present. Store the upper limit of the length of options plus
6810 * data in maxopd.
6811 *
6812 * NOTE that this routine is only called when we process an incoming
6813 * segment, for outgoing segments only tcp_mssopt is called.
6814 *
6815 */
6816 void
tcp_mss(struct tcpcb * tp,int offer,unsigned int input_ifscope)6817 tcp_mss(struct tcpcb *tp, int offer, unsigned int input_ifscope)
6818 {
6819 struct rtentry *rt;
6820 struct ifnet *ifp;
6821 int rtt, mss;
6822 uint32_t bufsize;
6823 struct inpcb *inp;
6824 struct socket *so;
6825 int origoffer = offer;
6826 int isnetlocal = 0;
6827 int isipv6;
6828 int min_protoh;
6829
6830 inp = tp->t_inpcb;
6831
6832 so = inp->inp_socket;
6833 /*
6834 * Nothing left to send after the socket is defunct or TCP is in the closed state
6835 */
6836 if ((so->so_state & SS_DEFUNCT) || tp->t_state == TCPS_CLOSED) {
6837 return;
6838 }
6839
6840 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
6841 min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
6842 : sizeof(struct tcpiphdr);
6843
6844 if (isipv6) {
6845 rt = tcp_rtlookup6(inp, input_ifscope);
6846 } else {
6847 rt = tcp_rtlookup(inp, input_ifscope);
6848 }
6849 isnetlocal = (tp->t_flags & TF_LOCAL);
6850
6851 if (rt == NULL) {
6852 tp->t_maxopd = tp->t_maxseg = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6853 return;
6854 }
6855 ifp = rt->rt_ifp;
6856 /*
6857 * Slower link window correction:
6858 * If a value is specificied for slowlink_wsize use it for
6859 * PPP links believed to be on a serial modem (speed <128Kbps).
6860 * Excludes 9600bps as it is the default value adversized
6861 * by pseudo-devices over ppp.
6862 */
6863 if (ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
6864 ifp->if_baudrate > 9600 && ifp->if_baudrate <= 128000) {
6865 tp->t_flags |= TF_SLOWLINK;
6866 }
6867
6868 /*
6869 * Offer == -1 means that we didn't receive SYN yet. Use 0 then.
6870 */
6871 if (offer == -1) {
6872 offer = rt->rt_rmx.rmx_filler[0];
6873 }
6874 /*
6875 * Offer == 0 means that there was no MSS on the SYN segment,
6876 * in this case we use tcp_mssdflt.
6877 */
6878 if (offer == 0) {
6879 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6880 } else {
6881 /*
6882 * Prevent DoS attack with too small MSS. Round up
6883 * to at least minmss.
6884 */
6885 offer = max(offer, tcp_minmss);
6886 /*
6887 * Sanity check: make sure that maxopd will be large
6888 * enough to allow some data on segments even is the
6889 * all the option space is used (40bytes). Otherwise
6890 * funny things may happen in tcp_output.
6891 */
6892 offer = max(offer, 64);
6893 }
6894 rt->rt_rmx.rmx_filler[0] = offer;
6895
6896 /*
6897 * While we're here, check if there's an initial rtt
6898 * or rttvar. Convert from the route-table units
6899 * to scaled multiples of the slow timeout timer.
6900 */
6901 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt) != 0) {
6902 tcp_getrt_rtt(tp, rt);
6903 } else {
6904 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCPTV_REXMTMIN;
6905 }
6906
6907 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
6908
6909 #if NECP
6910 // At this point, the mss is just the MTU. Adjust if necessary.
6911 mss = necp_socket_get_effective_mtu(inp, mss);
6912 #endif /* NECP */
6913
6914 mss -= min_protoh;
6915
6916 if (rt->rt_rmx.rmx_mtu == 0) {
6917 if (isipv6) {
6918 if (!isnetlocal) {
6919 mss = min(mss, tcp_v6mssdflt);
6920 }
6921 } else if (!isnetlocal) {
6922 mss = min(mss, tcp_mssdflt);
6923 }
6924 }
6925
6926 mss = min(mss, offer);
6927 /*
6928 * maxopd stores the maximum length of data AND options
6929 * in a segment; maxseg is the amount of data in a normal
6930 * segment. We need to store this value (maxopd) apart
6931 * from maxseg, because now every segment carries options
6932 * and thus we normally have somewhat less data in segments.
6933 */
6934 tp->t_maxopd = mss;
6935
6936 /*
6937 * origoffer==-1 indicates, that no segments were received yet.
6938 * In this case we just guess.
6939 */
6940 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
6941 (origoffer == -1 ||
6942 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)) {
6943 mss -= TCPOLEN_TSTAMP_APPA;
6944 }
6945
6946 #if MPTCP
6947 mss -= mptcp_adj_mss(tp, FALSE);
6948 #endif /* MPTCP */
6949 tp->t_maxseg = mss;
6950
6951 /*
6952 * If there's a pipesize (ie loopback), change the socket
6953 * buffer to that size only if it's bigger than the current
6954 * sockbuf size. Make the socket buffers an integral
6955 * number of mss units; if the mss is larger than
6956 * the socket buffer, decrease the mss.
6957 */
6958 #if RTV_SPIPE
6959 bufsize = rt->rt_rmx.rmx_sendpipe;
6960 if (bufsize < so->so_snd.sb_hiwat)
6961 #endif
6962 bufsize = so->so_snd.sb_hiwat;
6963 if (bufsize < mss) {
6964 mss = bufsize;
6965 } else {
6966 bufsize = (((bufsize + mss - 1) / mss) * mss);
6967 (void)sbreserve(&so->so_snd, bufsize);
6968 }
6969 tp->t_maxseg = mss;
6970
6971 ASSERT(tp->t_maxseg);
6972
6973 /*
6974 * Update MSS using recommendation from link status report. This is
6975 * temporary
6976 */
6977 tcp_update_mss_locked(so, ifp);
6978
6979 #if RTV_RPIPE
6980 bufsize = rt->rt_rmx.rmx_recvpipe;
6981 if (bufsize < so->so_rcv.sb_hiwat)
6982 #endif
6983 bufsize = so->so_rcv.sb_hiwat;
6984 if (bufsize > mss) {
6985 bufsize = (((bufsize + mss - 1) / mss) * mss);
6986 (void)sbreserve(&so->so_rcv, bufsize);
6987 }
6988
6989 set_tcp_stream_priority(so);
6990
6991 if (rt->rt_rmx.rmx_ssthresh) {
6992 /*
6993 * There's some sort of gateway or interface
6994 * buffer limit on the path. Use this to set
6995 * slow-start threshold, but set the threshold to
6996 * no less than 2*mss.
6997 */
6998 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
6999 tcpstat.tcps_usedssthresh++;
7000 } else {
7001 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
7002 }
7003
7004 /*
7005 * Set the slow-start flight size depending on whether this
7006 * is a local network or not.
7007 */
7008 if (CC_ALGO(tp)->cwnd_init != NULL) {
7009 CC_ALGO(tp)->cwnd_init(tp);
7010 }
7011
7012 tcp_ccdbg_trace(tp, NULL, TCP_CC_CWND_INIT);
7013
7014 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.rwnd_init != NULL) {
7015 tcp_cc_rledbat.rwnd_init(tp);
7016 }
7017
7018 /* Route locked during lookup above */
7019 RT_UNLOCK(rt);
7020 }
7021
7022 /*
7023 * Determine the MSS option to send on an outgoing SYN.
7024 */
7025 int
tcp_mssopt(struct tcpcb * tp)7026 tcp_mssopt(struct tcpcb *tp)
7027 {
7028 struct rtentry *rt;
7029 int mss;
7030 int isipv6;
7031 int min_protoh;
7032
7033 isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
7034 min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
7035 : sizeof(struct tcpiphdr);
7036
7037 if (isipv6) {
7038 rt = tcp_rtlookup6(tp->t_inpcb, IFSCOPE_NONE);
7039 } else {
7040 rt = tcp_rtlookup(tp->t_inpcb, IFSCOPE_NONE);
7041 }
7042 if (rt == NULL) {
7043 return isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
7044 }
7045 /*
7046 * Slower link window correction:
7047 * If a value is specificied for slowlink_wsize use it for PPP links
7048 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
7049 * it is the default value adversized by pseudo-devices over ppp.
7050 */
7051 if (rt->rt_ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
7052 rt->rt_ifp->if_baudrate > 9600 && rt->rt_ifp->if_baudrate <= 128000) {
7053 tp->t_flags |= TF_SLOWLINK;
7054 }
7055
7056 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
7057 /* Route locked during lookup above */
7058 RT_UNLOCK(rt);
7059
7060 #if NECP
7061 // At this point, the mss is just the MTU. Adjust if necessary.
7062 mss = necp_socket_get_effective_mtu(tp->t_inpcb, mss);
7063 #endif /* NECP */
7064
7065 return mss - min_protoh;
7066 }
7067
7068 /*
7069 * On a partial ack arrives, force the retransmission of the
7070 * next unacknowledged segment. Do not clear tp->t_dupacks.
7071 * By setting snd_nxt to th_ack, this forces retransmission timer to
7072 * be started again.
7073 */
7074 static void
tcp_newreno_partial_ack(struct tcpcb * tp,struct tcphdr * th)7075 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
7076 {
7077 tcp_seq onxt = tp->snd_nxt;
7078 u_int32_t ocwnd = tp->snd_cwnd;
7079 tp->t_timer[TCPT_REXMT] = 0;
7080 tp->t_timer[TCPT_PTO] = 0;
7081 tp->t_rtttime = 0;
7082 tp->snd_nxt = th->th_ack;
7083 /*
7084 * Set snd_cwnd to one segment beyond acknowledged offset
7085 * (tp->snd_una has not yet been updated when this function
7086 * is called)
7087 */
7088 tp->snd_cwnd = tp->t_maxseg + BYTES_ACKED(th, tp);
7089 (void) tcp_output(tp);
7090 tp->snd_cwnd = ocwnd;
7091 if (SEQ_GT(onxt, tp->snd_nxt)) {
7092 tp->snd_nxt = onxt;
7093 }
7094 /*
7095 * Partial window deflation. Relies on fact that tp->snd_una
7096 * not updated yet.
7097 */
7098 if (tp->snd_cwnd > BYTES_ACKED(th, tp)) {
7099 tp->snd_cwnd -= BYTES_ACKED(th, tp);
7100 } else {
7101 tp->snd_cwnd = 0;
7102 }
7103 tp->snd_cwnd += tp->t_maxseg;
7104 }
7105
7106 /*
7107 * Drop a random TCP connection that hasn't been serviced yet and
7108 * is eligible for discard. There is a one in qlen chance that
7109 * we will return a null, saying that there are no dropable
7110 * requests. In this case, the protocol specific code should drop
7111 * the new request. This insures fairness.
7112 *
7113 * The listening TCP socket "head" must be locked
7114 */
7115 static int
tcp_dropdropablreq(struct socket * head)7116 tcp_dropdropablreq(struct socket *head)
7117 {
7118 struct socket *so, *sonext;
7119 unsigned int j, qlen;
7120 static uint32_t rnd = 0;
7121 static uint64_t old_runtime;
7122 static unsigned int cur_cnt, old_cnt;
7123 uint64_t now_sec, i;
7124 struct inpcb *inp = NULL;
7125 struct tcpcb *tp;
7126
7127 if ((head->so_options & SO_ACCEPTCONN) == 0) {
7128 return 0;
7129 }
7130
7131 if (TAILQ_EMPTY(&head->so_incomp)) {
7132 return 0;
7133 }
7134
7135 so_acquire_accept_list(head, NULL);
7136 socket_unlock(head, 0);
7137
7138 /*
7139 * Check if there is any socket in the incomp queue
7140 * that is closed because of a reset from the peer and is
7141 * waiting to be garbage collected. If so, pick that as
7142 * the victim
7143 */
7144 TAILQ_FOREACH_SAFE(so, &head->so_incomp, so_list, sonext) {
7145 inp = sotoinpcb(so);
7146 tp = intotcpcb(inp);
7147 if (tp != NULL && tp->t_state == TCPS_CLOSED &&
7148 so->so_head != NULL &&
7149 (so->so_state & (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) ==
7150 (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) {
7151 /*
7152 * The listen socket is already locked but we
7153 * can lock this socket here without lock ordering
7154 * issues because it is in the incomp queue and
7155 * is not visible to others.
7156 */
7157 if (socket_try_lock(so)) {
7158 so->so_usecount++;
7159 goto found_victim;
7160 } else {
7161 continue;
7162 }
7163 }
7164 }
7165
7166 so = TAILQ_FIRST(&head->so_incomp);
7167
7168 now_sec = net_uptime();
7169 if ((i = (now_sec - old_runtime)) != 0) {
7170 old_runtime = now_sec;
7171 old_cnt = cur_cnt / i;
7172 cur_cnt = 0;
7173 }
7174
7175 qlen = head->so_incqlen;
7176 if (rnd == 0) {
7177 rnd = RandomULong();
7178 }
7179
7180 if (++cur_cnt > qlen || old_cnt > qlen) {
7181 rnd = (314159 * rnd + 66329) & 0xffff;
7182 j = ((qlen + 1) * rnd) >> 16;
7183
7184 while (j-- && so) {
7185 so = TAILQ_NEXT(so, so_list);
7186 }
7187 }
7188 /* Find a connection that is not already closing (or being served) */
7189 while (so) {
7190 inp = (struct inpcb *)so->so_pcb;
7191
7192 sonext = TAILQ_NEXT(so, so_list);
7193
7194 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
7195 /*
7196 * Avoid the issue of a socket being accepted
7197 * by one input thread and being dropped by
7198 * another input thread. If we can't get a hold
7199 * on this mutex, then grab the next socket in
7200 * line.
7201 */
7202 if (socket_try_lock(so)) {
7203 so->so_usecount++;
7204 if ((so->so_usecount == 2) &&
7205 (so->so_state & SS_INCOMP) &&
7206 !(so->so_flags & SOF_INCOMP_INPROGRESS)) {
7207 break;
7208 } else {
7209 /*
7210 * don't use if being accepted or
7211 * used in any other way
7212 */
7213 in_pcb_checkstate(inp, WNT_RELEASE, 1);
7214 socket_unlock(so, 1);
7215 }
7216 } else {
7217 /*
7218 * do not try to lock the inp in
7219 * in_pcb_checkstate because the lock
7220 * is already held in some other thread.
7221 * Only drop the inp_wntcnt reference.
7222 */
7223 in_pcb_checkstate(inp, WNT_RELEASE, 1);
7224 }
7225 }
7226 so = sonext;
7227 }
7228 if (so == NULL) {
7229 socket_lock(head, 0);
7230 so_release_accept_list(head);
7231 return 0;
7232 }
7233
7234 /* Makes sure socket is still in the right state to be discarded */
7235
7236 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
7237 socket_unlock(so, 1);
7238 socket_lock(head, 0);
7239 so_release_accept_list(head);
7240 return 0;
7241 }
7242
7243 found_victim:
7244 if (so->so_usecount != 2 || !(so->so_state & SS_INCOMP)) {
7245 /* do not discard: that socket is being accepted */
7246 socket_unlock(so, 1);
7247 socket_lock(head, 0);
7248 so_release_accept_list(head);
7249 return 0;
7250 }
7251
7252 socket_lock(head, 0);
7253 TAILQ_REMOVE(&head->so_incomp, so, so_list);
7254 head->so_incqlen--;
7255 head->so_qlen--;
7256 so->so_state &= ~SS_INCOMP;
7257 so->so_flags |= SOF_OVERFLOW;
7258 so->so_head = NULL;
7259 so_release_accept_list(head);
7260 socket_unlock(head, 0);
7261
7262 socket_lock_assert_owned(so);
7263 tp = sototcpcb(so);
7264
7265 tcp_close(tp);
7266 if (inp->inp_wantcnt > 0 && inp->inp_wantcnt != WNT_STOPUSING) {
7267 /*
7268 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
7269 * doesn't require a lock, it could have happened while
7270 * we are holding the lock. This pcb will have to
7271 * be garbage collected later.
7272 * Release the reference held for so_incomp queue
7273 */
7274 VERIFY(so->so_usecount > 0);
7275 so->so_usecount--;
7276 socket_unlock(so, 1);
7277 } else {
7278 /*
7279 * Unlock this socket and leave the reference on.
7280 * We need to acquire the pcbinfo lock in order to
7281 * fully dispose it off
7282 */
7283 socket_unlock(so, 0);
7284
7285 lck_rw_lock_exclusive(&tcbinfo.ipi_lock);
7286
7287 socket_lock(so, 0);
7288 /* Release the reference held for so_incomp queue */
7289 VERIFY(so->so_usecount > 0);
7290 so->so_usecount--;
7291
7292 if (so->so_usecount != 1 ||
7293 (inp->inp_wantcnt > 0 &&
7294 inp->inp_wantcnt != WNT_STOPUSING)) {
7295 /*
7296 * There is an extra wantcount or usecount
7297 * that must have been added when the socket
7298 * was unlocked. This socket will have to be
7299 * garbage collected later
7300 */
7301 socket_unlock(so, 1);
7302 } else {
7303 /* Drop the reference held for this function */
7304 VERIFY(so->so_usecount > 0);
7305 so->so_usecount--;
7306
7307 in_pcbdispose(inp);
7308 }
7309 lck_rw_done(&tcbinfo.ipi_lock);
7310 }
7311 tcpstat.tcps_drops++;
7312
7313 socket_lock(head, 0);
7314 return 1;
7315 }
7316
7317 /* Set background congestion control on a socket */
7318 void
tcp_set_background_cc(struct socket * so)7319 tcp_set_background_cc(struct socket *so)
7320 {
7321 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
7322 }
7323
7324 /* Set foreground congestion control on a socket */
7325 void
tcp_set_foreground_cc(struct socket * so)7326 tcp_set_foreground_cc(struct socket *so)
7327 {
7328 if (tcp_use_newreno) {
7329 tcp_set_new_cc(so, TCP_CC_ALGO_NEWRENO_INDEX);
7330 #if (DEVELOPMENT || DEBUG)
7331 } else if (tcp_use_ledbat) {
7332 /* Only used for testing */
7333 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
7334 #endif
7335 } else {
7336 struct inpcb *inp = sotoinpcb(so);
7337 struct tcpcb *tp = intotcpcb(inp);
7338 if (TCP_L4S_ENABLED(tp)) {
7339 tcp_set_new_cc(so, TCP_CC_ALGO_PRAGUE_INDEX);
7340 } else {
7341 tcp_set_new_cc(so, TCP_CC_ALGO_CUBIC_INDEX);
7342 }
7343 }
7344 }
7345
7346 static void
tcp_set_new_cc(struct socket * so,uint8_t cc_index)7347 tcp_set_new_cc(struct socket *so, uint8_t cc_index)
7348 {
7349 struct inpcb *inp = sotoinpcb(so);
7350 struct tcpcb *tp = intotcpcb(inp);
7351
7352 if (tp->tcp_cc_index != cc_index) {
7353 if (CC_ALGO(tp)->cleanup != NULL) {
7354 CC_ALGO(tp)->cleanup(tp);
7355 }
7356 tp->tcp_cc_index = cc_index;
7357
7358 tcp_cc_allocate_state(tp);
7359
7360 if (CC_ALGO(tp)->switch_to != NULL) {
7361 CC_ALGO(tp)->switch_to(tp);
7362 }
7363
7364 tcp_ccdbg_trace(tp, NULL, TCP_CC_CHANGE_ALGO);
7365 }
7366 }
7367
7368 void
tcp_set_recv_bg(struct socket * so)7369 tcp_set_recv_bg(struct socket *so)
7370 {
7371 if (!IS_TCP_RECV_BG(so)) {
7372 so->so_flags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
7373
7374 struct inpcb *inp = sotoinpcb(so);
7375 struct tcpcb *tp = intotcpcb(inp);
7376
7377 if (TCP_RLEDBAT_ENABLED(tp) && tcp_cc_rledbat.switch_to != NULL) {
7378 tcp_cc_rledbat.switch_to(tp);
7379 }
7380 }
7381 }
7382
7383 void
tcp_clear_recv_bg(struct socket * so)7384 tcp_clear_recv_bg(struct socket *so)
7385 {
7386 if (IS_TCP_RECV_BG(so)) {
7387 so->so_flags1 &= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG);
7388 }
7389 }
7390
7391 void
inp_fc_throttle_tcp(struct inpcb * inp)7392 inp_fc_throttle_tcp(struct inpcb *inp)
7393 {
7394 struct tcpcb *tp = inp->inp_ppcb;
7395
7396 if (!tcp_flow_control_response) {
7397 return;
7398 }
7399
7400 /*
7401 * Back off the slow-start threshold and enter
7402 * congestion avoidance phase
7403 */
7404 if (CC_ALGO(tp)->pre_fr != NULL) {
7405 CC_ALGO(tp)->pre_fr(tp);
7406 }
7407 }
7408
7409 void
inp_fc_unthrottle_tcp(struct inpcb * inp)7410 inp_fc_unthrottle_tcp(struct inpcb *inp)
7411 {
7412 struct tcpcb *tp = inp->inp_ppcb;
7413
7414 if (tcp_flow_control_response) {
7415 if (CC_ALGO(tp)->post_fr != NULL) {
7416 CC_ALGO(tp)->post_fr(tp, NULL);
7417 }
7418
7419 tp->t_bytes_acked = 0;
7420
7421 /*
7422 * Reset retransmit shift as we know that the reason
7423 * for delay in sending a packet is due to flow
7424 * control on the outgoing interface. There is no need
7425 * to backoff retransmit timer.
7426 */
7427 TCP_RESET_REXMT_STATE(tp);
7428
7429 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
7430
7431 /*
7432 * Start the output stream again. Since we are
7433 * not retransmitting data, do not reset the
7434 * retransmit timer or rtt calculation.
7435 */
7436 tcp_output(tp);
7437 return;
7438 }
7439
7440 /*
7441 * Back off the slow-start threshold and enter
7442 * congestion avoidance phase
7443 */
7444 if (CC_ALGO(tp)->pre_fr != NULL) {
7445 CC_ALGO(tp)->pre_fr(tp);
7446 }
7447
7448 tp->snd_cwnd = tp->snd_ssthresh;
7449 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
7450 /*
7451 * Restart counting for ABC as we changed the
7452 * congestion window just now.
7453 */
7454 tp->t_bytes_acked = 0;
7455
7456 /* Reset retransmit shift as we know that the reason
7457 * for delay in sending a packet is due to flow
7458 * control on the outgoing interface. There is no need
7459 * to backoff retransmit timer.
7460 */
7461 TCP_RESET_REXMT_STATE(tp);
7462
7463 /*
7464 * Start the output stream again. Since we are
7465 * not retransmitting data, do not reset the
7466 * retransmit timer or rtt calculation.
7467 */
7468 tcp_output(tp);
7469 }
7470
7471 static int
7472 tcp_getstat SYSCTL_HANDLER_ARGS
7473 {
7474 #pragma unused(oidp, arg1, arg2)
7475
7476 int error;
7477 struct tcpstat *stat;
7478 stat = &tcpstat;
7479
7480 #if XNU_TARGET_OS_OSX
7481 struct tcpstat zero_stat;
7482
7483 if (tcp_disable_access_to_stats &&
7484 !kauth_cred_issuser(kauth_cred_get())) {
7485 bzero(&zero_stat, sizeof(zero_stat));
7486 stat = &zero_stat;
7487 }
7488
7489 #endif /* XNU_TARGET_OS_OSX */
7490
7491 if (req->oldptr == 0) {
7492 req->oldlen = (size_t)sizeof(struct tcpstat);
7493 }
7494
7495 error = SYSCTL_OUT(req, stat, MIN(sizeof(tcpstat), req->oldlen));
7496
7497 return error;
7498 }
7499
7500 /*
7501 * Checksum extended TCP header and data.
7502 */
7503 int
tcp_input_checksum(int af,struct mbuf * m,struct tcphdr * th,int off,int tlen)7504 tcp_input_checksum(int af, struct mbuf *m, struct tcphdr *th, int off, int tlen)
7505 {
7506 struct ifnet *ifp = m->m_pkthdr.rcvif;
7507
7508 switch (af) {
7509 case AF_INET: {
7510 struct ip *ip = mtod(m, struct ip *);
7511 struct ipovly *ipov = (struct ipovly *)ip;
7512
7513 /* ip_stripoptions() must have been called before we get here */
7514 ASSERT((ip->ip_hl << 2) == sizeof(*ip));
7515
7516 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
7517 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
7518 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
7519 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7520 th->th_sum = m->m_pkthdr.csum_rx_val;
7521 } else {
7522 uint32_t sum = m->m_pkthdr.csum_rx_val;
7523 uint32_t start = m->m_pkthdr.csum_rx_start;
7524 int32_t trailer = (m_pktlen(m) - (off + tlen));
7525
7526 /*
7527 * Perform 1's complement adjustment of octets
7528 * that got included/excluded in the hardware-
7529 * calculated checksum value. Ignore cases
7530 * where the value already includes the entire
7531 * IP header span, as the sum for those octets
7532 * would already be 0 by the time we get here;
7533 * IP has already performed its header checksum
7534 * checks. If we do need to adjust, restore
7535 * the original fields in the IP header when
7536 * computing the adjustment value. Also take
7537 * care of any trailing bytes and subtract out
7538 * their partial sum.
7539 */
7540 ASSERT(trailer >= 0);
7541 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
7542 ((start != 0 && start != off) || trailer)) {
7543 uint32_t swbytes = (uint32_t)trailer;
7544
7545 if (start < off) {
7546 ip->ip_len += sizeof(*ip);
7547 #if BYTE_ORDER != BIG_ENDIAN
7548 HTONS(ip->ip_len);
7549 HTONS(ip->ip_off);
7550 #endif /* BYTE_ORDER != BIG_ENDIAN */
7551 }
7552 /* callee folds in sum */
7553 sum = m_adj_sum16(m, start, off,
7554 tlen, sum);
7555 if (off > start) {
7556 swbytes += (off - start);
7557 } else {
7558 swbytes += (start - off);
7559 }
7560
7561 if (start < off) {
7562 #if BYTE_ORDER != BIG_ENDIAN
7563 NTOHS(ip->ip_off);
7564 NTOHS(ip->ip_len);
7565 #endif /* BYTE_ORDER != BIG_ENDIAN */
7566 ip->ip_len -= sizeof(*ip);
7567 }
7568
7569 if (swbytes != 0) {
7570 tcp_in_cksum_stats(swbytes);
7571 }
7572 if (trailer != 0) {
7573 m_adj(m, -trailer);
7574 }
7575 }
7576
7577 /* callee folds in sum */
7578 th->th_sum = in_pseudo(ip->ip_src.s_addr,
7579 ip->ip_dst.s_addr,
7580 sum + htonl(tlen + IPPROTO_TCP));
7581 }
7582 th->th_sum ^= 0xffff;
7583 } else {
7584 uint16_t ip_sum;
7585 int len;
7586 char b[9];
7587
7588 bcopy(ipov->ih_x1, b, sizeof(ipov->ih_x1));
7589 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
7590 ip_sum = ipov->ih_len;
7591 ipov->ih_len = (u_short)tlen;
7592 #if BYTE_ORDER != BIG_ENDIAN
7593 HTONS(ipov->ih_len);
7594 #endif
7595 len = sizeof(struct ip) + tlen;
7596 th->th_sum = in_cksum(m, len);
7597 bcopy(b, ipov->ih_x1, sizeof(ipov->ih_x1));
7598 ipov->ih_len = ip_sum;
7599
7600 tcp_in_cksum_stats(len);
7601 }
7602 break;
7603 }
7604 case AF_INET6: {
7605 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
7606
7607 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
7608 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
7609 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
7610 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7611 th->th_sum = m->m_pkthdr.csum_rx_val;
7612 } else {
7613 uint32_t sum = m->m_pkthdr.csum_rx_val;
7614 uint32_t start = m->m_pkthdr.csum_rx_start;
7615 int32_t trailer = (m_pktlen(m) - (off + tlen));
7616
7617 /*
7618 * Perform 1's complement adjustment of octets
7619 * that got included/excluded in the hardware-
7620 * calculated checksum value. Also take care
7621 * of any trailing bytes and subtract out their
7622 * partial sum.
7623 */
7624 ASSERT(trailer >= 0);
7625 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
7626 (start != off || trailer != 0)) {
7627 uint16_t s = 0, d = 0;
7628 uint32_t swbytes = (uint32_t)trailer;
7629
7630 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7631 s = ip6->ip6_src.s6_addr16[1];
7632 ip6->ip6_src.s6_addr16[1] = 0;
7633 }
7634 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7635 d = ip6->ip6_dst.s6_addr16[1];
7636 ip6->ip6_dst.s6_addr16[1] = 0;
7637 }
7638
7639 /* callee folds in sum */
7640 sum = m_adj_sum16(m, start, off,
7641 tlen, sum);
7642 if (off > start) {
7643 swbytes += (off - start);
7644 } else {
7645 swbytes += (start - off);
7646 }
7647
7648 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7649 ip6->ip6_src.s6_addr16[1] = s;
7650 }
7651 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7652 ip6->ip6_dst.s6_addr16[1] = d;
7653 }
7654
7655 if (swbytes != 0) {
7656 tcp_in6_cksum_stats(swbytes);
7657 }
7658 if (trailer != 0) {
7659 m_adj(m, -trailer);
7660 }
7661 }
7662
7663 th->th_sum = in6_pseudo(
7664 &ip6->ip6_src, &ip6->ip6_dst,
7665 sum + htonl(tlen + IPPROTO_TCP));
7666 }
7667 th->th_sum ^= 0xffff;
7668 } else {
7669 tcp_in6_cksum_stats(tlen);
7670 th->th_sum = in6_cksum(m, IPPROTO_TCP, off, tlen);
7671 }
7672 break;
7673 }
7674 default:
7675 VERIFY(0);
7676 /* NOTREACHED */
7677 }
7678
7679 if (th->th_sum != 0) {
7680 tcpstat.tcps_rcvbadsum++;
7681 IF_TCP_STATINC(ifp, badformat);
7682 return -1;
7683 }
7684
7685 return 0;
7686 }
7687
7688 #define DUMP_BUF_CHK() { \
7689 clen -= k; \
7690 if (clen < 1) \
7691 goto done; \
7692 c += k; \
7693 }
7694
7695 int
dump_tcp_reass_qlen(char * str,int str_len)7696 dump_tcp_reass_qlen(char *str, int str_len)
7697 {
7698 char *c = str;
7699 int k, clen = str_len;
7700
7701 if (tcp_reass_total_qlen != 0) {
7702 k = scnprintf(c, clen, "\ntcp reass qlen %d\n", tcp_reass_total_qlen);
7703 DUMP_BUF_CHK();
7704 }
7705
7706 done:
7707 return str_len - clen;
7708 }
7709
7710 uint32_t
tcp_reass_qlen_space(struct socket * so)7711 tcp_reass_qlen_space(struct socket *so)
7712 {
7713 uint32_t space = 0;
7714 struct inpcb *inp = sotoinpcb(so);
7715
7716 if (inp != NULL) {
7717 struct tcpcb *tp = intotcpcb(inp);
7718
7719 if (tp != NULL) {
7720 space = tp->t_reassq_mbcnt;
7721 }
7722 }
7723 return space;
7724 }
7725
7726
7727 SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats,
7728 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, tcp_getstat,
7729 "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
7730
7731 static int
7732 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
7733 {
7734 #pragma unused(arg1, arg2)
7735
7736 int error, val = tcprexmtthresh;
7737
7738 error = sysctl_handle_int(oidp, &val, 0, req);
7739 if (error || !req->newptr) {
7740 return error;
7741 }
7742
7743 /*
7744 * Constrain the number of duplicate ACKs
7745 * to consider for TCP fast retransmit
7746 * to either 2 or 3
7747 */
7748
7749 if (val < 2 || val > 3) {
7750 return EINVAL;
7751 }
7752
7753 tcprexmtthresh = (uint8_t)val;
7754
7755 return 0;
7756 }
7757
7758 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, rexmt_thresh, CTLTYPE_INT | CTLFLAG_RW |
7759 CTLFLAG_LOCKED, &tcprexmtthresh, 0, &sysctl_rexmtthresh, "I",
7760 "Duplicate ACK Threshold for Fast Retransmit");
7761