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