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