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 unsigned int head_nocell, head_recvanyif,
2398 head_noexpensive, head_awdl_unrestricted,
2399 head_intcoproc_allowed, head_external_port,
2400 head_noconstrained;
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
2416 /*
2417 * If the state is LISTEN then ignore segment if it contains an RST.
2418 * If the segment contains an ACK then it is bad and send a RST.
2419 * If it does not contain a SYN then it is not interesting; drop it.
2420 * If it is from this socket, drop it, it must be forged.
2421 */
2422 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
2423 IF_TCP_STATINC(ifp, listbadsyn);
2424
2425 if (thflags & TH_RST) {
2426 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false,
2427 thflags & TH_SYN ? "ignore SYN with RST" : "ignore RST");
2428 goto drop;
2429 }
2430 if (thflags & TH_ACK) {
2431 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false,
2432 thflags & TH_SYN ? "bad SYN with ACK" : "bad ACK");
2433 tp = NULL;
2434 tcpstat.tcps_badsyn++;
2435 goto dropwithreset;
2436 }
2437
2438 /* We come here if there is no SYN set */
2439 tcpstat.tcps_badsyn++;
2440 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad SYN");
2441 goto drop;
2442 }
2443 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START, 0, 0, 0, 0, 0);
2444 if (th->th_dport == th->th_sport) {
2445 if (isipv6) {
2446 if (in6_are_addr_equal_scoped(&ip6->ip6_dst, &ip6->ip6_src, ip6_input_getdstifscope(m), ip6_input_getsrcifscope(m))) {
2447 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad tuple same port");
2448 goto drop;
2449 }
2450 } else if (ip->ip_dst.s_addr == ip->ip_src.s_addr) {
2451 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad tuple same IPv4 address");
2452 goto drop;
2453 }
2454 }
2455 /*
2456 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2457 * in_broadcast() should never return true on a received
2458 * packet with M_BCAST not set.
2459 *
2460 * Packets with a multicast source address should also
2461 * be discarded.
2462 */
2463 if (m->m_flags & (M_BCAST | M_MCAST)) {
2464 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "mbuf M_BCAST | M_MCAST");
2465 goto drop;
2466 }
2467 if (isipv6) {
2468 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2469 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
2470 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "IN6_IS_ADDR_MULTICAST");
2471 goto drop;
2472 }
2473 } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2474 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2475 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2476 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
2477 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "multicast or broadcast address");
2478 goto drop;
2479 }
2480
2481
2482 /*
2483 * If deprecated address is forbidden,
2484 * we do not accept SYN to deprecated interface
2485 * address to prevent any new inbound connection from
2486 * getting established.
2487 * When we do not accept SYN, we send a TCP RST,
2488 * with deprecated source address (instead of dropping
2489 * it). We compromise it as it is much better for peer
2490 * to send a RST, and RST will be the final packet
2491 * for the exchange.
2492 *
2493 * If we do not forbid deprecated addresses, we accept
2494 * the SYN packet. RFC 4862 forbids dropping SYN in
2495 * this case.
2496 */
2497 if (isipv6 && !ip6_use_deprecated) {
2498 uint32_t ia6_flags;
2499
2500 if (ip6_getdstifaddr_info(m, NULL,
2501 &ia6_flags) == 0) {
2502 if (ia6_flags & IN6_IFF_DEPRECATED) {
2503 tp = NULL;
2504 IF_TCP_STATINC(ifp, deprecate6);
2505 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "deprecated IPv6 address");
2506 goto dropwithreset;
2507 }
2508 }
2509 }
2510 if (so->so_filt || check_cfil) {
2511 if (isipv6) {
2512 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&from;
2513
2514 sin6->sin6_len = sizeof(*sin6);
2515 sin6->sin6_family = AF_INET6;
2516 sin6->sin6_port = th->th_sport;
2517 sin6->sin6_flowinfo = 0;
2518 sin6->sin6_addr = ip6->ip6_src;
2519 sin6->sin6_scope_id = 0;
2520
2521 sin6 = (struct sockaddr_in6*)&to2;
2522
2523 sin6->sin6_len = sizeof(struct sockaddr_in6);
2524 sin6->sin6_family = AF_INET6;
2525 sin6->sin6_port = th->th_dport;
2526 sin6->sin6_flowinfo = 0;
2527 sin6->sin6_addr = ip6->ip6_dst;
2528 sin6->sin6_scope_id = 0;
2529 } else {
2530 struct sockaddr_in *sin = (struct sockaddr_in*)&from;
2531
2532 sin->sin_len = sizeof(*sin);
2533 sin->sin_family = AF_INET;
2534 sin->sin_port = th->th_sport;
2535 sin->sin_addr = ip->ip_src;
2536
2537 sin = (struct sockaddr_in*)&to2;
2538
2539 sin->sin_len = sizeof(struct sockaddr_in);
2540 sin->sin_family = AF_INET;
2541 sin->sin_port = th->th_dport;
2542 sin->sin_addr = ip->ip_dst;
2543 }
2544 }
2545
2546 if (so->so_filt) {
2547 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
2548 } else {
2549 so2 = sonewconn(so, 0, NULL);
2550 }
2551 if (so2 == 0) {
2552 tcpstat.tcps_listendrop++;
2553 if (tcp_dropdropablreq(so)) {
2554 if (so->so_filt) {
2555 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
2556 } else {
2557 so2 = sonewconn(so, 0, NULL);
2558 }
2559 }
2560 if (!so2) {
2561 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " listen drop");
2562 goto drop;
2563 }
2564 }
2565
2566 /* Point "inp" and "tp" in tandem to new socket */
2567 inp = (struct inpcb *)so2->so_pcb;
2568 tp = intotcpcb(inp);
2569
2570 oso = so;
2571 socket_unlock(so, 0); /* Unlock but keep a reference on listener for now */
2572
2573 so = so2;
2574 socket_lock(so, 1);
2575 /*
2576 * Mark socket as temporary until we're
2577 * committed to keeping it. The code at
2578 * ``drop'' and ``dropwithreset'' check the
2579 * flag dropsocket to see if the temporary
2580 * socket created here should be discarded.
2581 * We mark the socket as discardable until
2582 * we're committed to it below in TCPS_LISTEN.
2583 * There are some error conditions in which we
2584 * have to drop the temporary socket.
2585 */
2586 dropsocket++;
2587 /*
2588 * Inherit INP_BOUND_IF from listener; testing if
2589 * head_ifscope is non-NULL is sufficient, since it
2590 * can only be set to a non-zero value earlier if
2591 * the listener has such a flag set.
2592 */
2593 if (head_ifscope != NULL) {
2594 inp->inp_flags |= INP_BOUND_IF;
2595 inp->inp_boundifp = head_ifscope;
2596 } else {
2597 inp->inp_flags &= ~INP_BOUND_IF;
2598 }
2599 /*
2600 * Inherit restrictions from listener.
2601 */
2602 if (head_nocell) {
2603 inp_set_nocellular(inp);
2604 }
2605 if (head_noexpensive) {
2606 inp_set_noexpensive(inp);
2607 }
2608 if (head_noconstrained) {
2609 inp_set_noconstrained(inp);
2610 }
2611 if (head_awdl_unrestricted) {
2612 inp_set_awdl_unrestricted(inp);
2613 }
2614 if (head_intcoproc_allowed) {
2615 inp_set_intcoproc_allowed(inp);
2616 }
2617 /*
2618 * Inherit {IN,IN6}_RECV_ANYIF from listener.
2619 */
2620 if (head_recvanyif) {
2621 inp->inp_flags |= INP_RECV_ANYIF;
2622 } else {
2623 inp->inp_flags &= ~INP_RECV_ANYIF;
2624 }
2625
2626 if (head_external_port) {
2627 inp->inp_flags2 |= INP2_EXTERNAL_PORT;
2628 }
2629 if (isipv6) {
2630 inp->in6p_laddr = ip6->ip6_dst;
2631 inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
2632 in6_verify_ifscope(&ip6->ip6_dst, inp->inp_lifscope);
2633 } else {
2634 inp->inp_vflag &= ~INP_IPV6;
2635 inp->inp_vflag |= INP_IPV4;
2636 inp->inp_laddr = ip->ip_dst;
2637 }
2638 inp->inp_lport = th->th_dport;
2639 if (in_pcbinshash(inp, 0) != 0) {
2640 /*
2641 * Undo the assignments above if we failed to
2642 * put the PCB on the hash lists.
2643 */
2644 if (isipv6) {
2645 inp->in6p_laddr = in6addr_any;
2646 inp->inp_lifscope = IFSCOPE_NONE;
2647 } else {
2648 inp->inp_laddr.s_addr = INADDR_ANY;
2649 }
2650 #if SKYWALK
2651 netns_release(&inp->inp_netns_token);
2652 #endif /* SKYWALK */
2653 inp->inp_lport = 0;
2654 socket_lock(oso, 0); /* release ref on parent */
2655 socket_unlock(oso, 1);
2656 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " in_pcbinshash failed");
2657 goto drop;
2658 }
2659 socket_lock(oso, 0);
2660 if (isipv6) {
2661 /*
2662 * Inherit socket options from the listening
2663 * socket.
2664 * Note that in6p_inputopts are not (even
2665 * should not be) copied, since it stores
2666 * previously received options and is used to
2667 * detect if each new option is different than
2668 * the previous one and hence should be passed
2669 * to a user.
2670 * If we copied in6p_inputopts, a user would
2671 * not be able to receive options just after
2672 * calling the accept system call.
2673 */
2674 inp->inp_flags |=
2675 oinp->inp_flags & INP_CONTROLOPTS;
2676 if (oinp->in6p_outputopts) {
2677 inp->in6p_outputopts =
2678 ip6_copypktopts(oinp->in6p_outputopts,
2679 Z_NOWAIT);
2680 }
2681 } else {
2682 inp->inp_options = ip_srcroute();
2683 inp->inp_ip_tos = oinp->inp_ip_tos;
2684 }
2685 #if IPSEC
2686 /* copy old policy into new socket's */
2687 if (sotoinpcb(oso)->inp_sp) {
2688 int error = 0;
2689 /* Is it a security hole here to silently fail to copy the policy? */
2690 if (inp->inp_sp == NULL) {
2691 error = ipsec_init_policy(so, &inp->inp_sp);
2692 }
2693 if (error != 0 || ipsec_copy_policy(sotoinpcb(oso)->inp_sp, inp->inp_sp)) {
2694 printf("tcp_input: could not copy policy\n");
2695 }
2696 }
2697 #endif
2698 /* inherit states from the listener */
2699 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
2700 struct tcpcb *, tp, int32_t, TCPS_LISTEN);
2701 TCP_LOG_STATE(tp, TCPS_LISTEN);
2702 tp->t_state = TCPS_LISTEN;
2703 tp->t_flags |= tp0->t_flags & (TF_NOPUSH | TF_NOOPT | TF_NODELAY);
2704 tp->t_flagsext |= (tp0->t_flagsext & (TF_RXTFINDROP | TF_NOTIMEWAIT | TF_FASTOPEN));
2705 tp->t_keepinit = tp0->t_keepinit;
2706 tp->t_keepcnt = tp0->t_keepcnt;
2707 tp->t_keepintvl = tp0->t_keepintvl;
2708 tp->t_adaptive_wtimo = tp0->t_adaptive_wtimo;
2709 tp->t_adaptive_rtimo = tp0->t_adaptive_rtimo;
2710 tp->t_inpcb->inp_ip_ttl = tp0->t_inpcb->inp_ip_ttl;
2711 if ((so->so_flags & SOF_NOTSENT_LOWAT) != 0) {
2712 tp->t_notsent_lowat = tp0->t_notsent_lowat;
2713 }
2714 tp->t_inpcb->inp_flags2 |=
2715 tp0->t_inpcb->inp_flags2 & INP2_KEEPALIVE_OFFLOAD;
2716
2717 /* now drop the reference on the listener */
2718 socket_unlock(oso, 1);
2719
2720 tcp_set_max_rwinscale(tp, so);
2721
2722 #if CONTENT_FILTER
2723 if (check_cfil) {
2724 int error = cfil_sock_attach(so2, (struct sockaddr*)&to2, (struct sockaddr*)&from,
2725 CFS_CONNECTION_DIR_IN);
2726 if (error != 0) {
2727 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " cfil_sock_attach failed");
2728 goto drop;
2729 }
2730 }
2731 #endif /* CONTENT_FILTER */
2732
2733 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END, 0, 0, 0, 0, 0);
2734 }
2735 }
2736 socket_lock_assert_owned(so);
2737
2738 /*
2739 * Packet accounting should not be done on listening socket
2740 */
2741 if (th->th_flags & TH_SYN) {
2742 (void) os_add_overflow(1, tp->t_syn_rcvd, &tp->t_syn_rcvd);
2743 }
2744 if (th->th_flags & TH_FIN) {
2745 (void) os_add_overflow(1, tp->t_fin_rcvd, &tp->t_fin_rcvd);
2746 }
2747 if (th->th_flags & TH_RST) {
2748 (void) os_add_overflow(1, tp->t_rst_rcvd, &tp->t_rst_rcvd);
2749 }
2750 TCP_LOG_TH_FLAGS(TCP_LOG_HDR, th, tp, false, ifp);
2751
2752 if (net_mpklog_enabled && (m->m_pkthdr.rcvif->if_xflags & IFXF_MPK_LOG)) {
2753 MPKL_TCP_INPUT(tcp_mpkl_log_object,
2754 ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
2755 th->th_seq, th->th_ack, tlen, thflags,
2756 so->last_pid, so->so_log_seqn++);
2757 }
2758
2759 if (tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
2760 /*
2761 * Evaluate the rate of arrival of packets to see if the
2762 * receiver can reduce the ack traffic. The algorithm to
2763 * stretch acks will be enabled if the connection meets
2764 * certain criteria defined in tcp_stretch_ack_enable function.
2765 */
2766 if ((tp->t_flagsext & TF_RCVUNACK_WAITSS) != 0) {
2767 TCP_INC_VAR(tp->rcv_waitforss, segment_count);
2768 }
2769 if (tcp_stretch_ack_enable(tp, thflags)) {
2770 tp->t_flags |= TF_STRETCHACK;
2771 tp->t_flagsext &= ~(TF_RCVUNACK_WAITSS);
2772 tp->rcv_waitforss = 0;
2773 } else {
2774 tp->t_flags &= ~(TF_STRETCHACK);
2775 }
2776 if (TSTMP_GT(tp->rcv_unackwin - (tcp_rcvunackwin >> 1), tcp_now)) {
2777 tp->rcv_by_unackhalfwin += (tlen + off);
2778 tp->rcv_by_unackwin += (tlen + off);
2779 } else {
2780 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
2781 tp->rcv_by_unackwin = tp->rcv_by_unackhalfwin + tlen + off;
2782 tp->rcv_by_unackhalfwin = tlen + off;
2783 }
2784 }
2785
2786 /* Accurate ECN has different semantics for TH_CWR. */
2787 if (!TCP_ACC_ECN_ENABLED()) {
2788 /*
2789 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2790 * bother doing extensive checks for state and whatnot.
2791 */
2792 if (thflags & TH_CWR) {
2793 tp->ecn_flags &= ~TE_SENDECE;
2794 tp->t_ecn_recv_cwr++;
2795 }
2796 }
2797
2798 /*
2799 * Accurate ECN feedback
2800 * 1. Process peer's feedback in received TCP thflags and update s.cep
2801 * 2. Process IP ECN bits and update r.cep for CE marked pure ACKs
2802 * or valid data packets
2803 *
2804 */
2805 if (TCP_ACC_ECN_ON(tp) && tp->t_state == TCPS_ESTABLISHED) {
2806 /*
2807 * Update s.cep if bytes have been acknowledged
2808 * otherwise, this ACK has already been superseded.
2809 */
2810 if (BYTES_ACKED(th, tp) > 0) {
2811 uint8_t ace = tcp_get_ace(th);
2812 /* Congestion was experienced if delta_cep > 0 */
2813 tp->t_delta_ce_packets = (ace + TCP_ACE_DIV - (tp->t_snd_ce_packets % TCP_ACE_DIV)) % TCP_ACE_DIV;
2814 tp->t_snd_ce_packets += tp->t_delta_ce_packets;
2815 }
2816 /* Update receive side counters */
2817 if (tlen == 0 || (tlen > 0 &&
2818 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2819 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd))) {
2820 tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
2821 }
2822 } else {
2823 /*
2824 * Explicit Congestion Notification - Flag that we need to send ECE if
2825 * + The IP Congestion experienced flag was set.
2826 * + Socket is in established state
2827 * + We negotiated ECN in the TCP setup
2828 * + This isn't a pure ack (tlen > 0)
2829 * + The data is in the valid window
2830 *
2831 * TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2832 */
2833 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2834 TCP_ECN_ENABLED(tp) && tlen > 0 &&
2835 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2836 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2837 tp->t_ecn_recv_ce++;
2838 tcpstat.tcps_ecn_recv_ce++;
2839 INP_INC_IFNET_STAT(inp, ecn_recv_ce);
2840 /* Mark this connection as it received CE from network */
2841 tp->ecn_flags |= TE_RECV_ECN_CE;
2842 tp->ecn_flags |= TE_SENDECE;
2843 }
2844 }
2845
2846 /*
2847 * If we received an explicit notification of congestion in
2848 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
2849 * the ack-stretching state. We need to handle ECN notification if
2850 * an ECN setup SYN was sent even once.
2851 */
2852 if (tp->t_state == TCPS_ESTABLISHED &&
2853 (tp->ecn_flags & TE_SETUPSENT) &&
2854 (ip_ecn == IPTOS_ECN_CE || (thflags & TH_CWR))) {
2855 tcp_reset_stretch_ack(tp);
2856 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
2857 CLEAR_IAJ_STATE(tp);
2858 }
2859
2860 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2861 !TCP_ECN_ENABLED(tp) && !(tp->ecn_flags & TE_CEHEURI_SET)) {
2862 tcpstat.tcps_ecn_fallback_ce++;
2863 tcp_heuristic_ecn_aggressive(tp);
2864 tp->ecn_flags |= TE_CEHEURI_SET;
2865 }
2866
2867 if (tp->t_state == TCPS_ESTABLISHED && TCP_ECN_ENABLED(tp) &&
2868 ip_ecn == IPTOS_ECN_CE && !(tp->ecn_flags & TE_CEHEURI_SET)) {
2869 if (inp->inp_stat->rxpackets < ECN_MIN_CE_PROBES) {
2870 tp->t_ecn_recv_ce_pkt++;
2871 } else if (tp->t_ecn_recv_ce_pkt > ECN_MAX_CE_RATIO) {
2872 tcpstat.tcps_ecn_fallback_ce++;
2873 tcp_heuristic_ecn_aggressive(tp);
2874 tp->ecn_flags |= TE_CEHEURI_SET;
2875 INP_INC_IFNET_STAT(inp, ecn_fallback_ce);
2876 } else {
2877 /* We tracked the first ECN_MIN_CE_PROBES segments, we
2878 * now know that the path is good.
2879 */
2880 tp->ecn_flags |= TE_CEHEURI_SET;
2881 }
2882 }
2883
2884 /* Update rcvtime as a new segment was received on the connection */
2885 tp->t_rcvtime = tcp_now;
2886
2887 /*
2888 * Segment received on connection.
2889 * Reset idle time and keep-alive timer.
2890 */
2891 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2892 tcp_keepalive_reset(tp);
2893
2894 if (tp->t_mpsub) {
2895 mptcp_reset_keepalive(tp);
2896 }
2897 }
2898
2899 /*
2900 * Process options if not in LISTEN state,
2901 * else do it below (after getting remote address).
2902 */
2903 if (tp->t_state != TCPS_LISTEN && optp) {
2904 tcp_dooptions(tp, optp, optlen, th, &to);
2905 }
2906 #if MPTCP
2907 if (tp->t_state != TCPS_LISTEN && (so->so_flags & SOF_MP_SUBFLOW)) {
2908 mptcp_insert_rmap(tp, m, th);
2909 }
2910 #endif /* MPTCP */
2911 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
2912 if (!(thflags & TH_ACK) ||
2913 (SEQ_GT(th->th_ack, tp->iss) &&
2914 SEQ_LEQ(th->th_ack, tp->snd_max))) {
2915 tcp_finalize_options(tp, &to, ifscope);
2916 }
2917 }
2918
2919 #if TRAFFIC_MGT
2920 /*
2921 * Compute inter-packet arrival jitter. According to RFC 3550,
2922 * inter-packet arrival jitter is defined as the difference in
2923 * packet spacing at the receiver compared to the sender for a
2924 * pair of packets. When two packets of maximum segment size come
2925 * one after the other with consecutive sequence numbers, we
2926 * consider them as packets sent together at the sender and use
2927 * them as a pair to compute inter-packet arrival jitter. This
2928 * metric indicates the delay induced by the network components due
2929 * to queuing in edge/access routers.
2930 */
2931 if (tp->t_state == TCPS_ESTABLISHED &&
2932 (thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK | TH_ECE | TH_PUSH)) == TH_ACK &&
2933 ((tp->t_flags & TF_NEEDFIN) == 0) &&
2934 ((to.to_flags & TOF_TS) == 0 ||
2935 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
2936 th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
2937 int seg_size = tlen;
2938 if (tp->iaj_pktcnt <= IAJ_IGNORE_PKTCNT) {
2939 TCP_INC_VAR(tp->iaj_pktcnt, segment_count);
2940 }
2941
2942 if (tp->iaj_size == 0 || seg_size > tp->iaj_size ||
2943 (seg_size == tp->iaj_size && tp->iaj_rcv_ts == 0)) {
2944 /*
2945 * State related to inter-arrival jitter is
2946 * uninitialized or we are trying to find a good
2947 * first packet to start computing the metric
2948 */
2949 update_iaj_state(tp, seg_size, 0);
2950 } else {
2951 if (seg_size == tp->iaj_size) {
2952 /*
2953 * Compute inter-arrival jitter taking
2954 * this packet as the second packet
2955 */
2956 compute_iaj(tp);
2957 }
2958 if (seg_size < tp->iaj_size) {
2959 /*
2960 * There is a smaller packet in the stream.
2961 * Some times the maximum size supported
2962 * on a path can change if there is a new
2963 * link with smaller MTU. The receiver will
2964 * not know about this change. If there
2965 * are too many packets smaller than
2966 * iaj_size, we try to learn the iaj_size
2967 * again.
2968 */
2969 TCP_INC_VAR(tp->iaj_small_pkt, segment_count);
2970 if (tp->iaj_small_pkt > RESET_IAJ_SIZE_THRESH) {
2971 update_iaj_state(tp, seg_size, 1);
2972 } else {
2973 CLEAR_IAJ_STATE(tp);
2974 }
2975 } else {
2976 update_iaj_state(tp, seg_size, 0);
2977 }
2978 }
2979 } else {
2980 CLEAR_IAJ_STATE(tp);
2981 }
2982 #endif /* TRAFFIC_MGT */
2983
2984 /*
2985 * Header prediction: check for the two common cases
2986 * of a uni-directional data xfer. If the packet has
2987 * no control flags, is in-sequence, the window didn't
2988 * change and we're not retransmitting, it's a
2989 * candidate. If the length is zero and the ack moved
2990 * forward, we're the sender side of the xfer. Just
2991 * free the data acked & wake any higher level process
2992 * that was blocked waiting for space. If the length
2993 * is non-zero and the ack didn't move, we're the
2994 * receiver side. If we're getting packets in-order
2995 * (the reassembly queue is empty), add the data to
2996 * the socket buffer and note that we need a delayed ack.
2997 * Make sure that the hidden state-flags are also off.
2998 * Since we check for TCPS_ESTABLISHED above, it can only
2999 * be TH_NEEDSYN.
3000 */
3001 if (tp->t_state == TCPS_ESTABLISHED &&
3002 !(so->so_state & SS_CANTRCVMORE) &&
3003 (thflags & TH_FLAGS) == TH_ACK &&
3004 ((tp->t_flags & TF_NEEDFIN) == 0) &&
3005 ((to.to_flags & TOF_TS) == 0 ||
3006 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
3007 th->th_seq == tp->rcv_nxt &&
3008 tiwin && tiwin == tp->snd_wnd &&
3009 tp->snd_nxt == tp->snd_max) {
3010 /*
3011 * If last ACK falls within this segment's sequence numbers,
3012 * record the timestamp.
3013 * NOTE that the test is modified according to the latest
3014 * proposal of the [email protected] list (Braden 1993/04/26).
3015 */
3016 if ((to.to_flags & TOF_TS) != 0 &&
3017 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
3018 tp->ts_recent_age = tcp_now;
3019 tp->ts_recent = to.to_tsval;
3020 }
3021
3022 if (tlen == 0) {
3023 if (SEQ_GT(th->th_ack, tp->snd_una) &&
3024 SEQ_LEQ(th->th_ack, tp->snd_max) &&
3025 tp->snd_cwnd >= tp->snd_ssthresh &&
3026 (!IN_FASTRECOVERY(tp) &&
3027 ((!(SACK_ENABLED(tp)) &&
3028 tp->t_dupacks < tp->t_rexmtthresh) ||
3029 (SACK_ENABLED(tp) && to.to_nsacks == 0 &&
3030 TAILQ_EMPTY(&tp->snd_holes))))) {
3031 /*
3032 * this is a pure ack for outstanding data.
3033 */
3034 ++tcpstat.tcps_predack;
3035
3036 tcp_bad_rexmt_check(tp, th, &to);
3037
3038 /* Recalculate the RTT */
3039 tcp_compute_rtt(tp, &to, th);
3040
3041 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
3042 acked = BYTES_ACKED(th, tp);
3043 tcpstat.tcps_rcvackpack++;
3044 tcpstat.tcps_rcvackbyte += acked;
3045
3046 /*
3047 * Handle an ack that is in sequence during
3048 * congestion avoidance phase. The
3049 * calculations in this function
3050 * assume that snd_una is not updated yet.
3051 */
3052 if (CC_ALGO(tp)->congestion_avd != NULL) {
3053 CC_ALGO(tp)->congestion_avd(tp, th);
3054 }
3055 tcp_ccdbg_trace(tp, th, TCP_CC_INSEQ_ACK_RCVD);
3056 sbdrop(&so->so_snd, acked);
3057 tcp_sbsnd_trim(&so->so_snd);
3058
3059 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
3060 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
3061 tp->snd_recover = th->th_ack - 1;
3062 }
3063
3064 tcp_update_snd_una(tp, th->th_ack);
3065
3066 TCP_RESET_REXMT_STATE(tp);
3067
3068 /*
3069 * pull snd_wl2 up to prevent seq wrap relative
3070 * to th_ack.
3071 */
3072 tp->snd_wl2 = th->th_ack;
3073
3074 if (tp->t_dupacks > 0) {
3075 tp->t_dupacks = 0;
3076 tp->t_rexmtthresh = tcprexmtthresh;
3077 tp->t_new_dupacks = 0;
3078 }
3079
3080 tp->sackhint.sack_bytes_acked = 0;
3081
3082 /*
3083 * If all outstanding data are acked, stop
3084 * retransmit timer, otherwise restart timer
3085 * using current (possibly backed-off) value.
3086 * If process is waiting for space,
3087 * wakeup/selwakeup/signal. If data
3088 * are ready to send, let tcp_output
3089 * decide between more output or persist.
3090 */
3091 if (tp->snd_una == tp->snd_max) {
3092 tp->t_timer[TCPT_REXMT] = 0;
3093 tp->t_timer[TCPT_PTO] = 0;
3094 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
3095 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
3096 }
3097 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
3098 !TCP_DSACK_SEQ_IN_WINDOW(tp,
3099 tp->t_dsack_lastuna, tp->snd_una)) {
3100 tcp_rxtseg_clean(tp);
3101 }
3102
3103 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
3104 tp->t_bwmeas != NULL) {
3105 tcp_bwmeas_check(tp);
3106 }
3107
3108 write_wakeup = 1;
3109 if (!SLIST_EMPTY(&tp->t_notify_ack)) {
3110 tcp_notify_acknowledgement(tp, so);
3111 }
3112
3113 if ((so->so_snd.sb_cc) || (tp->t_flags & TF_ACKNOW)) {
3114 (void) tcp_output(tp);
3115 }
3116
3117 tcp_tfo_rcv_ack(tp, th);
3118
3119 m_freem(m);
3120
3121 tcp_check_timer_state(tp);
3122
3123 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3124
3125 socket_unlock(so, 1);
3126 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3127 return;
3128 }
3129 } else if (th->th_ack == tp->snd_una && LIST_EMPTY(&tp->t_segq) &&
3130 tlen <= tcp_sbspace(tp)) {
3131 /*
3132 * this is a pure, in-sequence data packet
3133 * with nothing on the reassembly queue and
3134 * we have enough buffer space to take it.
3135 */
3136
3137 /* Clean receiver SACK report if present */
3138 if (SACK_ENABLED(tp) && tp->rcv_numsacks) {
3139 tcp_clean_sackreport(tp);
3140 }
3141 ++tcpstat.tcps_preddat;
3142 tp->rcv_nxt += tlen;
3143 /* Update highest received sequence and its timestamp */
3144 if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
3145 tp->rcv_high = tp->rcv_nxt;
3146 if (to.to_flags & TOF_TS) {
3147 tp->tsv_high = to.to_tsval;
3148 }
3149 }
3150
3151 /*
3152 * Pull snd_wl1 up to prevent seq wrap relative to
3153 * th_seq.
3154 */
3155 tp->snd_wl1 = th->th_seq;
3156 /*
3157 * Pull rcv_up up to prevent seq wrap relative to
3158 * rcv_nxt.
3159 */
3160 tp->rcv_up = tp->rcv_nxt;
3161 TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
3162 tcpstat.tcps_rcvbyte += tlen;
3163 if (nstat_collect) {
3164 INP_ADD_STAT(inp, cell, wifi, wired,
3165 rxpackets, 1);
3166 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes,
3167 tlen);
3168 inp_set_activity_bitmap(inp);
3169 }
3170
3171 /* Calculate the RTT on the receiver */
3172 tcp_compute_rcv_rtt(tp, &to, th);
3173
3174 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
3175 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.data_rcvd != NULL) {
3176 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
3177 }
3178
3179 /*
3180 * Add data to socket buffer.
3181 */
3182 so_recv_data_stat(so, m, 0);
3183 m_adj(m, drop_hdrlen); /* delayed header drop */
3184
3185 if (isipv6) {
3186 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
3187 ip6 = (struct ip6_hdr *)&saved_hdr[0];
3188 } else {
3189 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
3190 ip = (struct ip *)&saved_hdr[0];
3191 }
3192 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
3193
3194 if (th->th_flags & TH_PUSH) {
3195 tp->t_flagsext |= TF_LAST_IS_PSH;
3196 } else {
3197 tp->t_flagsext &= ~TF_LAST_IS_PSH;
3198 }
3199
3200 if (sbappendstream_rcvdemux(so, m)) {
3201 mptcp_handle_input(so);
3202 read_wakeup = 1;
3203 }
3204 th = &saved_tcphdr;
3205
3206 if (isipv6) {
3207 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3208 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
3209 th->th_seq, th->th_ack, th->th_win);
3210 } else {
3211 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3212 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
3213 th->th_seq, th->th_ack, th->th_win);
3214 }
3215 TCP_INC_VAR(tp->t_unacksegs, segment_count);
3216 if (DELAY_ACK(tp, th)) {
3217 if ((tp->t_flags & TF_DELACK) == 0) {
3218 tp->t_flags |= TF_DELACK;
3219 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3220 }
3221 } else {
3222 tp->t_flags |= TF_ACKNOW;
3223 tcp_output(tp);
3224 }
3225
3226 tcp_adaptive_rwtimo_check(tp, tlen);
3227
3228 if (tlen > 0) {
3229 tcp_tfo_rcv_data(tp);
3230 }
3231
3232 tcp_check_timer_state(tp);
3233
3234 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3235
3236 socket_unlock(so, 1);
3237 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3238 return;
3239 }
3240 }
3241
3242 /*
3243 * Calculate amount of space in receive window,
3244 * and then do TCP input processing.
3245 * Receive window is amount of space in rcv queue,
3246 * but not less than advertised window.
3247 */
3248 socket_lock_assert_owned(so);
3249 win = tcp_sbspace(tp);
3250 if (win < 0) {
3251 win = 0;
3252 } else { /* clip rcv window to 4K for modems */
3253 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
3254 win = min(win, slowlink_wsize);
3255 }
3256 }
3257 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
3258 #if MPTCP
3259 /*
3260 * Ensure that the subflow receive window isn't greater
3261 * than the connection level receive window.
3262 */
3263 if ((tp->t_mpflags & TMPF_MPTCP_TRUE) && (mp_tp = tptomptp(tp))) {
3264 socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
3265 int64_t recwin_conn = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
3266
3267 VERIFY(recwin_conn < INT32_MAX && recwin_conn > INT32_MIN);
3268 if (recwin_conn > 0 && tp->rcv_wnd > (uint32_t)recwin_conn) {
3269 tp->rcv_wnd = (uint32_t)recwin_conn;
3270 tcpstat.tcps_mp_reducedwin++;
3271 }
3272 }
3273 #endif /* MPTCP */
3274
3275 switch (tp->t_state) {
3276 /*
3277 * Initialize tp->rcv_nxt, and tp->irs, select an initial
3278 * tp->iss, and send a segment:
3279 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3280 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3281 * Fill in remote peer address fields if not previously specified.
3282 * Enter SYN_RECEIVED state, and process any other fields of this
3283 * segment in this state.
3284 */
3285 case TCPS_LISTEN: {
3286 struct sockaddr_in *sin;
3287 struct sockaddr_in6 *sin6;
3288
3289 socket_lock_assert_owned(so);
3290
3291 /* Clear the logging flags inherited from the listening socket */
3292 tp->t_log_flags = 0;
3293 tp->t_flagsext &= ~TF_LOGGED_CONN_SUMMARY;
3294
3295 if (isipv6) {
3296 sin6 = kalloc_type(struct sockaddr_in6, Z_NOWAIT | Z_ZERO);
3297 if (sin6 == NULL) {
3298 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3299 goto drop;
3300 }
3301 sin6->sin6_family = AF_INET6;
3302 sin6->sin6_len = sizeof(*sin6);
3303 sin6->sin6_addr = ip6->ip6_src;
3304 sin6->sin6_port = th->th_sport;
3305 if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3306 sin6->sin6_scope_id = ip6_input_getsrcifscope(m);
3307 }
3308 laddr6 = inp->in6p_laddr;
3309 uint32_t lifscope = inp->inp_lifscope;
3310 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
3311 inp->in6p_laddr = ip6->ip6_dst;
3312 inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
3313 in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3314 }
3315 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
3316 kernel_proc)) {
3317 inp->in6p_laddr = laddr6;
3318 kfree_type(struct sockaddr_in6, sin6);
3319 inp->inp_lifscope = lifscope;
3320 in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3321 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in6_pcbconnect failed");
3322 goto drop;
3323 }
3324 kfree_type(struct sockaddr_in6, sin6);
3325 } else {
3326 socket_lock_assert_owned(so);
3327 sin = kalloc_type(struct sockaddr_in, Z_NOWAIT);
3328 if (sin == NULL) {
3329 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3330 goto drop;
3331 }
3332 sin->sin_family = AF_INET;
3333 sin->sin_len = sizeof(*sin);
3334 sin->sin_addr = ip->ip_src;
3335 sin->sin_port = th->th_sport;
3336 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
3337 laddr = inp->inp_laddr;
3338 if (inp->inp_laddr.s_addr == INADDR_ANY) {
3339 inp->inp_laddr = ip->ip_dst;
3340 }
3341 if (in_pcbconnect(inp, (struct sockaddr *)sin, kernel_proc,
3342 IFSCOPE_NONE, NULL)) {
3343 inp->inp_laddr = laddr;
3344 kfree_type(struct sockaddr_in, sin);
3345 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in_pcbconnect failed");
3346 goto drop;
3347 }
3348 kfree_type(struct sockaddr_in, sin);
3349 }
3350
3351 tcp_dooptions(tp, optp, optlen, th, &to);
3352 tcp_finalize_options(tp, &to, ifscope);
3353
3354 if (tfo_enabled(tp) && tcp_tfo_syn(tp, &to)) {
3355 isconnected = TRUE;
3356 }
3357
3358 if (iss) {
3359 tp->iss = iss;
3360 } else {
3361 tp->iss = tcp_new_isn(tp);
3362 }
3363 tp->irs = th->th_seq;
3364 tcp_sendseqinit(tp);
3365 tcp_rcvseqinit(tp);
3366 tp->snd_recover = tp->snd_una;
3367 /*
3368 * Initialization of the tcpcb for transaction;
3369 * set SND.WND = SEG.WND,
3370 * initialize CCsend and CCrecv.
3371 */
3372 tp->snd_wnd = tiwin; /* initial send-window */
3373 tp->max_sndwnd = tp->snd_wnd;
3374 tp->t_flags |= TF_ACKNOW;
3375 tp->t_unacksegs = 0;
3376 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3377 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
3378 TCP_LOG_STATE(tp, TCPS_SYN_RECEIVED);
3379 tp->t_state = TCPS_SYN_RECEIVED;
3380 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
3381 TCP_CONN_KEEPINIT(tp));
3382 tp->t_connect_time = tcp_now;
3383 dropsocket = 0; /* committed to socket */
3384
3385 if (inp->inp_flowhash == 0) {
3386 inp_calc_flowhash(inp);
3387 ASSERT(inp->inp_flowhash != 0);
3388 }
3389 /* update flowinfo - RFC 6437 */
3390 if (inp->inp_flow == 0 &&
3391 inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
3392 inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
3393 inp->inp_flow |=
3394 (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
3395 }
3396
3397 /* reset the incomp processing flag */
3398 so->so_flags &= ~(SOF_INCOMP_INPROGRESS);
3399 tcpstat.tcps_accepts++;
3400
3401 int ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3402 switch (ace_flags) {
3403 case (0 | 0 | 0):
3404 /* No ECN */
3405 break;
3406 case (0 | TH_CWR | TH_ECE):
3407 /* Legacy ECN-setup */
3408 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
3409 break;
3410 case (TH_ACE):
3411 /* Accurate ECN */
3412 if (TCP_ACC_ECN_ENABLED()) {
3413 switch (ip_ecn) {
3414 case IPTOS_ECN_NOTECT:
3415 tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
3416 break;
3417 case IPTOS_ECN_ECT1:
3418 tp->ecn_flags |= TE_ACE_SETUP_ECT1;
3419 break;
3420 case IPTOS_ECN_ECT0:
3421 tp->ecn_flags |= TE_ACE_SETUP_ECT0;
3422 break;
3423 case IPTOS_ECN_CE:
3424 tp->ecn_flags |= TE_ACE_SETUP_CE;
3425 break;
3426 }
3427 /*
3428 * We are not yet committing to send IP ECT packets when
3429 * Accurate ECN is enabled
3430 */
3431 tp->ecn_flags |= (TE_ACE_SETUPRECEIVED);
3432 } else {
3433 /*
3434 * If AccECN is not enabled, ignore
3435 * the TH_AE bit and do Legacy ECN-setup
3436 */
3437 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
3438 }
3439 default:
3440 /* Forward Compatibility */
3441 /* Accurate ECN */
3442 if (TCP_ACC_ECN_ENABLED()) {
3443 switch (ip_ecn) {
3444 case IPTOS_ECN_NOTECT:
3445 tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
3446 break;
3447 case IPTOS_ECN_ECT1:
3448 tp->ecn_flags |= TE_ACE_SETUP_ECT1;
3449 break;
3450 case IPTOS_ECN_ECT0:
3451 tp->ecn_flags |= TE_ACE_SETUP_ECT0;
3452 break;
3453 case IPTOS_ECN_CE:
3454 tp->ecn_flags |= TE_ACE_SETUP_CE;
3455 break;
3456 }
3457 /*
3458 * We are not yet committing to send IP ECT packets when
3459 * Accurate ECN is enabled
3460 */
3461 tp->ecn_flags |= (TE_ACE_SETUPRECEIVED);
3462 }
3463 break;
3464 }
3465
3466 /*
3467 * The address and connection state are finalized
3468 */
3469 TCP_LOG_CONNECT(tp, false, 0);
3470
3471 tcp_add_fsw_flow(tp, ifp);
3472
3473 goto trimthenstep6;
3474 }
3475
3476 /*
3477 * If the state is SYN_RECEIVED and the seg contains an ACK,
3478 * but not for our SYN/ACK, send a RST.
3479 */
3480 case TCPS_SYN_RECEIVED:
3481 if ((thflags & TH_ACK) &&
3482 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
3483 SEQ_GT(th->th_ack, tp->snd_max))) {
3484 IF_TCP_STATINC(ifp, ooopacket);
3485 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad ACK");
3486 goto dropwithreset;
3487 }
3488
3489 /*
3490 * In SYN_RECEIVED state, if we recv some SYNS with
3491 * window scale and others without, window scaling should
3492 * be disabled. Otherwise the window advertised will be
3493 * lower if we assume scaling and the other end does not.
3494 */
3495 if ((thflags & TH_SYN) &&
3496 (tp->irs == th->th_seq) &&
3497 !(to.to_flags & TOF_SCALE)) {
3498 tp->t_flags &= ~TF_RCVD_SCALE;
3499 }
3500
3501 /*
3502 * AccECN server in SYN-RCVD state received an ACK with
3503 * SYN=0, process handshake encoding present in the ACK for SYN-ACK
3504 * and update receive side counters.
3505 */
3506 if (TCP_ACC_ECN_ON(tp) && (thflags & (TH_SYN | TH_ACK)) == TH_ACK) {
3507 const uint32_t ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3508 if (tlen == 0 && to.to_nsacks > 0) {
3509 /*
3510 * ACK for SYN-ACK reflects the state (ECN) in which SYN-ACK packet
3511 * was delivered. Use Table 4 of Accurate ECN draft to decode only
3512 * when a pure ACK with no SACK block is received.
3513 * 0|0|0 will fail Accurate ECN negotiation and disable ECN.
3514 */
3515 switch (ace_flags) {
3516 case (0 | TH_CWR | 0):
3517 /* Non-ECT SYN-ACK was delivered */
3518 OS_FALLTHROUGH;
3519 case (0 | TH_CWR | TH_ECE):
3520 /* ECT1 SYN-ACK was delivered */
3521 OS_FALLTHROUGH;
3522 case (TH_AE | 0 | 0):
3523 /* ECT0 SYN-ACK was delivered */
3524 tp->t_snd_ce_packets = 5;
3525 break;
3526 case (TH_AE | TH_CWR | 0):
3527 /* CE SYN-ACK was delivered, set cwnd to 2 segments */
3528 tp->t_snd_ce_packets = 6;
3529 tp->snd_cwnd = 2 * tp->t_maxseg;
3530 break;
3531 case (0 | 0 | 0):
3532 /* Disable ECN */
3533 tp->ecn_flags &= ~(TE_SETUPRECEIVED | TE_SENDIPECT |
3534 TE_SENDCWR | TE_ACE_SETUPRECEIVED);
3535 break;
3536 default:
3537 /* Unused values for forward compatibility */
3538 tp->t_snd_ce_packets = 5;
3539 break;
3540 }
3541 }
3542 /* Increment receive side counters based on IP-ECN */
3543 tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
3544 }
3545
3546 break;
3547
3548 /*
3549 * If the state is SYN_SENT:
3550 * if seg contains an ACK, but not for our SYN, drop the input.
3551 * if seg contains a RST, then drop the connection.
3552 * if seg does not contain SYN, then drop it.
3553 * Otherwise this is an acceptable SYN segment
3554 * initialize tp->rcv_nxt and tp->irs
3555 * if seg contains ack then advance tp->snd_una
3556 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3557 * arrange for segment to be acked (eventually)
3558 * continue processing rest of data/controls, beginning with URG
3559 */
3560 case TCPS_SYN_SENT:
3561 if ((thflags & TH_ACK) &&
3562 (SEQ_LEQ(th->th_ack, tp->iss) ||
3563 SEQ_GT(th->th_ack, tp->snd_max))) {
3564 IF_TCP_STATINC(ifp, ooopacket);
3565 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT bad ACK");
3566 goto dropwithreset;
3567 }
3568 if (thflags & TH_RST) {
3569 if ((thflags & TH_ACK) != 0) {
3570 if (tfo_enabled(tp) &&
3571 !(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE)) {
3572 tcp_heuristic_tfo_rst(tp);
3573 }
3574 if ((tp->ecn_flags & (TE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_SETUPSENT ||
3575 (tp->ecn_flags & (TE_ACE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_ACE_SETUPSENT) {
3576 /*
3577 * On local connections, send
3578 * non-ECN syn one time before
3579 * dropping the connection
3580 */
3581 if (tp->t_flags & TF_LOCAL) {
3582 tp->ecn_flags |= TE_RCVD_SYN_RST;
3583 goto drop;
3584 } else {
3585 tcp_heuristic_ecn_synrst(tp);
3586 }
3587 }
3588 soevent(so,
3589 (SO_FILT_HINT_LOCKED |
3590 SO_FILT_HINT_CONNRESET));
3591 tp = tcp_drop(tp, ECONNREFUSED);
3592 }
3593 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT got RST");
3594 goto drop;
3595 }
3596 if ((thflags & TH_SYN) == 0) {
3597 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT no SYN");
3598 goto drop;
3599 }
3600 tp->snd_wnd = th->th_win; /* initial send window */
3601 tp->max_sndwnd = tp->snd_wnd;
3602
3603 tp->irs = th->th_seq;
3604 tcp_rcvseqinit(tp);
3605 if (thflags & TH_ACK) {
3606 /* Client processes SYN-ACK */
3607 tcpstat.tcps_connects++;
3608
3609 const uint32_t ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3610
3611 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE)) {
3612 /* Receiving Any|0|1 is classic ECN-setup SYN-ACK */
3613 tp->ecn_flags |= TE_SETUPRECEIVED;
3614 if (TCP_ECN_ENABLED(tp)) {
3615 tcp_heuristic_ecn_success(tp);
3616 tcpstat.tcps_ecn_client_success++;
3617 }
3618
3619 if (tp->ecn_flags & TE_ACE_SETUPSENT) {
3620 /*
3621 * Sent AccECN SYN but received classic ECN SYN-ACK
3622 * Set classic ECN related flags
3623 */
3624 tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
3625 tp->ecn_flags &= ~TE_ACE_SETUPSENT;
3626 }
3627 } else if (TCP_ACC_ECN_ENABLED() && ace_flags != 0 &&
3628 ace_flags != TH_ACE) {
3629 /* Initialize sender side packet & byte counters */
3630 tp->t_snd_ce_packets = 5;
3631 tp->t_snd_ect1_bytes = tp->t_snd_ect0_bytes = 1;
3632 tp->t_snd_ce_bytes = 0;
3633 tp->ecn_flags |= TE_ACE_FINAL_ACK_3WHS;
3634 /*
3635 * Client received AccECN SYN-ACK that reflects the state (ECN)
3636 * in which SYN packet was delivered. This helps to detect if
3637 * there was mangling of the SYN packet on the path. Currently, we
3638 * only send Not-ECT on SYN packets. So, we should set Not-ECT in
3639 * all packets if we receive any encoding other than 0|TH_CWR|0.
3640 * If 0|0|0 and 1|1|1 were received, fail Accurate ECN negotiation
3641 * by not setting TE_ACE_SETUPRECEIVED.
3642 */
3643 switch (ace_flags) {
3644 case (0 | TH_CWR | 0):
3645 /* Non-ECT SYN was delivered */
3646 tp->ecn_flags |= TE_ACE_SETUPRECEIVED;
3647 tcpstat.tcps_ecn_ace_syn_not_ect++;
3648 break;
3649 case (0 | TH_CWR | TH_ECE):
3650 /* ECT1 SYN was delivered */
3651 tp->ecn_flags |= TE_ACE_SETUPRECEIVED;
3652 /* Mangling detected, set Non-ECT on outgoing packets */
3653 tp->ecn_flags &= ~TE_SENDIPECT;
3654 tcpstat.tcps_ecn_ace_syn_ect1++;
3655 break;
3656 case (TH_AE | 0 | 0):
3657 /* ECT0 SYN was delivered */
3658 tp->ecn_flags |= TE_ACE_SETUPRECEIVED;
3659 /* Mangling detected, set Non-ECT on outgoing packets */
3660 tp->ecn_flags &= ~TE_SENDIPECT;
3661 tcpstat.tcps_ecn_ace_syn_ect0++;
3662 break;
3663 case (TH_AE | TH_CWR | 0):
3664 /* CE SYN was delivered */
3665 tp->ecn_flags |= TE_ACE_SETUPRECEIVED;
3666 /* Mangling detected, set Non-ECT on outgoing packets */
3667 tp->ecn_flags &= ~TE_SENDIPECT;
3668 /*
3669 * Although we don't send ECT SYN yet, it is possible that
3670 * a network element changed Not-ECT to ECT and later there
3671 * was congestion at another network element that set it to CE.
3672 * To keep it simple, we will consider this as a congestion event
3673 * for the congestion controller.
3674 * If a TCP client in AccECN mode receives CE feedback in the TCP
3675 * flags of a SYN/ACK, it MUST NOT increment s.cep.
3676 */
3677 tcpstat.tcps_ecn_ace_syn_ce++;
3678 break;
3679 default:
3680 break;
3681 }
3682 if (TCP_ECN_ENABLED(tp)) {
3683 tcp_heuristic_ecn_success(tp);
3684 tcpstat.tcps_ecn_client_success++;
3685 }
3686 /*
3687 * A TCP client in AccECN mode MUST feed back which of the 4
3688 * possible values of the IP-ECN field that was received in the
3689 * SYN/ACK. Set the setup flag for final ACK accordingly.
3690 * We will initialize r.cep, r.e1b, r.e0b first and then increment
3691 * if CE was set on the IP-ECN field of the SYN-ACK.
3692 */
3693 tp->t_rcv_ce_packets = 5;
3694 tp->t_rcv_ect0_bytes = tp->t_rcv_ect1_bytes = 1;
3695 tp->t_rcv_ce_bytes = 0;
3696
3697 /* Increment packet & byte counters based on IP-ECN */
3698 tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
3699
3700 switch (ip_ecn) {
3701 case IPTOS_ECN_NOTECT:
3702 /* Not-ECT SYN-ACK was received */
3703 tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
3704 break;
3705 case IPTOS_ECN_ECT1:
3706 /* ECT1 SYN-ACK was received */
3707 tp->ecn_flags |= TE_ACE_SETUP_ECT1;
3708 break;
3709 case IPTOS_ECN_ECT0:
3710 /* ECT0 SYN-ACK was received */
3711 tp->ecn_flags |= TE_ACE_SETUP_ECT0;
3712 break;
3713 case IPTOS_ECN_CE:
3714 tp->ecn_flags |= TE_ACE_SETUP_CE;
3715 break;
3716 }
3717 } else {
3718 if ((tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) &&
3719 tp->t_rxtshift == 0) {
3720 tcp_heuristic_ecn_success(tp);
3721 tcpstat.tcps_ecn_not_supported++;
3722 }
3723 if ((tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) &&
3724 tp->t_rxtshift > 0) {
3725 tcp_heuristic_ecn_loss(tp);
3726 }
3727
3728 /* non-ECN-setup SYN-ACK */
3729 tp->ecn_flags &= ~TE_SENDIPECT;
3730 }
3731
3732 /* Do window scaling on this connection? */
3733 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
3734 tp->snd_scale = tp->requested_s_scale;
3735 tp->rcv_scale = tp->request_r_scale;
3736 }
3737
3738 uint32_t recwin = min(tp->rcv_wnd, TCP_MAXWIN << tp->rcv_scale);
3739 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.get_rlwin != NULL) {
3740 /* For a LBE receiver, also use rledbat_win */
3741 uint32_t rledbat_win = tcp_cc_rledbat.get_rlwin(tp);
3742 if (rledbat_win > 0) {
3743 recwin = min(recwin, rledbat_win);
3744 }
3745 }
3746 tp->rcv_adv += recwin;
3747
3748 tp->snd_una++; /* SYN is acked */
3749 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
3750 tp->snd_nxt = tp->snd_una;
3751 }
3752
3753 /*
3754 * We have sent more in the SYN than what is being
3755 * acked. (e.g., TFO)
3756 * We should restart the sending from what the receiver
3757 * has acknowledged immediately.
3758 */
3759 if (SEQ_GT(tp->snd_nxt, th->th_ack)) {
3760 /*
3761 * rdar://problem/33214601
3762 * There is a middlebox that acks all but one
3763 * byte and still drops the data.
3764 */
3765 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
3766 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3767 tp->snd_max == th->th_ack + 1 &&
3768 tp->snd_max > tp->snd_una + 1) {
3769 tcp_heuristic_tfo_middlebox(tp);
3770
3771 so->so_error = ENODATA;
3772 soevent(so,
3773 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
3774
3775 tp->t_tfo_stats |= TFO_S_ONE_BYTE_PROXY;
3776 }
3777
3778 tp->snd_max = tp->snd_nxt = th->th_ack;
3779 }
3780
3781 /*
3782 * If there's data, delay ACK; if there's also a FIN
3783 * ACKNOW will be turned on later.
3784 */
3785 TCP_INC_VAR(tp->t_unacksegs, segment_count);
3786 if (DELAY_ACK(tp, th) && tlen != 0) {
3787 if ((tp->t_flags & TF_DELACK) == 0) {
3788 tp->t_flags |= TF_DELACK;
3789 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3790 }
3791 } else {
3792 tp->t_flags |= TF_ACKNOW;
3793 }
3794 /*
3795 * Received <SYN,ACK> in SYN_SENT[*] state.
3796 * Transitions:
3797 * SYN_SENT --> ESTABLISHED
3798 * SYN_SENT* --> FIN_WAIT_1
3799 */
3800 tp->t_starttime = tcp_now;
3801 tcp_sbrcv_tstmp_check(tp);
3802 if (tp->t_flags & TF_NEEDFIN) {
3803 DTRACE_TCP4(state__change, void, NULL,
3804 struct inpcb *, inp,
3805 struct tcpcb *, tp, int32_t,
3806 TCPS_FIN_WAIT_1);
3807 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
3808 tp->t_state = TCPS_FIN_WAIT_1;
3809 tp->t_flags &= ~TF_NEEDFIN;
3810 thflags &= ~TH_SYN;
3811
3812 TCP_LOG_CONNECTION_SUMMARY(tp);
3813 } else {
3814 DTRACE_TCP4(state__change, void, NULL,
3815 struct inpcb *, inp, struct tcpcb *,
3816 tp, int32_t, TCPS_ESTABLISHED);
3817 TCP_LOG_STATE(tp, TCPS_ESTABLISHED);
3818 tp->t_state = TCPS_ESTABLISHED;
3819 tp->t_timer[TCPT_KEEP] =
3820 OFFSET_FROM_START(tp,
3821 TCP_CONN_KEEPIDLE(tp));
3822 if (nstat_collect) {
3823 nstat_route_connect_success(
3824 inp->inp_route.ro_rt);
3825 }
3826 TCP_LOG_CONNECTED(tp, 0);
3827 /*
3828 * The SYN is acknowledged but una is not
3829 * updated yet. So pass the value of
3830 * ack to compute sndbytes correctly
3831 */
3832 inp_count_sndbytes(inp, th->th_ack);
3833 }
3834 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
3835 #if MPTCP
3836 /*
3837 * Do not send the connect notification for additional
3838 * subflows until ACK for 3-way handshake arrives.
3839 */
3840 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
3841 (tp->t_mpflags & TMPF_SENT_JOIN)) {
3842 isconnected = FALSE;
3843 } else
3844 #endif /* MPTCP */
3845 isconnected = TRUE;
3846
3847 if ((tp->t_tfo_flags & (TFO_F_COOKIE_REQ | TFO_F_COOKIE_SENT)) ||
3848 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT)) {
3849 tcp_tfo_synack(tp, &to);
3850
3851 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3852 SEQ_LT(tp->snd_una, th->th_ack)) {
3853 tp->t_tfo_stats |= TFO_S_SYN_DATA_ACKED;
3854 tcpstat.tcps_tfo_syn_data_acked++;
3855 #if MPTCP
3856 if (so->so_flags & SOF_MP_SUBFLOW) {
3857 so->so_flags1 |= SOF1_TFO_REWIND;
3858 }
3859 #endif
3860 tcp_tfo_rcv_probe(tp, tlen);
3861 }
3862 }
3863 } else {
3864 /*
3865 * Received initial SYN in SYN-SENT[*] state => simul-
3866 * taneous open.
3867 * Do 3-way handshake:
3868 * SYN-SENT -> SYN-RECEIVED
3869 * SYN-SENT* -> SYN-RECEIVED*
3870 */
3871 tp->t_flags |= TF_ACKNOW;
3872 tp->t_timer[TCPT_REXMT] = 0;
3873 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3874 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
3875 TCP_LOG_STATE(tp, TCPS_SYN_RECEIVED);
3876 tp->t_state = TCPS_SYN_RECEIVED;
3877
3878 /*
3879 * During simultaneous open, TFO should not be used.
3880 * So, we disable it here, to prevent that data gets
3881 * sent on the SYN/ACK.
3882 */
3883 tcp_disable_tfo(tp);
3884 }
3885
3886 trimthenstep6:
3887 /*
3888 * Advance th->th_seq to correspond to first data byte.
3889 * If data, trim to stay within window,
3890 * dropping FIN if necessary.
3891 */
3892 th->th_seq++;
3893 if (tlen > tp->rcv_wnd) {
3894 todrop = tlen - tp->rcv_wnd;
3895 m_adj(m, -todrop);
3896 tlen = tp->rcv_wnd;
3897 thflags &= ~TH_FIN;
3898 tcpstat.tcps_rcvpackafterwin++;
3899 tcpstat.tcps_rcvbyteafterwin += todrop;
3900 }
3901 tp->snd_wl1 = th->th_seq - 1;
3902 tp->rcv_up = th->th_seq;
3903 /*
3904 * Client side of transaction: already sent SYN and data.
3905 * If the remote host used T/TCP to validate the SYN,
3906 * our data will be ACK'd; if so, enter normal data segment
3907 * processing in the middle of step 5, ack processing.
3908 * Otherwise, goto step 6.
3909 */
3910 if (thflags & TH_ACK) {
3911 goto process_ACK;
3912 }
3913 goto step6;
3914 /*
3915 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
3916 * do normal processing.
3917 *
3918 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
3919 */
3920 case TCPS_LAST_ACK:
3921 case TCPS_CLOSING:
3922 case TCPS_TIME_WAIT:
3923 break; /* continue normal processing */
3924
3925 /* Received a SYN while connection is already established.
3926 * This is a "half open connection and other anomalies" described
3927 * in RFC793 page 34, send an ACK so the remote reset the connection
3928 * or recovers by adjusting its sequence numbering. Sending an ACK is
3929 * in accordance with RFC 5961 Section 4.2
3930 */
3931 case TCPS_ESTABLISHED:
3932 if (thflags & TH_SYN && tlen <= 0) {
3933 /* Drop the packet silently if we have reached the limit */
3934 if (tcp_is_ack_ratelimited(tp)) {
3935 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
3936 goto drop;
3937 } else {
3938 /* Send challenge ACK */
3939 tcpstat.tcps_synchallenge++;
3940 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
3941 goto dropafterack;
3942 }
3943 }
3944 break;
3945 }
3946
3947 /*
3948 * States other than LISTEN or SYN_SENT.
3949 * First check the RST flag and sequence number since reset segments
3950 * are exempt from the timestamp and connection count tests. This
3951 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
3952 * below which allowed reset segments in half the sequence space
3953 * to fall though and be processed (which gives forged reset
3954 * segments with a random sequence number a 50 percent chance of
3955 * killing a connection).
3956 * Then check timestamp, if present.
3957 * Then check the connection count, if present.
3958 * Then check that at least some bytes of segment are within
3959 * receive window. If segment begins before rcv_nxt,
3960 * drop leading data (and SYN); if nothing left, just ack.
3961 *
3962 *
3963 * If the RST bit is set, check the sequence number to see
3964 * if this is a valid reset segment.
3965 * RFC 793 page 37:
3966 * In all states except SYN-SENT, all reset (RST) segments
3967 * are validated by checking their SEQ-fields. A reset is
3968 * valid if its sequence number is in the window.
3969 * Note: this does not take into account delayed ACKs, so
3970 * we should test against last_ack_sent instead of rcv_nxt.
3971 * The sequence number in the reset segment is normally an
3972 * echo of our outgoing acknowlegement numbers, but some hosts
3973 * send a reset with the sequence number at the rightmost edge
3974 * of our receive window, and we have to handle this case.
3975 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
3976 * that brute force RST attacks are possible. To combat this,
3977 * we use a much stricter check while in the ESTABLISHED state,
3978 * only accepting RSTs where the sequence number is equal to
3979 * last_ack_sent. In all other states (the states in which a
3980 * RST is more likely), the more permissive check is used.
3981 * RFC 5961 Section 3.2: if the RST bit is set, sequence # is
3982 * within the receive window and last_ack_sent == seq,
3983 * then reset the connection. Otherwise if the seq doesn't
3984 * match last_ack_sent, TCP must send challenge ACK. Perform
3985 * rate limitation when sending the challenge ACK.
3986 * If we have multiple segments in flight, the intial reset
3987 * segment sequence numbers will be to the left of last_ack_sent,
3988 * but they will eventually catch up.
3989 * In any case, it never made sense to trim reset segments to
3990 * fit the receive window since RFC 1122 says:
3991 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
3992 *
3993 * A TCP SHOULD allow a received RST segment to include data.
3994 *
3995 * DISCUSSION
3996 * It has been suggested that a RST segment could contain
3997 * ASCII text that encoded and explained the cause of the
3998 * RST. No standard has yet been established for such
3999 * data.
4000 *
4001 * If the reset segment passes the sequence number test examine
4002 * the state:
4003 * SYN_RECEIVED STATE:
4004 * If passive open, return to LISTEN state.
4005 * If active open, inform user that connection was refused.
4006 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
4007 * Inform user that connection was reset, and close tcb.
4008 * CLOSING, LAST_ACK STATES:
4009 * Close the tcb.
4010 * TIME_WAIT STATE:
4011 * Drop the segment - see Stevens, vol. 2, p. 964 and
4012 * RFC 1337.
4013 *
4014 * Radar 4803931: Allows for the case where we ACKed the FIN but
4015 * there is already a RST in flight from the peer.
4016 * In that case, accept the RST for non-established
4017 * state if it's one off from last_ack_sent.
4018 *
4019 */
4020 if (thflags & TH_RST) {
4021 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
4022 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
4023 (tp->rcv_wnd == 0 &&
4024 ((tp->last_ack_sent == th->th_seq) ||
4025 ((tp->last_ack_sent - 1) == th->th_seq)))) {
4026 if (tp->last_ack_sent == th->th_seq) {
4027 switch (tp->t_state) {
4028 case TCPS_SYN_RECEIVED:
4029 IF_TCP_STATINC(ifp, rstinsynrcv);
4030 so->so_error = ECONNREFUSED;
4031 goto close;
4032
4033 case TCPS_ESTABLISHED:
4034 if ((TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) &&
4035 tp->snd_una == tp->iss + 1 &&
4036 SEQ_GT(tp->snd_max, tp->snd_una)) {
4037 /*
4038 * If the first data packet on an
4039 * ECN connection, receives a RST
4040 * increment the heuristic
4041 */
4042 tcp_heuristic_ecn_droprst(tp);
4043 }
4044 OS_FALLTHROUGH;
4045 case TCPS_FIN_WAIT_1:
4046 case TCPS_CLOSE_WAIT:
4047 case TCPS_FIN_WAIT_2:
4048 so->so_error = ECONNRESET;
4049 close:
4050 soevent(so,
4051 (SO_FILT_HINT_LOCKED |
4052 SO_FILT_HINT_CONNRESET));
4053
4054 tcpstat.tcps_drops++;
4055 tp = tcp_close(tp);
4056 break;
4057
4058 case TCPS_CLOSING:
4059 case TCPS_LAST_ACK:
4060 tp = tcp_close(tp);
4061 break;
4062
4063 case TCPS_TIME_WAIT:
4064 break;
4065 }
4066 } else {
4067 tcpstat.tcps_badrst++;
4068 /* Drop if we have reached the ACK limit */
4069 if (tcp_is_ack_ratelimited(tp)) {
4070 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
4071 goto drop;
4072 } else {
4073 /* Send challenge ACK */
4074 tcpstat.tcps_rstchallenge++;
4075 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
4076 goto dropafterack;
4077 }
4078 }
4079 }
4080 goto drop;
4081 }
4082
4083 /*
4084 * RFC 1323 PAWS: If we have a timestamp reply on this segment
4085 * and it's less than ts_recent, drop it.
4086 */
4087 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
4088 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
4089 /* Check to see if ts_recent is over 24 days old. */
4090 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
4091 /*
4092 * Invalidate ts_recent. If this segment updates
4093 * ts_recent, the age will be reset later and ts_recent
4094 * will get a valid value. If it does not, setting
4095 * ts_recent to zero will at least satisfy the
4096 * requirement that zero be placed in the timestamp
4097 * echo reply when ts_recent isn't valid. The
4098 * age isn't reset until we get a valid ts_recent
4099 * because we don't want out-of-order segments to be
4100 * dropped when ts_recent is old.
4101 */
4102 tp->ts_recent = 0;
4103 } else {
4104 tcpstat.tcps_rcvduppack++;
4105 tcpstat.tcps_rcvdupbyte += tlen;
4106 tp->t_pawsdrop++;
4107 tcpstat.tcps_pawsdrop++;
4108
4109 /*
4110 * PAWS-drop when ECN is being used? That indicates
4111 * that ECT-marked packets take a different path, with
4112 * different congestion-characteristics.
4113 *
4114 * Only fallback when we did send less than 2GB as PAWS
4115 * really has no reason to kick in earlier.
4116 */
4117 if ((TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) &&
4118 inp->inp_stat->rxbytes < 2147483648) {
4119 INP_INC_IFNET_STAT(inp, ecn_fallback_reorder);
4120 tcpstat.tcps_ecn_fallback_reorder++;
4121 tcp_heuristic_ecn_aggressive(tp);
4122 }
4123
4124 if (nstat_collect) {
4125 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt,
4126 1, tlen, NSTAT_RX_FLAG_DUPLICATE);
4127 INP_ADD_STAT(inp, cell, wifi, wired,
4128 rxpackets, 1);
4129 INP_ADD_STAT(inp, cell, wifi, wired,
4130 rxbytes, tlen);
4131 tp->t_stat.rxduplicatebytes += tlen;
4132 inp_set_activity_bitmap(inp);
4133 }
4134 if (tlen > 0) {
4135 goto dropafterack;
4136 }
4137 goto drop;
4138 }
4139 }
4140
4141 /*
4142 * In the SYN-RECEIVED state, validate that the packet belongs to
4143 * this connection before trimming the data to fit the receive
4144 * window. Check the sequence number versus IRS since we know
4145 * the sequence numbers haven't wrapped. This is a partial fix
4146 * for the "LAND" DoS attack.
4147 */
4148 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
4149 IF_TCP_STATINC(ifp, dospacket);
4150 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad SEQ");
4151 goto dropwithreset;
4152 }
4153
4154 /*
4155 * Check if there is old data at the beginning of the window
4156 * i.e. the sequence number is before rcv_nxt
4157 */
4158 todrop = tp->rcv_nxt - th->th_seq;
4159 if (todrop > 0) {
4160 boolean_t is_syn_set = FALSE;
4161
4162 if (thflags & TH_SYN) {
4163 is_syn_set = TRUE;
4164 thflags &= ~TH_SYN;
4165 th->th_seq++;
4166 if (th->th_urp > 1) {
4167 th->th_urp--;
4168 } else {
4169 thflags &= ~TH_URG;
4170 }
4171 todrop--;
4172 }
4173 /*
4174 * Following if statement from Stevens, vol. 2, p. 960.
4175 * The amount of duplicate data is greater than or equal
4176 * to the size of the segment - entire segment is duplicate
4177 */
4178 if (todrop > tlen
4179 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
4180 /*
4181 * Any valid FIN must be to the left of the window.
4182 * At this point the FIN must be a duplicate or out
4183 * of sequence; drop it.
4184 */
4185 thflags &= ~TH_FIN;
4186
4187 /*
4188 * Send an ACK to resynchronize and drop any data.
4189 * But keep on processing for RST or ACK.
4190 *
4191 * If the SYN bit was originally set, then only send
4192 * an ACK if we are not rate-limiting this connection.
4193 */
4194 if (is_syn_set) {
4195 if (!tcp_is_ack_ratelimited(tp)) {
4196 tcpstat.tcps_synchallenge++;
4197 tp->t_flags |= TF_ACKNOW;
4198 }
4199 } else {
4200 tp->t_flags |= TF_ACKNOW;
4201 }
4202
4203 if (todrop == 1) {
4204 /* This could be a keepalive */
4205 soevent(so, SO_FILT_HINT_LOCKED |
4206 SO_FILT_HINT_KEEPALIVE);
4207 }
4208 todrop = tlen;
4209 tcpstat.tcps_rcvduppack++;
4210 tcpstat.tcps_rcvdupbyte += todrop;
4211 } else {
4212 tcpstat.tcps_rcvpartduppack++;
4213 tcpstat.tcps_rcvpartdupbyte += todrop;
4214 }
4215
4216 if (todrop > 1) {
4217 /*
4218 * Note the duplicate data sequence space so that
4219 * it can be reported in DSACK option.
4220 */
4221 tp->t_dsack_lseq = th->th_seq;
4222 tp->t_dsack_rseq = th->th_seq + todrop;
4223 tp->t_flags |= TF_ACKNOW;
4224 }
4225 if (nstat_collect) {
4226 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt, 1,
4227 todrop, NSTAT_RX_FLAG_DUPLICATE);
4228 INP_ADD_STAT(inp, cell, wifi, wired, rxpackets, 1);
4229 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes, todrop);
4230 tp->t_stat.rxduplicatebytes += todrop;
4231 inp_set_activity_bitmap(inp);
4232 }
4233 drop_hdrlen += todrop; /* drop from the top afterwards */
4234 th->th_seq += todrop;
4235 tlen -= todrop;
4236 if (th->th_urp > todrop) {
4237 th->th_urp -= todrop;
4238 } else {
4239 thflags &= ~TH_URG;
4240 th->th_urp = 0;
4241 }
4242 }
4243
4244 /*
4245 * If new data are received on a connection after the user
4246 * processes are gone, then RST the other end.
4247 * Send also a RST when we received a data segment after we've
4248 * sent our FIN when the socket is defunct.
4249 * Note that an MPTCP subflow socket would have SS_NOFDREF set
4250 * by default. So, if it's an MPTCP-subflow we rather check the
4251 * MPTCP-level's socket state for SS_NOFDREF.
4252 */
4253 if (tlen) {
4254 boolean_t close_it = FALSE;
4255
4256 if (!(so->so_flags & SOF_MP_SUBFLOW) && (so->so_state & SS_NOFDREF) &&
4257 tp->t_state > TCPS_CLOSE_WAIT) {
4258 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_NOFDREF");
4259 close_it = TRUE;
4260 }
4261
4262 if ((so->so_flags & SOF_MP_SUBFLOW) && (mptetoso(tptomptp(tp)->mpt_mpte)->so_state & SS_NOFDREF) &&
4263 tp->t_state > TCPS_CLOSE_WAIT) {
4264 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_MP_SUBFLOW SS_NOFDREF");
4265 close_it = TRUE;
4266 }
4267
4268 if ((so->so_flags & SOF_DEFUNCT) && tp->t_state > TCPS_FIN_WAIT_1) {
4269 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_DEFUNCT");
4270 close_it = TRUE;
4271 }
4272
4273 if (so->so_state & SS_CANTRCVMORE) {
4274 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_CANTRCVMORE");
4275 close_it = TRUE;
4276 }
4277
4278 if (close_it) {
4279 tp = tcp_close(tp);
4280 tcpstat.tcps_rcvafterclose++;
4281 IF_TCP_STATINC(ifp, cleanup);
4282 goto dropwithreset;
4283 }
4284 }
4285
4286 /*
4287 * If segment ends after window, drop trailing data
4288 * (and PUSH and FIN); if nothing left, just ACK.
4289 */
4290 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
4291 if (todrop > 0) {
4292 tcpstat.tcps_rcvpackafterwin++;
4293 if (todrop >= tlen) {
4294 tcpstat.tcps_rcvbyteafterwin += tlen;
4295 /*
4296 * If a new connection request is received
4297 * while in TIME_WAIT, drop the old connection
4298 * and start over if the sequence numbers
4299 * are above the previous ones.
4300 */
4301 if (thflags & TH_SYN &&
4302 tp->t_state == TCPS_TIME_WAIT &&
4303 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
4304 iss = tcp_new_isn(tp);
4305 tp = tcp_close(tp);
4306 socket_unlock(so, 1);
4307 goto findpcb;
4308 }
4309 /*
4310 * If window is closed can only take segments at
4311 * window edge, and have to drop data and PUSH from
4312 * incoming segments. Continue processing, but
4313 * remember to ack. Otherwise, drop segment
4314 * and ack.
4315 */
4316 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
4317 tp->t_flags |= TF_ACKNOW;
4318 tcpstat.tcps_rcvwinprobe++;
4319 } else {
4320 goto dropafterack;
4321 }
4322 } else {
4323 tcpstat.tcps_rcvbyteafterwin += todrop;
4324 }
4325 m_adj(m, -todrop);
4326 tlen -= todrop;
4327 thflags &= ~(TH_PUSH | TH_FIN);
4328 }
4329
4330 /*
4331 * If last ACK falls within this segment's sequence numbers,
4332 * record its timestamp.
4333 * NOTE:
4334 * 1) That the test incorporates suggestions from the latest
4335 * proposal of the [email protected] list (Braden 1993/04/26).
4336 * 2) That updating only on newer timestamps interferes with
4337 * our earlier PAWS tests, so this check should be solely
4338 * predicated on the sequence space of this segment.
4339 * 3) That we modify the segment boundary check to be
4340 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
4341 * instead of RFC1323's
4342 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
4343 * This modified check allows us to overcome RFC1323's
4344 * limitations as described in Stevens TCP/IP Illustrated
4345 * Vol. 2 p.869. In such cases, we can still calculate the
4346 * RTT correctly when RCV.NXT == Last.ACK.Sent.
4347 */
4348 if ((to.to_flags & TOF_TS) != 0 &&
4349 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
4350 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
4351 ((thflags & (TH_SYN | TH_FIN)) != 0))) {
4352 tp->ts_recent_age = tcp_now;
4353 tp->ts_recent = to.to_tsval;
4354 }
4355
4356 /*
4357 * Stevens: If a SYN is in the window, then this is an
4358 * error and we send an RST and drop the connection.
4359 *
4360 * RFC 5961 Section 4.2
4361 * Send challenge ACK for any SYN in synchronized state
4362 * Perform rate limitation in doing so.
4363 */
4364 if (thflags & TH_SYN) {
4365 if (!tcp_syn_data_valid(tp, th, tlen)) {
4366 tcpstat.tcps_badsyn++;
4367 /* Drop if we have reached ACK limit */
4368 if (tcp_is_ack_ratelimited(tp)) {
4369 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN rate limited");
4370 goto drop;
4371 } else {
4372 /* Send challenge ACK */
4373 tcpstat.tcps_synchallenge++;
4374 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN challenge ack");
4375 goto dropafterack;
4376 }
4377 } else {
4378 /*
4379 * Received SYN (/ACK) with data.
4380 * Move sequence number along to process the data.
4381 */
4382 th->th_seq++;
4383 thflags &= ~TH_SYN;
4384 }
4385 }
4386
4387 /*
4388 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
4389 * flag is on (half-synchronized state), then queue data for
4390 * later processing; else drop segment and return.
4391 */
4392 if ((thflags & TH_ACK) == 0) {
4393 if (tp->t_state == TCPS_SYN_RECEIVED) {
4394 if ((tfo_enabled(tp))) {
4395 /*
4396 * So, we received a valid segment while in
4397 * SYN-RECEIVED.
4398 * As this cannot be an RST (see that if a bit
4399 * higher), and it does not have the ACK-flag
4400 * set, we want to retransmit the SYN/ACK.
4401 * Thus, we have to reset snd_nxt to snd_una to
4402 * trigger the going back to sending of the
4403 * SYN/ACK. This is more consistent with the
4404 * behavior of tcp_output(), which expects
4405 * to send the segment that is pointed to by
4406 * snd_nxt.
4407 */
4408 tp->snd_nxt = tp->snd_una;
4409
4410 /*
4411 * We need to make absolutely sure that we are
4412 * going to reply upon a duplicate SYN-segment.
4413 */
4414 if (th->th_flags & TH_SYN) {
4415 needoutput = 1;
4416 }
4417 }
4418
4419 goto step6;
4420 } else if (tp->t_flags & TF_ACKNOW) {
4421 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4422 goto dropafterack;
4423 } else {
4424 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4425 goto drop;
4426 }
4427 }
4428
4429 /*
4430 * Ack processing.
4431 */
4432
4433 switch (tp->t_state) {
4434 /*
4435 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
4436 * ESTABLISHED state and continue processing.
4437 * The ACK was checked above.
4438 */
4439 case TCPS_SYN_RECEIVED:
4440
4441 tcpstat.tcps_connects++;
4442
4443 /* Do window scaling? */
4444 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
4445 tp->snd_scale = tp->requested_s_scale;
4446 tp->rcv_scale = tp->request_r_scale;
4447 tp->snd_wnd = th->th_win << tp->snd_scale;
4448 tp->max_sndwnd = tp->snd_wnd;
4449 tiwin = tp->snd_wnd;
4450 }
4451 /*
4452 * Make transitions:
4453 * SYN-RECEIVED -> ESTABLISHED
4454 * SYN-RECEIVED* -> FIN-WAIT-1
4455 */
4456 tp->t_starttime = tcp_now;
4457 tcp_sbrcv_tstmp_check(tp);
4458 if (tp->t_flags & TF_NEEDFIN) {
4459 DTRACE_TCP4(state__change, void, NULL,
4460 struct inpcb *, inp,
4461 struct tcpcb *, tp, int32_t, TCPS_FIN_WAIT_1);
4462 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
4463 tp->t_state = TCPS_FIN_WAIT_1;
4464 tp->t_flags &= ~TF_NEEDFIN;
4465
4466 TCP_LOG_CONNECTION_SUMMARY(tp);
4467 } else {
4468 DTRACE_TCP4(state__change, void, NULL,
4469 struct inpcb *, inp,
4470 struct tcpcb *, tp, int32_t, TCPS_ESTABLISHED);
4471 TCP_LOG_STATE(tp, TCPS_ESTABLISHED);
4472 tp->t_state = TCPS_ESTABLISHED;
4473 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
4474 TCP_CONN_KEEPIDLE(tp));
4475 if (nstat_collect) {
4476 nstat_route_connect_success(
4477 tp->t_inpcb->inp_route.ro_rt);
4478 }
4479 TCP_LOG_CONNECTED(tp, 0);
4480 /*
4481 * The SYN is acknowledged but una is not updated
4482 * yet. So pass the value of ack to compute
4483 * sndbytes correctly
4484 */
4485 inp_count_sndbytes(inp, th->th_ack);
4486 }
4487 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
4488
4489 VERIFY(LIST_EMPTY(&tp->t_segq));
4490 tp->snd_wl1 = th->th_seq - 1;
4491
4492 #if MPTCP
4493 /*
4494 * Do not send the connect notification for additional subflows
4495 * until ACK for 3-way handshake arrives.
4496 */
4497 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
4498 (tp->t_mpflags & TMPF_SENT_JOIN)) {
4499 isconnected = FALSE;
4500 } else
4501 #endif /* MPTCP */
4502 isconnected = TRUE;
4503 if ((tp->t_tfo_flags & TFO_F_COOKIE_VALID)) {
4504 /* Done this when receiving the SYN */
4505 isconnected = FALSE;
4506
4507 OSDecrementAtomic(&tcp_tfo_halfcnt);
4508
4509 /* Panic if something has gone terribly wrong. */
4510 VERIFY(tcp_tfo_halfcnt >= 0);
4511
4512 tp->t_tfo_flags &= ~TFO_F_COOKIE_VALID;
4513 }
4514
4515 /*
4516 * In case there is data in the send-queue (e.g., TFO is being
4517 * used, or connectx+data has been done), then if we would
4518 * "FALLTHROUGH", we would handle this ACK as if data has been
4519 * acknowledged. But, we have to prevent this. And this
4520 * can be prevented by increasing snd_una by 1, so that the
4521 * SYN is not considered as data (snd_una++ is actually also
4522 * done in SYN_SENT-state as part of the regular TCP stack).
4523 *
4524 * In case there is data on this ack as well, the data will be
4525 * handled by the label "dodata" right after step6.
4526 */
4527 if (so->so_snd.sb_cc) {
4528 tp->snd_una++; /* SYN is acked */
4529 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4530 tp->snd_nxt = tp->snd_una;
4531 }
4532
4533 /*
4534 * No duplicate-ACK handling is needed. So, we
4535 * directly advance to processing the ACK (aka,
4536 * updating the RTT estimation,...)
4537 *
4538 * But, we first need to handle eventual SACKs,
4539 * because TFO will start sending data with the
4540 * SYN/ACK, so it might be that the client
4541 * includes a SACK with its ACK.
4542 */
4543 if (SACK_ENABLED(tp) &&
4544 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4545 tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &sack_bytes_newly_acked);
4546 }
4547
4548 goto process_ACK;
4549 }
4550
4551 OS_FALLTHROUGH;
4552
4553 /*
4554 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4555 * ACKs. If the ack is in the range
4556 * tp->snd_una < th->th_ack <= tp->snd_max
4557 * then advance tp->snd_una to th->th_ack and drop
4558 * data from the retransmission queue. If this ACK reflects
4559 * more up to date window information we update our window information.
4560 */
4561 case TCPS_ESTABLISHED:
4562 case TCPS_FIN_WAIT_1:
4563 case TCPS_FIN_WAIT_2:
4564 case TCPS_CLOSE_WAIT:
4565 case TCPS_CLOSING:
4566 case TCPS_LAST_ACK:
4567 case TCPS_TIME_WAIT:
4568 if (SEQ_GT(th->th_ack, tp->snd_max)) {
4569 tcpstat.tcps_rcvacktoomuch++;
4570 if (tcp_is_ack_ratelimited(tp)) {
4571 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 rcvacktoomuch");
4572 goto drop;
4573 } else {
4574 goto dropafterack;
4575 }
4576 }
4577 if (SEQ_LT(th->th_ack, tp->snd_una - tp->max_sndwnd)) {
4578 if (tcp_is_ack_ratelimited(tp)) {
4579 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad ACK");
4580 goto drop;
4581 } else {
4582 goto dropafterack;
4583 }
4584 }
4585 if (SACK_ENABLED(tp) && to.to_nsacks > 0) {
4586 recvd_dsack = tcp_sack_process_dsack(tp, &to, th);
4587 /*
4588 * If DSACK is received and this packet has no
4589 * other SACK information, it can be dropped.
4590 * We do not want to treat it as a duplicate ack.
4591 */
4592 if (recvd_dsack &&
4593 SEQ_LEQ(th->th_ack, tp->snd_una) &&
4594 to.to_nsacks == 0) {
4595 tcp_bad_rexmt_check(tp, th, &to);
4596 goto drop;
4597 }
4598 }
4599
4600 if (SACK_ENABLED(tp) &&
4601 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4602 tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &sack_bytes_newly_acked);
4603 }
4604
4605 #if MPTCP
4606 if (tp->t_mpuna && SEQ_GEQ(th->th_ack, tp->t_mpuna)) {
4607 if (tp->t_mpflags & TMPF_PREESTABLISHED) {
4608 /* MP TCP establishment succeeded */
4609 tp->t_mpuna = 0;
4610 if (tp->t_mpflags & TMPF_JOINED_FLOW) {
4611 if (tp->t_mpflags & TMPF_SENT_JOIN) {
4612 tp->t_mpflags &=
4613 ~TMPF_PREESTABLISHED;
4614 tp->t_mpflags |=
4615 TMPF_MPTCP_TRUE;
4616
4617 tp->t_timer[TCPT_JACK_RXMT] = 0;
4618 tp->t_mprxtshift = 0;
4619 isconnected = TRUE;
4620 } else {
4621 isconnected = FALSE;
4622 }
4623 } else {
4624 isconnected = TRUE;
4625 }
4626 }
4627 }
4628 #endif /* MPTCP */
4629
4630 tcp_tfo_rcv_ack(tp, th);
4631
4632 /*
4633 * If we have outstanding data (other than
4634 * a window probe), this is a completely
4635 * duplicate ack and the ack is the biggest we've seen.
4636 *
4637 * Need to accommodate a change in window on duplicate acks
4638 * to allow operating systems that update window during
4639 * recovery with SACK
4640 */
4641 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
4642 if (tlen == 0 && (tiwin == tp->snd_wnd ||
4643 (to.to_nsacks > 0 && sack_bytes_acked > 0))) {
4644 uint32_t old_dupacks;
4645 /*
4646 * If both ends send FIN at the same time,
4647 * then the ack will be a duplicate ack
4648 * but we have to process the FIN. Check
4649 * for this condition and process the FIN
4650 * instead of the dupack
4651 */
4652 if ((thflags & TH_FIN) &&
4653 !TCPS_HAVERCVDFIN(tp->t_state)) {
4654 break;
4655 }
4656 process_dupack:
4657 old_dupacks = tp->t_dupacks;
4658 #if MPTCP
4659 /*
4660 * MPTCP options that are ignored must
4661 * not be treated as duplicate ACKs.
4662 */
4663 if (to.to_flags & TOF_MPTCP) {
4664 goto drop;
4665 }
4666
4667 if ((isconnected) && (tp->t_mpflags & TMPF_JOINED_FLOW)) {
4668 break;
4669 }
4670 #endif /* MPTCP */
4671 /*
4672 * If a duplicate acknowledgement was seen
4673 * after ECN, it indicates packet loss in
4674 * addition to ECN. Reset INRECOVERY flag
4675 * so that we can process partial acks
4676 * correctly
4677 */
4678 if (tp->ecn_flags & TE_INRECOVERY) {
4679 tp->ecn_flags &= ~TE_INRECOVERY;
4680 }
4681
4682 tcpstat.tcps_rcvdupack++;
4683 if (SACK_ENABLED(tp) && tcp_do_better_lr) {
4684 tp->t_dupacks += max(1, sack_bytes_acked / tp->t_maxseg);
4685 } else {
4686 ++tp->t_dupacks;
4687 }
4688
4689 tp->sackhint.sack_bytes_acked += sack_bytes_acked;
4690
4691 if (SACK_ENABLED(tp) && tcp_do_better_lr) {
4692 tp->t_new_dupacks += (sack_bytes_newly_acked / tp->t_maxseg);
4693
4694 if (tp->t_new_dupacks >= tp->t_rexmtthresh && IN_FASTRECOVERY(tp)) {
4695 /* Let's restart the retransmission */
4696 tcp_sack_lost_rexmit(tp);
4697
4698 /*
4699 * If the current tcp cc module has
4700 * defined a hook for tasks to run
4701 * before entering FR, call it
4702 */
4703 if (CC_ALGO(tp)->pre_fr != NULL) {
4704 CC_ALGO(tp)->pre_fr(tp);
4705 }
4706
4707 ENTER_FASTRECOVERY(tp);
4708
4709 if (tp->t_flags & TF_SENTFIN) {
4710 tp->snd_recover = tp->snd_max - 1;
4711 } else {
4712 tp->snd_recover = tp->snd_max;
4713 }
4714 tp->t_rtttime = 0;
4715 /*
4716 * Accurate ECN Sender MUST NOT set CWR to indicate
4717 * it has received and responded to indications
4718 * of congestion. ACE field is used to reflect counters
4719 * that are continously updated overloading the CWR bit.
4720 */
4721 if (!TCP_ACC_ECN_ON(tp) && TCP_ECN_ENABLED(tp)) {
4722 tp->ecn_flags |= TE_SENDCWR;
4723 }
4724
4725 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
4726 tcp_cc_adjust_nonvalidated_cwnd(tp);
4727 } else {
4728 tp->snd_cwnd = tp->snd_ssthresh;
4729 }
4730 }
4731 }
4732
4733 /*
4734 * Check if we need to reset the limit on
4735 * early retransmit
4736 */
4737 if (tp->t_early_rexmt_count > 0 &&
4738 TSTMP_GEQ(tcp_now,
4739 (tp->t_early_rexmt_win +
4740 TCP_EARLY_REXMT_WIN))) {
4741 tp->t_early_rexmt_count = 0;
4742 }
4743
4744 /*
4745 * Is early retransmit needed? We check for
4746 * this when the connection is waiting for
4747 * duplicate acks to enter fast recovery.
4748 */
4749 if (!IN_FASTRECOVERY(tp)) {
4750 tcp_early_rexmt_check(tp, th);
4751 }
4752
4753 /*
4754 * If we've seen exactly rexmt threshold
4755 * of duplicate acks, assume a packet
4756 * has been dropped and retransmit it.
4757 * Kludge snd_nxt & the congestion
4758 * window so we send only this one
4759 * packet.
4760 *
4761 * We know we're losing at the current
4762 * window size so do congestion avoidance
4763 * (set ssthresh to half the current window
4764 * and pull our congestion window back to
4765 * the new ssthresh).
4766 *
4767 * Dup acks mean that packets have left the
4768 * network (they're now cached at the receiver)
4769 * so bump cwnd by the amount in the receiver
4770 * to keep a constant cwnd packets in the
4771 * network.
4772 */
4773 if (tp->t_timer[TCPT_REXMT] == 0 ||
4774 (th->th_ack != tp->snd_una && sack_bytes_acked == 0)) {
4775 tp->t_dupacks = 0;
4776 tp->t_rexmtthresh = tcprexmtthresh;
4777 tp->t_new_dupacks = 0;
4778 } else if ((tp->t_dupacks > tp->t_rexmtthresh && (!tcp_do_better_lr || old_dupacks >= tp->t_rexmtthresh)) ||
4779 IN_FASTRECOVERY(tp)) {
4780 /*
4781 * If this connection was seeing packet
4782 * reordering, then recovery might be
4783 * delayed to disambiguate between
4784 * reordering and loss
4785 */
4786 if (SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
4787 (tp->t_flagsext &
4788 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) ==
4789 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
4790 /*
4791 * Since the SACK information is already
4792 * updated, this ACK will be dropped
4793 */
4794 break;
4795 }
4796
4797 /*
4798 * Dup acks mean that packets have left the
4799 * network (they're now cached at the receiver)
4800 * so bump cwnd by the amount in the receiver
4801 * to keep a constant cwnd packets in the
4802 * network.
4803 */
4804 if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp)) {
4805 int awnd;
4806
4807 /*
4808 * Compute the amount of data in flight first.
4809 * We can inject new data into the pipe iff
4810 * we have less than snd_ssthres worth of data in
4811 * flight.
4812 */
4813 awnd = (tp->snd_nxt - tp->snd_fack) + tp->sackhint.sack_bytes_rexmit;
4814 if (awnd < tp->snd_ssthresh) {
4815 tp->snd_cwnd += tp->t_maxseg;
4816 if (tp->snd_cwnd > tp->snd_ssthresh) {
4817 tp->snd_cwnd = tp->snd_ssthresh;
4818 }
4819 }
4820 } else {
4821 tp->snd_cwnd += tp->t_maxseg;
4822 }
4823
4824 /* Process any window updates */
4825 if (tiwin > tp->snd_wnd) {
4826 tcp_update_window(tp, thflags,
4827 th, tiwin, tlen);
4828 }
4829 tcp_ccdbg_trace(tp, th,
4830 TCP_CC_IN_FASTRECOVERY);
4831
4832 (void) tcp_output(tp);
4833
4834 goto drop;
4835 } else if ((!tcp_do_better_lr && tp->t_dupacks == tp->t_rexmtthresh) ||
4836 (tcp_do_better_lr && tp->t_dupacks >= tp->t_rexmtthresh)) {
4837 tcp_seq onxt = tp->snd_nxt;
4838
4839 /*
4840 * If we're doing sack, check to
4841 * see if we're already in sack
4842 * recovery. If we're not doing sack,
4843 * check to see if we're in newreno
4844 * recovery.
4845 */
4846 if (SACK_ENABLED(tp)) {
4847 if (IN_FASTRECOVERY(tp)) {
4848 tp->t_dupacks = 0;
4849 break;
4850 } else if (tp->t_flagsext & TF_DELAY_RECOVERY) {
4851 break;
4852 }
4853 } else {
4854 if (SEQ_LEQ(th->th_ack, tp->snd_recover)) {
4855 tp->t_dupacks = 0;
4856 break;
4857 }
4858 }
4859 if (tp->t_flags & TF_SENTFIN) {
4860 tp->snd_recover = tp->snd_max - 1;
4861 } else {
4862 tp->snd_recover = tp->snd_max;
4863 }
4864 tp->t_timer[TCPT_PTO] = 0;
4865 tp->t_rtttime = 0;
4866
4867 /*
4868 * If the connection has seen pkt
4869 * reordering, delay recovery until
4870 * it is clear that the packet
4871 * was lost.
4872 */
4873 if (SACK_ENABLED(tp) &&
4874 (tp->t_flagsext &
4875 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
4876 == TF_PKTS_REORDERED &&
4877 !IN_FASTRECOVERY(tp) &&
4878 tp->t_reorderwin > 0 &&
4879 (tp->t_state == TCPS_ESTABLISHED ||
4880 tp->t_state == TCPS_FIN_WAIT_1)) {
4881 tp->t_timer[TCPT_DELAYFR] =
4882 OFFSET_FROM_START(tp,
4883 tp->t_reorderwin);
4884 tp->t_flagsext |= TF_DELAY_RECOVERY;
4885 tcpstat.tcps_delay_recovery++;
4886 tcp_ccdbg_trace(tp, th,
4887 TCP_CC_DELAY_FASTRECOVERY);
4888 break;
4889 }
4890
4891 tcp_rexmt_save_state(tp);
4892 /*
4893 * If the current tcp cc module has
4894 * defined a hook for tasks to run
4895 * before entering FR, call it
4896 */
4897 if (CC_ALGO(tp)->pre_fr != NULL) {
4898 CC_ALGO(tp)->pre_fr(tp);
4899 }
4900 ENTER_FASTRECOVERY(tp);
4901 tp->t_timer[TCPT_REXMT] = 0;
4902 if (!TCP_ACC_ECN_ON(tp) && TCP_ECN_ENABLED(tp)) {
4903 tp->ecn_flags |= TE_SENDCWR;
4904 }
4905
4906 if (SACK_ENABLED(tp)) {
4907 tcpstat.tcps_sack_recovery_episode++;
4908 tp->t_sack_recovery_episode++;
4909 tp->sack_newdata = tp->snd_nxt;
4910 if (tcp_do_better_lr) {
4911 tp->snd_cwnd = tp->snd_ssthresh;
4912 } else {
4913 tp->snd_cwnd = tp->t_maxseg;
4914 }
4915 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
4916
4917 /* Process any window updates */
4918 if (tiwin > tp->snd_wnd) {
4919 tcp_update_window(tp, thflags, th, tiwin, tlen);
4920 }
4921
4922 tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
4923 (void) tcp_output(tp);
4924 goto drop;
4925 }
4926 tp->snd_nxt = th->th_ack;
4927 tp->snd_cwnd = tp->t_maxseg;
4928
4929 /* Process any window updates */
4930 if (tiwin > tp->snd_wnd) {
4931 tcp_update_window(tp, thflags, th, tiwin, tlen);
4932 }
4933
4934 (void) tcp_output(tp);
4935 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
4936 tcp_cc_adjust_nonvalidated_cwnd(tp);
4937 } else {
4938 tp->snd_cwnd = tp->snd_ssthresh + tp->t_maxseg * tp->t_dupacks;
4939 }
4940 if (SEQ_GT(onxt, tp->snd_nxt)) {
4941 tp->snd_nxt = onxt;
4942 }
4943
4944 tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
4945 goto drop;
4946 } else if (ALLOW_LIMITED_TRANSMIT(tp) &&
4947 (!(SACK_ENABLED(tp)) || sack_bytes_acked > 0) &&
4948 (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)) > 0) {
4949 u_int32_t incr = (tp->t_maxseg * tp->t_dupacks);
4950
4951 /* Use Limited Transmit algorithm on the first two
4952 * duplicate acks when there is new data to transmit
4953 */
4954 tp->snd_cwnd += incr;
4955 tcpstat.tcps_limited_txt++;
4956 (void) tcp_output(tp);
4957
4958 tcp_ccdbg_trace(tp, th, TCP_CC_LIMITED_TRANSMIT);
4959
4960 /* Reset snd_cwnd back to normal */
4961 tp->snd_cwnd -= incr;
4962 }
4963 }
4964 break;
4965 }
4966 /*
4967 * If the congestion window was inflated to account
4968 * for the other side's cached packets, retract it.
4969 */
4970 if (IN_FASTRECOVERY(tp)) {
4971 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
4972 /*
4973 * If we received an ECE and entered
4974 * recovery, the subsequent ACKs should
4975 * not be treated as partial acks.
4976 */
4977 if (tp->ecn_flags & TE_INRECOVERY) {
4978 goto process_ACK;
4979 }
4980
4981 if (SACK_ENABLED(tp)) {
4982 tcp_sack_partialack(tp, th);
4983 } else {
4984 tcp_newreno_partial_ack(tp, th);
4985 }
4986 tcp_ccdbg_trace(tp, th, TCP_CC_PARTIAL_ACK);
4987 } else {
4988 if (tcp_cubic_minor_fixes) {
4989 exiting_fr = 1;
4990 }
4991 EXIT_FASTRECOVERY(tp);
4992 if (CC_ALGO(tp)->post_fr != NULL) {
4993 CC_ALGO(tp)->post_fr(tp, th);
4994 }
4995 tp->t_pipeack = 0;
4996 tcp_clear_pipeack_state(tp);
4997 tcp_ccdbg_trace(tp, th,
4998 TCP_CC_EXIT_FASTRECOVERY);
4999 }
5000 } else if ((tp->t_flagsext &
5001 (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
5002 == (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
5003 /*
5004 * If the ack acknowledges upto snd_recover or if
5005 * it acknowledges all the snd holes, exit
5006 * recovery and cancel the timer. Otherwise,
5007 * this is a partial ack. Wait for recovery timer
5008 * to enter recovery. The snd_holes have already
5009 * been updated.
5010 */
5011 if (SEQ_GEQ(th->th_ack, tp->snd_recover) ||
5012 TAILQ_EMPTY(&tp->snd_holes)) {
5013 tp->t_timer[TCPT_DELAYFR] = 0;
5014 tp->t_flagsext &= ~TF_DELAY_RECOVERY;
5015 EXIT_FASTRECOVERY(tp);
5016 tcp_ccdbg_trace(tp, th,
5017 TCP_CC_EXIT_FASTRECOVERY);
5018 }
5019 } else {
5020 /*
5021 * We were not in fast recovery. Reset the
5022 * duplicate ack counter.
5023 */
5024 tp->t_dupacks = 0;
5025 tp->t_rexmtthresh = tcprexmtthresh;
5026 tp->t_new_dupacks = 0;
5027 }
5028
5029 process_ACK:
5030 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
5031 acked = BYTES_ACKED(th, tp);
5032 tcpstat.tcps_rcvackpack++;
5033 tcpstat.tcps_rcvackbyte += acked;
5034
5035 /*
5036 * If the last packet was a retransmit, make sure
5037 * it was not spurious.
5038 *
5039 * This will also take care of congestion window
5040 * adjustment if a last packet was recovered due to a
5041 * tail loss probe.
5042 */
5043 tcp_bad_rexmt_check(tp, th, &to);
5044
5045 /* Recalculate the RTT */
5046 tcp_compute_rtt(tp, &to, th);
5047
5048 /*
5049 * If all outstanding data is acked, stop retransmit
5050 * timer and remember to restart (more output or persist).
5051 * If there is more data to be acked, restart retransmit
5052 * timer, using current (possibly backed-off) value.
5053 */
5054 TCP_RESET_REXMT_STATE(tp);
5055 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
5056 tp->t_rttmin, TCPTV_REXMTMAX,
5057 TCP_ADD_REXMTSLOP(tp));
5058 if (th->th_ack == tp->snd_max) {
5059 tp->t_timer[TCPT_REXMT] = 0;
5060 tp->t_timer[TCPT_PTO] = 0;
5061 needoutput = 1;
5062 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
5063 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
5064 tp->t_rxtcur);
5065 }
5066
5067 if ((prev_t_state == TCPS_SYN_SENT ||
5068 prev_t_state == TCPS_SYN_RECEIVED) &&
5069 tp->t_state == TCPS_ESTABLISHED) {
5070 TCP_LOG_RTT_INFO(tp);
5071 }
5072
5073 /*
5074 * If no data (only SYN) was ACK'd, skip rest of ACK
5075 * processing.
5076 */
5077 if (acked == 0) {
5078 goto step6;
5079 }
5080
5081 /*
5082 * When outgoing data has been acked (except the SYN+data), we
5083 * mark this connection as "sending good" for TFO.
5084 */
5085 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
5086 !(tp->t_tfo_flags & TFO_F_NO_SNDPROBING) &&
5087 !(th->th_flags & TH_SYN)) {
5088 tp->t_tfo_flags |= TFO_F_NO_SNDPROBING;
5089 }
5090
5091 /*
5092 * Accurate ECN uses delta_cep to determine a congestion
5093 * event if new CE counts were received.
5094 * For classic ECN, congestion event is receiving TH_ECE.
5095 */
5096 if ((tp->ecn_flags & TE_SENDIPECT)) {
5097 if (TCP_ACC_ECN_ON(tp)) {
5098 if (!IN_FASTRECOVERY(tp) && tp->t_delta_ce_packets > 0) {
5099 tcp_reduce_congestion_window(tp);
5100 tp->ecn_flags |= (TE_INRECOVERY);
5101 /* update the stats */
5102 tcpstat.tcps_ecn_ace_recv_ce += tp->t_delta_ce_packets;
5103 tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
5104 }
5105 } else if (TCP_ECN_ENABLED(tp) && (thflags & TH_ECE)) {
5106 /*
5107 * Reduce the congestion window if we haven't
5108 * done so.
5109 */
5110 if (!IN_FASTRECOVERY(tp)) {
5111 tcp_reduce_congestion_window(tp);
5112 tp->ecn_flags |= (TE_INRECOVERY | TE_SENDCWR);
5113 /*
5114 * Also note that the connection received
5115 * ECE atleast once
5116 */
5117 tp->ecn_flags |= TE_RECV_ECN_ECE;
5118 INP_INC_IFNET_STAT(inp, ecn_recv_ece);
5119 tcpstat.tcps_ecn_recv_ece++;
5120 tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
5121 }
5122 }
5123 }
5124
5125 /*
5126 * When new data is acked, open the congestion window.
5127 * The specifics of how this is achieved are up to the
5128 * congestion control algorithm in use for this connection.
5129 *
5130 * The calculations in this function assume that snd_una is
5131 * not updated yet.
5132 */
5133 if (!IN_FASTRECOVERY(tp) && !exiting_fr) {
5134 if (CC_ALGO(tp)->ack_rcvd != NULL) {
5135 CC_ALGO(tp)->ack_rcvd(tp, th);
5136 }
5137 tcp_ccdbg_trace(tp, th, TCP_CC_ACK_RCVD);
5138 }
5139 if (acked > so->so_snd.sb_cc) {
5140 tp->snd_wnd -= so->so_snd.sb_cc;
5141 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
5142 ourfinisacked = 1;
5143 } else {
5144 sbdrop(&so->so_snd, acked);
5145 tcp_sbsnd_trim(&so->so_snd);
5146 tp->snd_wnd -= acked;
5147 ourfinisacked = 0;
5148 }
5149 /* detect una wraparound */
5150 if (!IN_FASTRECOVERY(tp) &&
5151 SEQ_GT(tp->snd_una, tp->snd_recover) &&
5152 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
5153 tp->snd_recover = th->th_ack - 1;
5154 }
5155
5156 if (IN_FASTRECOVERY(tp) &&
5157 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
5158 EXIT_FASTRECOVERY(tp);
5159 }
5160
5161 tcp_update_snd_una(tp, th->th_ack);
5162
5163 if (SACK_ENABLED(tp)) {
5164 if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
5165 tp->snd_recover = tp->snd_una;
5166 }
5167 }
5168 if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
5169 tp->snd_nxt = tp->snd_una;
5170 }
5171 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
5172 !TCP_DSACK_SEQ_IN_WINDOW(tp, tp->t_dsack_lastuna,
5173 tp->snd_una)) {
5174 tcp_rxtseg_clean(tp);
5175 }
5176 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
5177 tp->t_bwmeas != NULL) {
5178 tcp_bwmeas_check(tp);
5179 }
5180
5181 write_wakeup = 1;
5182
5183 if (!SLIST_EMPTY(&tp->t_notify_ack)) {
5184 tcp_notify_acknowledgement(tp, so);
5185 }
5186
5187 switch (tp->t_state) {
5188 /*
5189 * In FIN_WAIT_1 STATE in addition to the processing
5190 * for the ESTABLISHED state if our FIN is now acknowledged
5191 * then enter FIN_WAIT_2.
5192 */
5193 case TCPS_FIN_WAIT_1:
5194 if (ourfinisacked) {
5195 /*
5196 * If we can't receive any more
5197 * data, then closing user can proceed.
5198 * Starting the TCPT_2MSL timer is contrary to the
5199 * specification, but if we don't get a FIN
5200 * we'll hang forever.
5201 */
5202 DTRACE_TCP4(state__change, void, NULL,
5203 struct inpcb *, inp,
5204 struct tcpcb *, tp,
5205 int32_t, TCPS_FIN_WAIT_2);
5206 TCP_LOG_STATE(tp, TCPS_FIN_WAIT_2);
5207 tp->t_state = TCPS_FIN_WAIT_2;
5208 if (so->so_state & SS_CANTRCVMORE) {
5209 isconnected = FALSE;
5210 isdisconnected = TRUE;
5211 tcp_set_finwait_timeout(tp);
5212 }
5213 /*
5214 * fall through and make sure we also recognize
5215 * data ACKed with the FIN
5216 */
5217 }
5218 break;
5219
5220 /*
5221 * In CLOSING STATE in addition to the processing for
5222 * the ESTABLISHED state if the ACK acknowledges our FIN
5223 * then enter the TIME-WAIT state, otherwise ignore
5224 * the segment.
5225 */
5226 case TCPS_CLOSING:
5227 if (ourfinisacked) {
5228 DTRACE_TCP4(state__change, void, NULL,
5229 struct inpcb *, inp,
5230 struct tcpcb *, tp,
5231 int32_t, TCPS_TIME_WAIT);
5232 TCP_LOG_STATE(tp, TCPS_TIME_WAIT);
5233 tp->t_state = TCPS_TIME_WAIT;
5234 tcp_canceltimers(tp);
5235 if (tp->t_flagsext & TF_NOTIMEWAIT) {
5236 tp->t_flags |= TF_CLOSING;
5237 } else {
5238 add_to_time_wait(tp, 2 * tcp_msl);
5239 }
5240 isconnected = FALSE;
5241 isdisconnected = TRUE;
5242 }
5243 break;
5244
5245 /*
5246 * In LAST_ACK, we may still be waiting for data to drain
5247 * and/or to be acked, as well as for the ack of our FIN.
5248 * If our FIN is now acknowledged, delete the TCB,
5249 * enter the closed state and return.
5250 */
5251 case TCPS_LAST_ACK:
5252 if (ourfinisacked) {
5253 tp = tcp_close(tp);
5254 goto drop;
5255 }
5256 break;
5257
5258 /*
5259 * In TIME_WAIT state the only thing that should arrive
5260 * is a retransmission of the remote FIN. Acknowledge
5261 * it and restart the finack timer.
5262 */
5263 case TCPS_TIME_WAIT:
5264 add_to_time_wait(tp, 2 * tcp_msl);
5265 goto dropafterack;
5266 }
5267
5268 /*
5269 * If there is a SACK option on the ACK and we
5270 * haven't seen any duplicate acks before, count
5271 * it as a duplicate ack even if the cumulative
5272 * ack is advanced. If the receiver delayed an
5273 * ack and detected loss afterwards, then the ack
5274 * will advance cumulative ack and will also have
5275 * a SACK option. So counting it as one duplicate
5276 * ack is ok.
5277 */
5278 if (tp->t_state == TCPS_ESTABLISHED &&
5279 SACK_ENABLED(tp) && sack_bytes_acked > 0 &&
5280 to.to_nsacks > 0 && tp->t_dupacks == 0 &&
5281 SEQ_LEQ(th->th_ack, tp->snd_una) && tlen == 0 &&
5282 !(tp->t_flagsext & TF_PKTS_REORDERED)) {
5283 tcpstat.tcps_sack_ackadv++;
5284 goto process_dupack;
5285 }
5286 }
5287
5288 step6:
5289 /*
5290 * Update window information.
5291 */
5292 if (tcp_update_window(tp, thflags, th, tiwin, tlen)) {
5293 needoutput = 1;
5294 }
5295
5296 /*
5297 * Process segments with URG.
5298 */
5299 if ((thflags & TH_URG) && th->th_urp &&
5300 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5301 /*
5302 * This is a kludge, but if we receive and accept
5303 * random urgent pointers, we'll crash in
5304 * soreceive. It's hard to imagine someone
5305 * actually wanting to send this much urgent data.
5306 */
5307 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
5308 th->th_urp = 0; /* XXX */
5309 thflags &= ~TH_URG; /* XXX */
5310 goto dodata; /* XXX */
5311 }
5312 /*
5313 * If this segment advances the known urgent pointer,
5314 * then mark the data stream. This should not happen
5315 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
5316 * a FIN has been received from the remote side.
5317 * In these states we ignore the URG.
5318 *
5319 * According to RFC961 (Assigned Protocols),
5320 * the urgent pointer points to the last octet
5321 * of urgent data. We continue, however,
5322 * to consider it to indicate the first octet
5323 * of data past the urgent section as the original
5324 * spec states (in one of two places).
5325 */
5326 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
5327 tp->rcv_up = th->th_seq + th->th_urp;
5328 so->so_oobmark = so->so_rcv.sb_cc +
5329 (tp->rcv_up - tp->rcv_nxt) - 1;
5330 if (so->so_oobmark == 0) {
5331 so->so_state |= SS_RCVATMARK;
5332 }
5333 sohasoutofband(so);
5334 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
5335 }
5336 /*
5337 * Remove out of band data so doesn't get presented to user.
5338 * This can happen independent of advancing the URG pointer,
5339 * but if two URG's are pending at once, some out-of-band
5340 * data may creep in... ick.
5341 */
5342 if (th->th_urp <= (u_int32_t)tlen
5343 #if SO_OOBINLINE
5344 && (so->so_options & SO_OOBINLINE) == 0
5345 #endif
5346 ) {
5347 tcp_pulloutofband(so, th, m,
5348 drop_hdrlen); /* hdr drop is delayed */
5349 }
5350 } else {
5351 /*
5352 * If no out of band data is expected,
5353 * pull receive urgent pointer along
5354 * with the receive window.
5355 */
5356 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) {
5357 tp->rcv_up = tp->rcv_nxt;
5358 }
5359 }
5360 dodata:
5361
5362 /* Set socket's connect or disconnect state correcly before doing data.
5363 * The following might unlock the socket if there is an upcall or a socket
5364 * filter.
5365 */
5366 if (isconnected) {
5367 soisconnected(so);
5368 } else if (isdisconnected) {
5369 soisdisconnected(so);
5370 }
5371
5372 /* Let's check the state of pcb just to make sure that it did not get closed
5373 * when we unlocked above
5374 */
5375 if (inp->inp_state == INPCB_STATE_DEAD) {
5376 /* Just drop the packet that we are processing and return */
5377 TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "INPCB_STATE_DEAD");
5378 goto drop;
5379 }
5380
5381 /*
5382 * Process the segment text, merging it into the TCP sequencing queue,
5383 * and arranging for acknowledgment of receipt if necessary.
5384 * This process logically involves adjusting tp->rcv_wnd as data
5385 * is presented to the user (this happens in tcp_usrreq.c,
5386 * case PRU_RCVD). If a FIN has already been received on this
5387 * connection then we just ignore the text.
5388 *
5389 * If we are in SYN-received state and got a valid TFO cookie, we want
5390 * to process the data.
5391 */
5392 if ((tlen || (thflags & TH_FIN)) &&
5393 TCPS_HAVERCVDFIN(tp->t_state) == 0 &&
5394 (TCPS_HAVEESTABLISHED(tp->t_state) ||
5395 (tp->t_state == TCPS_SYN_RECEIVED &&
5396 (tp->t_tfo_flags & TFO_F_COOKIE_VALID)))) {
5397 tcp_seq save_start = th->th_seq;
5398 tcp_seq save_end = th->th_seq + tlen;
5399 m_adj(m, drop_hdrlen); /* delayed header drop */
5400 /*
5401 * Insert segment which includes th into TCP reassembly queue
5402 * with control block tp. Set thflags to whether reassembly now
5403 * includes a segment with FIN. This handles the common case
5404 * inline (segment is the next to be received on an established
5405 * connection, and the queue is empty), avoiding linkage into
5406 * and removal from the queue and repetition of various
5407 * conversions.
5408 * Set DELACK for segments received in order, but ack
5409 * immediately when segments are out of order (so
5410 * fast retransmit can work).
5411 */
5412 if (th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
5413 TCP_INC_VAR(tp->t_unacksegs, segment_count);
5414
5415 /* Calculate the RTT on the receiver */
5416 tcp_compute_rcv_rtt(tp, &to, th);
5417
5418 if (DELAY_ACK(tp, th) &&
5419 ((tp->t_flags & TF_ACKNOW) == 0)) {
5420 if ((tp->t_flags & TF_DELACK) == 0) {
5421 tp->t_flags |= TF_DELACK;
5422 tp->t_timer[TCPT_DELACK] =
5423 OFFSET_FROM_START(tp, tcp_delack);
5424 }
5425 } else {
5426 tp->t_flags |= TF_ACKNOW;
5427 }
5428 tp->rcv_nxt += tlen;
5429 /* Update highest received sequence and its timestamp */
5430 if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
5431 tp->rcv_high = tp->rcv_nxt;
5432 if (to.to_flags & TOF_TS) {
5433 tp->tsv_high = to.to_tsval;
5434 }
5435 }
5436
5437 thflags = th->th_flags & TH_FIN;
5438 TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
5439 tcpstat.tcps_rcvbyte += tlen;
5440 if (nstat_collect) {
5441 INP_ADD_STAT(inp, cell, wifi, wired,
5442 rxpackets, 1);
5443 INP_ADD_STAT(inp, cell, wifi, wired,
5444 rxbytes, tlen);
5445 inp_set_activity_bitmap(inp);
5446 }
5447 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5448 if (TCP_USE_RLEDBAT(tp, so) &&
5449 tcp_cc_rledbat.data_rcvd != NULL) {
5450 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5451 }
5452
5453 so_recv_data_stat(so, m, drop_hdrlen);
5454
5455 if (isipv6) {
5456 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5457 ip6 = (struct ip6_hdr *)&saved_hdr[0];
5458 } else {
5459 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5460 ip = (struct ip *)&saved_hdr[0];
5461 }
5462 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5463
5464 if (th->th_flags & TH_PUSH) {
5465 tp->t_flagsext |= TF_LAST_IS_PSH;
5466 } else {
5467 tp->t_flagsext &= ~TF_LAST_IS_PSH;
5468 }
5469
5470 if (sbappendstream_rcvdemux(so, m)) {
5471 read_wakeup = 1;
5472 }
5473 th = &saved_tcphdr;
5474 } else {
5475 if (isipv6) {
5476 memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5477 ip6 = (struct ip6_hdr *)&saved_hdr[0];
5478 } else {
5479 memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5480 ip = (struct ip *)&saved_hdr[0];
5481 }
5482
5483 /* Update highest received sequence and its timestamp */
5484 if (SEQ_LT(tp->rcv_high, th->th_seq + tlen)) {
5485 tp->rcv_high = th->th_seq + tlen;
5486 if (to.to_flags & TOF_TS) {
5487 tp->tsv_high = to.to_tsval;
5488 }
5489 }
5490
5491 /*
5492 * Calculate the RTT on the receiver,
5493 * even if OOO segment is received.
5494 */
5495 tcp_compute_rcv_rtt(tp, &to, th);
5496
5497 if (tcp_autotune_reorder) {
5498 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5499 }
5500 if (TCP_USE_RLEDBAT(tp, so) &&
5501 tcp_cc_rledbat.data_rcvd != NULL) {
5502 tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5503 }
5504
5505 memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5506 thflags = tcp_reass(tp, th, &tlen, m, ifp, &read_wakeup);
5507 th = &saved_tcphdr;
5508 tp->t_flags |= TF_ACKNOW;
5509 }
5510
5511 if ((tlen > 0 || (th->th_flags & TH_FIN)) && SACK_ENABLED(tp)) {
5512 if (th->th_flags & TH_FIN) {
5513 save_end++;
5514 }
5515 tcp_update_sack_list(tp, save_start, save_end);
5516 }
5517
5518 tcp_adaptive_rwtimo_check(tp, tlen);
5519
5520 if (tlen > 0) {
5521 tcp_tfo_rcv_data(tp);
5522 }
5523
5524 if (tp->t_flags & TF_DELACK) {
5525 if (isipv6) {
5526 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5527 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
5528 th->th_seq, th->th_ack, th->th_win);
5529 } else {
5530 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5531 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
5532 th->th_seq, th->th_ack, th->th_win);
5533 }
5534 }
5535 } else {
5536 if ((so->so_flags & SOF_MP_SUBFLOW) && tlen == 0 &&
5537 (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN) &&
5538 (m->m_pkthdr.pkt_flags & PKTF_MPTCP)) {
5539 m_adj(m, drop_hdrlen); /* delayed header drop */
5540 /*
5541 * 0-length DATA_FIN. The rlen is actually 0. We special-case the
5542 * byte consumed by the dfin in mptcp_input and mptcp_reass_present
5543 */
5544 m->m_pkthdr.mp_rlen = 0;
5545 mptcp_input(tptomptp(tp)->mpt_mpte, m);
5546 tp->t_flags |= TF_ACKNOW;
5547 } else {
5548 m_freem(m);
5549 }
5550 thflags &= ~TH_FIN;
5551 }
5552
5553 /*
5554 * If FIN is received ACK the FIN and let the user know
5555 * that the connection is closing.
5556 */
5557 if (thflags & TH_FIN) {
5558 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5559 socantrcvmore(so);
5560 /*
5561 * If connection is half-synchronized
5562 * (ie NEEDSYN flag on) then delay ACK,
5563 * so it may be piggybacked when SYN is sent.
5564 * Otherwise, since we received a FIN then no
5565 * more input can be expected, send ACK now.
5566 */
5567 TCP_INC_VAR(tp->t_unacksegs, segment_count);
5568 tp->t_flags |= TF_ACKNOW;
5569 tp->rcv_nxt++;
5570 }
5571 switch (tp->t_state) {
5572 /*
5573 * In SYN_RECEIVED and ESTABLISHED STATES
5574 * enter the CLOSE_WAIT state.
5575 */
5576 case TCPS_SYN_RECEIVED:
5577 tp->t_starttime = tcp_now;
5578 OS_FALLTHROUGH;
5579 case TCPS_ESTABLISHED:
5580 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5581 struct tcpcb *, tp, int32_t, TCPS_CLOSE_WAIT);
5582 TCP_LOG_STATE(tp, TCPS_CLOSE_WAIT);
5583 tp->t_state = TCPS_CLOSE_WAIT;
5584 break;
5585
5586 /*
5587 * If still in FIN_WAIT_1 STATE FIN has not been acked so
5588 * enter the CLOSING state.
5589 */
5590 case TCPS_FIN_WAIT_1:
5591 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5592 struct tcpcb *, tp, int32_t, TCPS_CLOSING);
5593 TCP_LOG_STATE(tp, TCPS_CLOSING);
5594 tp->t_state = TCPS_CLOSING;
5595 break;
5596
5597 /*
5598 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5599 * starting the time-wait timer, turning off the other
5600 * standard timers.
5601 */
5602 case TCPS_FIN_WAIT_2:
5603 DTRACE_TCP4(state__change, void, NULL,
5604 struct inpcb *, inp,
5605 struct tcpcb *, tp,
5606 int32_t, TCPS_TIME_WAIT);
5607 TCP_LOG_STATE(tp, TCPS_TIME_WAIT);
5608 tp->t_state = TCPS_TIME_WAIT;
5609 tcp_canceltimers(tp);
5610 tp->t_flags |= TF_ACKNOW;
5611 if (tp->t_flagsext & TF_NOTIMEWAIT) {
5612 tp->t_flags |= TF_CLOSING;
5613 } else {
5614 add_to_time_wait(tp, 2 * tcp_msl);
5615 }
5616 soisdisconnected(so);
5617 break;
5618
5619 /*
5620 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5621 */
5622 case TCPS_TIME_WAIT:
5623 add_to_time_wait(tp, 2 * tcp_msl);
5624 break;
5625 }
5626 }
5627 #if TCPDEBUG
5628 if (so->so_options & SO_DEBUG) {
5629 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
5630 &tcp_savetcp, 0);
5631 }
5632 #endif
5633
5634 if (read_wakeup) {
5635 mptcp_handle_input(so);
5636 }
5637
5638 /*
5639 * Return any desired output.
5640 */
5641 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
5642 (void) tcp_output(tp);
5643 }
5644
5645 tcp_check_timer_state(tp);
5646
5647 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5648
5649 socket_unlock(so, 1);
5650 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5651 return;
5652
5653 dropafterack:
5654 /*
5655 * Generate an ACK dropping incoming segment if it occupies
5656 * sequence space, where the ACK reflects our state.
5657 *
5658 * We can now skip the test for the RST flag since all
5659 * paths to this code happen after packets containing
5660 * RST have been dropped.
5661 *
5662 * In the SYN-RECEIVED state, don't send an ACK unless the
5663 * segment we received passes the SYN-RECEIVED ACK test.
5664 * If it fails send a RST. This breaks the loop in the
5665 * "LAND" DoS attack, and also prevents an ACK storm
5666 * between two listening ports that have been sent forged
5667 * SYN segments, each with the source address of the other.
5668 */
5669 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
5670 (SEQ_GT(tp->snd_una, th->th_ack) ||
5671 SEQ_GT(th->th_ack, tp->snd_max))) {
5672 IF_TCP_STATINC(ifp, dospacket);
5673 goto dropwithreset;
5674 }
5675 #if TCPDEBUG
5676 if (so->so_options & SO_DEBUG) {
5677 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
5678 &tcp_savetcp, 0);
5679 }
5680 #endif
5681 m_freem(m);
5682 tp->t_flags |= TF_ACKNOW;
5683
5684 (void) tcp_output(tp);
5685
5686 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5687
5688 /* Don't need to check timer state as we should have done it during tcp_output */
5689 socket_unlock(so, 1);
5690 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5691 return;
5692 dropwithresetnosock:
5693 nosock = 1;
5694 dropwithreset:
5695 /*
5696 * Generate a RST, dropping incoming segment.
5697 * Make ACK acceptable to originator of segment.
5698 * Don't bother to respond if destination was broadcast/multicast.
5699 */
5700 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST)) {
5701 goto drop;
5702 }
5703 if (isipv6) {
5704 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
5705 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
5706 goto drop;
5707 }
5708 } else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
5709 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
5710 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
5711 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
5712 goto drop;
5713 }
5714 /* IPv6 anycast check is done at tcp6_input() */
5715
5716 #if TCPDEBUG
5717 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
5718 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
5719 &tcp_savetcp, 0);
5720 }
5721 #endif
5722 bzero(&tra, sizeof(tra));
5723 tra.ifscope = ifscope;
5724 tra.awdl_unrestricted = 1;
5725 tra.intcoproc_allowed = 1;
5726 if (thflags & TH_ACK) {
5727 /* mtod() below is safe as long as hdr dropping is delayed */
5728 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
5729 TH_RST, &tra);
5730 } else {
5731 if (thflags & TH_SYN) {
5732 tlen++;
5733 }
5734 /* mtod() below is safe as long as hdr dropping is delayed */
5735 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
5736 (tcp_seq)0, TH_RST | TH_ACK, &tra);
5737 }
5738 /* destroy temporarily created socket */
5739 if (dropsocket) {
5740 (void) soabort(so);
5741 socket_unlock(so, 1);
5742 } else if ((inp != NULL) && (nosock == 0)) {
5743 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5744
5745 socket_unlock(so, 1);
5746 }
5747 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5748 return;
5749 dropnosock:
5750 nosock = 1;
5751 drop:
5752 /*
5753 * Drop space held by incoming segment and return.
5754 */
5755 #if TCPDEBUG
5756 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
5757 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
5758 &tcp_savetcp, 0);
5759 }
5760 #endif
5761 m_freem(m);
5762 /* destroy temporarily created socket */
5763 if (dropsocket) {
5764 (void) soabort(so);
5765 socket_unlock(so, 1);
5766 } else if (nosock == 0) {
5767 tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5768
5769 socket_unlock(so, 1);
5770 }
5771 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5772 return;
5773 }
5774
5775 /*
5776 * Parse TCP options and place in tcpopt.
5777 */
5778 static void
tcp_dooptions(struct tcpcb * tp,u_char * cp,int cnt,struct tcphdr * th,struct tcpopt * to)5779 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
5780 struct tcpopt *to)
5781 {
5782 u_short mss = 0;
5783 uint8_t opt, optlen;
5784
5785 for (; cnt > 0; cnt -= optlen, cp += optlen) {
5786 opt = cp[0];
5787 if (opt == TCPOPT_EOL) {
5788 break;
5789 }
5790 if (opt == TCPOPT_NOP) {
5791 optlen = 1;
5792 } else {
5793 if (cnt < 2) {
5794 break;
5795 }
5796 optlen = cp[1];
5797 if (optlen < 2 || optlen > cnt) {
5798 break;
5799 }
5800 }
5801 switch (opt) {
5802 default:
5803 continue;
5804
5805 case TCPOPT_MAXSEG:
5806 if (optlen != TCPOLEN_MAXSEG) {
5807 continue;
5808 }
5809 if (!(th->th_flags & TH_SYN)) {
5810 continue;
5811 }
5812 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
5813 NTOHS(mss);
5814 to->to_mss = mss;
5815 to->to_flags |= TOF_MSS;
5816 break;
5817
5818 case TCPOPT_WINDOW:
5819 if (optlen != TCPOLEN_WINDOW) {
5820 continue;
5821 }
5822 if (!(th->th_flags & TH_SYN)) {
5823 continue;
5824 }
5825 to->to_flags |= TOF_SCALE;
5826 to->to_requested_s_scale = MIN(cp[2], TCP_MAX_WINSHIFT);
5827 break;
5828
5829 case TCPOPT_TIMESTAMP:
5830 if (optlen != TCPOLEN_TIMESTAMP) {
5831 continue;
5832 }
5833 to->to_flags |= TOF_TS;
5834 bcopy((char *)cp + 2,
5835 (char *)&to->to_tsval, sizeof(to->to_tsval));
5836 NTOHL(to->to_tsval);
5837 bcopy((char *)cp + 6,
5838 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
5839 NTOHL(to->to_tsecr);
5840 to->to_tsecr -= tp->t_ts_offset;
5841 /* Re-enable sending Timestamps if we received them */
5842 if (!(tp->t_flags & TF_REQ_TSTMP)) {
5843 tp->t_flags |= TF_REQ_TSTMP;
5844 }
5845 break;
5846 case TCPOPT_SACK_PERMITTED:
5847 if (optlen != TCPOLEN_SACK_PERMITTED) {
5848 continue;
5849 }
5850 if (th->th_flags & TH_SYN) {
5851 to->to_flags |= TOF_SACK;
5852 }
5853 break;
5854 case TCPOPT_SACK:
5855 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) {
5856 continue;
5857 }
5858 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
5859 to->to_sacks = cp + 2;
5860 tcpstat.tcps_sack_rcv_blocks++;
5861
5862 break;
5863 case TCPOPT_FASTOPEN:
5864 if (optlen == TCPOLEN_FASTOPEN_REQ) {
5865 if (tp->t_state != TCPS_LISTEN) {
5866 continue;
5867 }
5868
5869 to->to_flags |= TOF_TFOREQ;
5870 } else {
5871 if (optlen < TCPOLEN_FASTOPEN_REQ ||
5872 (optlen - TCPOLEN_FASTOPEN_REQ) > TFO_COOKIE_LEN_MAX ||
5873 (optlen - TCPOLEN_FASTOPEN_REQ) < TFO_COOKIE_LEN_MIN) {
5874 continue;
5875 }
5876 if (tp->t_state != TCPS_LISTEN &&
5877 tp->t_state != TCPS_SYN_SENT) {
5878 continue;
5879 }
5880
5881 to->to_flags |= TOF_TFO;
5882 to->to_tfo = cp + 1;
5883 }
5884
5885 break;
5886 #if MPTCP
5887 case TCPOPT_MULTIPATH:
5888 tcp_do_mptcp_options(tp, cp, th, to, optlen);
5889 break;
5890 #endif /* MPTCP */
5891 }
5892 }
5893 }
5894
5895 static void
tcp_finalize_options(struct tcpcb * tp,struct tcpopt * to,unsigned int ifscope)5896 tcp_finalize_options(struct tcpcb *tp, struct tcpopt *to, unsigned int ifscope)
5897 {
5898 if (to->to_flags & TOF_TS) {
5899 tp->t_flags |= TF_RCVD_TSTMP;
5900 tp->ts_recent = to->to_tsval;
5901 tp->ts_recent_age = tcp_now;
5902 }
5903 if (to->to_flags & TOF_MSS) {
5904 tcp_mss(tp, to->to_mss, ifscope);
5905 }
5906 if (SACK_ENABLED(tp)) {
5907 if (!(to->to_flags & TOF_SACK)) {
5908 tp->t_flagsext &= ~(TF_SACK_ENABLE);
5909 } else {
5910 tp->t_flags |= TF_SACK_PERMIT;
5911 }
5912 }
5913 if (to->to_flags & TOF_SCALE) {
5914 tp->t_flags |= TF_RCVD_SCALE;
5915 tp->requested_s_scale = to->to_requested_s_scale;
5916
5917 /* Re-enable window scaling, if the option is received */
5918 if (tp->request_r_scale > 0) {
5919 tp->t_flags |= TF_REQ_SCALE;
5920 }
5921 }
5922 }
5923
5924 /*
5925 * Pull out of band byte out of a segment so
5926 * it doesn't appear in the user's data queue.
5927 * It is still reflected in the segment length for
5928 * sequencing purposes.
5929 *
5930 * @param off delayed to be droped hdrlen
5931 */
5932 static void
tcp_pulloutofband(struct socket * so,struct tcphdr * th,struct mbuf * m,int off)5933 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
5934 {
5935 int cnt = off + th->th_urp - 1;
5936
5937 while (cnt >= 0) {
5938 if (m->m_len > cnt) {
5939 char *cp = mtod(m, caddr_t) + cnt;
5940 struct tcpcb *tp = sototcpcb(so);
5941
5942 tp->t_iobc = *cp;
5943 tp->t_oobflags |= TCPOOB_HAVEDATA;
5944 bcopy(cp + 1, cp, (unsigned)(m->m_len - cnt - 1));
5945 m->m_len--;
5946 if (m->m_flags & M_PKTHDR) {
5947 m->m_pkthdr.len--;
5948 }
5949 return;
5950 }
5951 cnt -= m->m_len;
5952 m = m->m_next;
5953 if (m == 0) {
5954 break;
5955 }
5956 }
5957 panic("tcp_pulloutofband");
5958 }
5959
5960 uint32_t
get_base_rtt(struct tcpcb * tp)5961 get_base_rtt(struct tcpcb *tp)
5962 {
5963 struct rtentry *rt = tp->t_inpcb->inp_route.ro_rt;
5964 return (rt == NULL) ? 0 : rt->rtt_min;
5965 }
5966
5967 static void
update_curr_rtt(struct tcpcb * tp,uint32_t rtt)5968 update_curr_rtt(struct tcpcb * tp, uint32_t rtt)
5969 {
5970 tp->curr_rtt_index = (tp->curr_rtt_index + 1) % NCURR_RTT_HIST;
5971 tp->curr_rtt_hist[tp->curr_rtt_index] = rtt;
5972
5973 /* forget the old value and update minimum */
5974 tp->curr_rtt_min = 0;
5975 for (int i = 0; i < NCURR_RTT_HIST; ++i) {
5976 if (tp->curr_rtt_hist[i] != 0 && (tp->curr_rtt_min == 0 ||
5977 tp->curr_rtt_hist[i] < tp->curr_rtt_min)) {
5978 tp->curr_rtt_min = tp->curr_rtt_hist[i];
5979 }
5980 }
5981 }
5982
5983 /* Each value of RTT base represents the minimum RTT seen in a minute.
5984 * We keep upto N_RTT_BASE minutes worth of history.
5985 */
5986 void
update_base_rtt(struct tcpcb * tp,uint32_t rtt)5987 update_base_rtt(struct tcpcb *tp, uint32_t rtt)
5988 {
5989 u_int32_t base_rtt, i;
5990 struct rtentry *rt;
5991
5992 if ((rt = tp->t_inpcb->inp_route.ro_rt) == NULL) {
5993 return;
5994 }
5995 if (rt->rtt_expire_ts == 0) {
5996 RT_LOCK_SPIN(rt);
5997 if (rt->rtt_expire_ts != 0) {
5998 RT_UNLOCK(rt);
5999 goto update;
6000 }
6001 rt->rtt_expire_ts = tcp_now;
6002 rt->rtt_index = 0;
6003 rt->rtt_hist[0] = rtt;
6004 rt->rtt_min = rtt;
6005 RT_UNLOCK(rt);
6006
6007 tp->curr_rtt_index = 0;
6008 tp->curr_rtt_hist[0] = rtt;
6009 tp->curr_rtt_min = rtt;
6010 return;
6011 }
6012 update:
6013 #if TRAFFIC_MGT
6014 /*
6015 * If the recv side is being throttled, check if the
6016 * current RTT is closer to the base RTT seen in
6017 * first (recent) two slots. If so, unthrottle the stream.
6018 */
6019 if ((tp->t_flagsext & TF_RECV_THROTTLE) &&
6020 (int)(tcp_now - tp->t_recv_throttle_ts) >= TCP_RECV_THROTTLE_WIN) {
6021 base_rtt = rt->rtt_min;
6022 if (tp->t_rttcur <= (base_rtt + target_qdelay)) {
6023 tp->t_flagsext &= ~TF_RECV_THROTTLE;
6024 tp->t_recv_throttle_ts = 0;
6025 }
6026 }
6027 #endif /* TRAFFIC_MGT */
6028
6029 /* Update the next current RTT sample */
6030 update_curr_rtt(tp, rtt);
6031
6032 if ((int)(tcp_now - rt->rtt_expire_ts) >=
6033 TCP_RTT_HISTORY_EXPIRE_TIME) {
6034 RT_LOCK_SPIN(rt);
6035 /* check the condition again to avoid race */
6036 if ((int)(tcp_now - rt->rtt_expire_ts) >=
6037 TCP_RTT_HISTORY_EXPIRE_TIME) {
6038 /* Set the base rtt to 0 for idle periods */
6039 uint32_t times = MIN((tcp_now - rt->rtt_expire_ts) /
6040 TCP_RTT_HISTORY_EXPIRE_TIME, NRTT_HIST + 1);
6041
6042 for (i = rt->rtt_index + 1; i < rt->rtt_index + times; i++) {
6043 rt->rtt_hist[i % NRTT_HIST] = 0;
6044 }
6045
6046 rt->rtt_index = i % NRTT_HIST;
6047 rt->rtt_hist[rt->rtt_index] = rtt;
6048 rt->rtt_expire_ts = tcp_now;
6049 } else {
6050 rt->rtt_hist[rt->rtt_index] =
6051 min(rt->rtt_hist[rt->rtt_index], rtt);
6052 }
6053 /* forget the old value and update minimum */
6054 rt->rtt_min = 0;
6055 for (i = 0; i < NRTT_HIST; ++i) {
6056 if (rt->rtt_hist[i] != 0 &&
6057 (rt->rtt_min == 0 ||
6058 rt->rtt_hist[i] < rt->rtt_min)) {
6059 rt->rtt_min = rt->rtt_hist[i];
6060 }
6061 }
6062 RT_UNLOCK(rt);
6063 } else {
6064 rt->rtt_hist[rt->rtt_index] =
6065 min(rt->rtt_hist[rt->rtt_index], rtt);
6066 if (rt->rtt_min == 0) {
6067 rt->rtt_min = rtt;
6068 } else {
6069 rt->rtt_min = min(rt->rtt_min, rtt);
6070 }
6071 }
6072 }
6073
6074 /*
6075 * If we have a timestamp reply, update smoothed RTT. If no timestamp is
6076 * present but transmit timer is running and timed sequence number was
6077 * acked, update smoothed RTT.
6078 *
6079 * If timestamps are supported, a receiver can update RTT even if
6080 * there is no outstanding data.
6081 *
6082 * Some boxes send broken timestamp replies during the SYN+ACK phase,
6083 * ignore timestamps of 0or we could calculate a huge RTT and blow up
6084 * the retransmit timer.
6085 */
6086 static void
tcp_compute_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)6087 tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
6088 {
6089 int rtt = 0;
6090 VERIFY(to != NULL && th != NULL);
6091 if (tp->t_rtttime != 0 && SEQ_GT(th->th_ack, tp->t_rtseq)) {
6092 u_int32_t pipe_ack_val;
6093 rtt = tcp_now - tp->t_rtttime;
6094 if (rtt == 0) {
6095 /*
6096 * Make adjustment for sub ms RTT when
6097 * timestamps are not used.
6098 */
6099 rtt = 1;
6100 }
6101 /*
6102 * Compute pipe ack -- the amount of data acknowledged
6103 * in the last RTT -- only works for sender
6104 */
6105 if (SEQ_GT(th->th_ack, tp->t_pipeack_lastuna)) {
6106 pipe_ack_val = th->th_ack - tp->t_pipeack_lastuna;
6107 /* Update the sample */
6108 tp->t_pipeack_sample[tp->t_pipeack_ind++] =
6109 pipe_ack_val;
6110 tp->t_pipeack_ind %= TCP_PIPEACK_SAMPLE_COUNT;
6111
6112 /* Compute the max of the pipeack samples */
6113 pipe_ack_val = tcp_get_max_pipeack(tp);
6114 tp->t_pipeack = (pipe_ack_val >
6115 tcp_initial_cwnd(tp)) ?
6116 pipe_ack_val : 0;
6117 }
6118 /* start another measurement */
6119 tp->t_rtttime = 0;
6120 }
6121 if (((to->to_flags & TOF_TS) != 0) &&
6122 (to->to_tsecr != 0) &&
6123 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
6124 tcp_xmit_timer(tp, (tcp_now - to->to_tsecr),
6125 to->to_tsecr, th->th_ack);
6126 } else if (rtt > 0) {
6127 tcp_xmit_timer(tp, rtt, 0, th->th_ack);
6128 }
6129 }
6130
6131 static void
tcp_compute_rcv_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)6132 tcp_compute_rcv_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
6133 {
6134 uint32_t rtt = 0, delta = 0;
6135 VERIFY(to != NULL && th != NULL);
6136
6137 /* Calculate RTT */
6138 if (((to->to_flags & TOF_TS) != 0) && (to->to_tsecr != 0) &&
6139 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
6140 /* Timestamp is supported */
6141 rtt = tcp_now - to->to_tsecr;
6142 if (rtt == 0) {
6143 /* Make adjustment for sub ms RTT */
6144 rtt = 1;
6145 }
6146 } else if ((to->to_flags & TOF_TS) == 0) {
6147 /*
6148 * Timestamp is not supported, 1RTT is roughly
6149 * the time to receive one full window of data
6150 * Currently, RTT calculated this way is only used
6151 * for auto-tuning.
6152 */
6153 if (tp->rcv_rtt_est_ts != 0) {
6154 if (SEQ_LT(tp->rcv_nxt, tp->rcv_rtt_est_seq)) {
6155 /* Haven't received a full window yet */
6156 return;
6157 } else {
6158 rtt = tcp_now - tp->rcv_rtt_est_ts;
6159 if (rtt == 0) {
6160 /* Make adjustment for sub ms RTT */
6161 rtt = 1;
6162 }
6163 }
6164 } else {
6165 /* Use default value when no RTT measurement */
6166 rtt = TCPTV_RCVNOTS_QUANTUM;
6167 }
6168 /* Restart the measurement */
6169 tp->rcv_rtt_est_ts = tcp_now;
6170 tp->rcv_rtt_est_seq = tp->rcv_nxt + tp->rcv_wnd;
6171 }
6172
6173 /* Update receiver's SRTT */
6174 if (tp->rcv_srtt != 0) {
6175 /*
6176 * Use the smoothed rtt formula,
6177 * (srtt = rtt/8 + srtt*7/8) in fixed point
6178 */
6179 delta = (rtt << TCP_DELTA_SHIFT)
6180 - (tp->rcv_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6181
6182 if ((tp->rcv_srtt += delta) <= 0) {
6183 tp->rcv_srtt = 1;
6184 }
6185 } else {
6186 /* No previous measurement */
6187 tp->rcv_srtt = rtt << TCP_RTT_SHIFT;
6188 }
6189
6190 /*
6191 * For current RTT, base RTT and current RTT over k samples,
6192 * we are using the same state for both sender and receiver
6193 * as the most recent sample is always updated before any
6194 * other processing, i.e. the sender will not end up with
6195 * a high RTT due to the receiver.
6196 */
6197 tp->t_rttcur = rtt;
6198 update_base_rtt(tp, rtt);
6199 }
6200
6201 /*
6202 * Collect new round-trip time estimate and update averages and
6203 * current timeout.
6204 */
6205 static void
tcp_xmit_timer(struct tcpcb * tp,int rtt,u_int32_t tsecr,tcp_seq th_ack)6206 tcp_xmit_timer(struct tcpcb *tp, int rtt,
6207 u_int32_t tsecr, tcp_seq th_ack)
6208 {
6209 VERIFY(rtt >= 0);
6210 int delta;
6211 int old_srtt = tp->t_srtt;
6212 int old_rttvar = tp->t_rttvar;
6213 bool log_rtt = false;
6214
6215 if (rtt == 0) {
6216 /*
6217 * As rtt has millisecond precision,
6218 * make adjustment for sub ms RTT
6219 */
6220 rtt = 1;
6221 }
6222
6223 if (rtt > 4 * TCPTV_MSL) {
6224 TCP_LOG(tp, "%s: rtt is %d - maxing it at 4 x MSL\n", __func__, rtt);
6225 /*
6226 * We compute RTT either based on the time-to-ACK a packet,
6227 * if TSval is disabled or based on the TSecr value.
6228 * If there is a middlebox messing up the TSecr value, we can
6229 * end up having HUGE rtt values, causing all kinds of problems.
6230 * Let's protect against this by capping RTT to 4*MSL
6231 * (60seconds).
6232 */
6233 rtt = 4 * TCPTV_MSL;
6234 }
6235
6236 /*
6237 * On AWDL interface, the initial RTT measurement on SYN
6238 * can be wrong due to peer caching. Avoid the first RTT
6239 * measurement as it might skew up the RTO.
6240 * <rdar://problem/28739046>
6241 */
6242 if (tp->t_inpcb->inp_last_outifp != NULL &&
6243 (tp->t_inpcb->inp_last_outifp->if_eflags & IFEF_AWDL) &&
6244 th_ack == tp->iss + 1) {
6245 return;
6246 }
6247
6248 if (tp->t_flagsext & TF_RECOMPUTE_RTT) {
6249 if (SEQ_GT(th_ack, tp->snd_una) &&
6250 SEQ_LEQ(th_ack, tp->snd_max) &&
6251 (tsecr == 0 ||
6252 TSTMP_GEQ(tsecr, tp->t_badrexmt_time))) {
6253 /*
6254 * We received a new ACK after a
6255 * spurious timeout. Adapt retransmission
6256 * timer as described in rfc 4015.
6257 */
6258 tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
6259 tp->t_badrexmt_time = 0;
6260 tp->t_srtt = max(tp->t_srtt_prev, rtt);
6261 tp->t_srtt = tp->t_srtt << TCP_RTT_SHIFT;
6262 tp->t_rttvar = max(tp->t_rttvar_prev, (rtt >> 1));
6263 tp->t_rttvar = tp->t_rttvar << TCP_RTTVAR_SHIFT;
6264
6265 if (tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6266 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6267 }
6268
6269 goto compute_rto;
6270 } else {
6271 return;
6272 }
6273 }
6274
6275 tcpstat.tcps_rttupdated++;
6276 tp->t_rttupdated++;
6277
6278 tp->t_rttcur = rtt;
6279 update_base_rtt(tp, rtt);
6280
6281 if (tp->t_srtt != 0) {
6282 /*
6283 * srtt is stored as fixed point with 5 bits after the
6284 * binary point (i.e., scaled by 32). The following magic
6285 * is equivalent to the smoothing algorithm in rfc793 with
6286 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
6287 * point).
6288 *
6289 * Freebsd adjusts rtt to origin 0 by subtracting 1
6290 * from the provided rtt value. This was required because
6291 * of the way t_rtttime was initiailised to 1 before.
6292 * Since we changed t_rtttime to be based on
6293 * tcp_now, this extra adjustment is not needed.
6294 */
6295 delta = (rtt << TCP_DELTA_SHIFT)
6296 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6297
6298 if ((tp->t_srtt += delta) <= 0) {
6299 tp->t_srtt = 1;
6300 }
6301
6302 /*
6303 * We accumulate a smoothed rtt variance (actually, a
6304 * smoothed mean difference), then set the retransmit
6305 * timer to smoothed rtt + 4 times the smoothed variance.
6306 * rttvar is stored as fixed point with 4 bits after the
6307 * binary point (scaled by 16). The following is
6308 * equivalent to rfc793 smoothing with an alpha of .75
6309 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
6310 * rfc793's wired-in beta.
6311 */
6312 if (delta < 0) {
6313 delta = -delta;
6314 }
6315 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6316 if ((tp->t_rttvar += delta) <= 0) {
6317 tp->t_rttvar = 1;
6318 }
6319 if (tp->t_rttbest == 0 ||
6320 tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6321 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6322 }
6323 } else {
6324 /*
6325 * No rtt measurement yet - use the unsmoothed rtt.
6326 * Set the variance to half the rtt (so our first
6327 * retransmit happens at 3*rtt).
6328 */
6329 tp->t_srtt = rtt << TCP_RTT_SHIFT;
6330 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
6331 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6332
6333 /* Initialize the receive SRTT */
6334 if (tp->rcv_srtt == 0) {
6335 tp->rcv_srtt = tp->t_srtt;
6336 }
6337 }
6338
6339 compute_rto:
6340 nstat_route_rtt(tp->t_inpcb->inp_route.ro_rt, tp->t_srtt,
6341 tp->t_rttvar);
6342
6343 /*
6344 * the retransmit should happen at rtt + 4 * rttvar.
6345 * Because of the way we do the smoothing, srtt and rttvar
6346 * will each average +1/2 tick of bias. When we compute
6347 * the retransmit timer, we want 1/2 tick of rounding and
6348 * 1 extra tick because of +-1/2 tick uncertainty in the
6349 * firing of the timer. The bias will give us exactly the
6350 * 1.5 tick we need. But, because the bias is
6351 * statistical, we have to test that we don't drop below
6352 * the minimum feasible timer (which is 2 ticks).
6353 */
6354 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6355 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX,
6356 TCP_ADD_REXMTSLOP(tp));
6357
6358 /*
6359 * We received an ack for a packet that wasn't retransmitted;
6360 * it is probably safe to discard any error indications we've
6361 * received recently. This isn't quite right, but close enough
6362 * for now (a route might have failed after we sent a segment,
6363 * and the return path might not be symmetrical).
6364 */
6365 tp->t_softerror = 0;
6366
6367 if (log_rtt) {
6368 TCP_LOG_RTT_INFO(tp);
6369 }
6370
6371 TCP_LOG_RTT_CHANGE(tp, old_srtt, old_rttvar);
6372 }
6373
6374 static inline unsigned int
tcp_maxmtu(struct rtentry * rt)6375 tcp_maxmtu(struct rtentry *rt)
6376 {
6377 unsigned int maxmtu;
6378 int interface_mtu = 0;
6379
6380 RT_LOCK_ASSERT_HELD(rt);
6381 interface_mtu = rt->rt_ifp->if_mtu;
6382
6383 if (rt_key(rt)->sa_family == AF_INET &&
6384 INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
6385 interface_mtu = IN6_LINKMTU(rt->rt_ifp);
6386 /* Further adjust the size for CLAT46 expansion */
6387 interface_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
6388 }
6389
6390 if (rt->rt_rmx.rmx_mtu == 0) {
6391 maxmtu = interface_mtu;
6392 } else {
6393 maxmtu = MIN(rt->rt_rmx.rmx_mtu, interface_mtu);
6394 }
6395
6396 return maxmtu;
6397 }
6398
6399 static inline unsigned int
tcp_maxmtu6(struct rtentry * rt)6400 tcp_maxmtu6(struct rtentry *rt)
6401 {
6402 unsigned int maxmtu;
6403 struct nd_ifinfo *ndi = NULL;
6404
6405 RT_LOCK_ASSERT_HELD(rt);
6406 if ((ndi = ND_IFINFO(rt->rt_ifp)) != NULL && !ndi->initialized) {
6407 ndi = NULL;
6408 }
6409 if (ndi != NULL) {
6410 lck_mtx_lock(&ndi->lock);
6411 }
6412 if (rt->rt_rmx.rmx_mtu == 0) {
6413 maxmtu = IN6_LINKMTU(rt->rt_ifp);
6414 } else {
6415 maxmtu = MIN(rt->rt_rmx.rmx_mtu, IN6_LINKMTU(rt->rt_ifp));
6416 }
6417 if (ndi != NULL) {
6418 lck_mtx_unlock(&ndi->lock);
6419 }
6420
6421 return maxmtu;
6422 }
6423
6424 unsigned int
get_maxmtu(struct rtentry * rt)6425 get_maxmtu(struct rtentry *rt)
6426 {
6427 unsigned int maxmtu = 0;
6428
6429 RT_LOCK_ASSERT_NOTHELD(rt);
6430
6431 RT_LOCK(rt);
6432
6433 if (rt_key(rt)->sa_family == AF_INET6) {
6434 maxmtu = tcp_maxmtu6(rt);
6435 } else {
6436 maxmtu = tcp_maxmtu(rt);
6437 }
6438
6439 RT_UNLOCK(rt);
6440
6441 return maxmtu;
6442 }
6443
6444 /*
6445 * Determine a reasonable value for maxseg size.
6446 * If the route is known, check route for mtu.
6447 * If none, use an mss that can be handled on the outgoing
6448 * interface without forcing IP to fragment; if bigger than
6449 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
6450 * to utilize large mbufs. If no route is found, route has no mtu,
6451 * or the destination isn't local, use a default, hopefully conservative
6452 * size (usually 512 or the default IP max size, but no more than the mtu
6453 * of the interface), as we can't discover anything about intervening
6454 * gateways or networks. We also initialize the congestion/slow start
6455 * window. While looking at the routing entry, we also initialize
6456 * other path-dependent parameters from pre-set or cached values
6457 * in the routing entry.
6458 *
6459 * Also take into account the space needed for options that we
6460 * send regularly. Make maxseg shorter by that amount to assure
6461 * that we can send maxseg amount of data even when the options
6462 * are present. Store the upper limit of the length of options plus
6463 * data in maxopd.
6464 *
6465 * NOTE that this routine is only called when we process an incoming
6466 * segment, for outgoing segments only tcp_mssopt is called.
6467 *
6468 */
6469 void
tcp_mss(struct tcpcb * tp,int offer,unsigned int input_ifscope)6470 tcp_mss(struct tcpcb *tp, int offer, unsigned int input_ifscope)
6471 {
6472 struct rtentry *rt;
6473 struct ifnet *ifp;
6474 int rtt, mss;
6475 uint32_t bufsize;
6476 struct inpcb *inp;
6477 struct socket *so;
6478 int origoffer = offer;
6479 uint32_t sb_max_corrected;
6480 int isnetlocal = 0;
6481 int isipv6;
6482 int min_protoh;
6483
6484 inp = tp->t_inpcb;
6485
6486 so = inp->inp_socket;
6487 /*
6488 * Nothing left to send after the socket is defunct or TCP is in the closed state
6489 */
6490 if ((so->so_state & SS_DEFUNCT) || tp->t_state == TCPS_CLOSED) {
6491 return;
6492 }
6493
6494 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
6495 min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
6496 : sizeof(struct tcpiphdr);
6497
6498 if (isipv6) {
6499 rt = tcp_rtlookup6(inp, input_ifscope);
6500 } else {
6501 rt = tcp_rtlookup(inp, input_ifscope);
6502 }
6503 isnetlocal = (tp->t_flags & TF_LOCAL);
6504
6505 if (rt == NULL) {
6506 tp->t_maxopd = tp->t_maxseg = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6507 return;
6508 }
6509 ifp = rt->rt_ifp;
6510 /*
6511 * Slower link window correction:
6512 * If a value is specificied for slowlink_wsize use it for
6513 * PPP links believed to be on a serial modem (speed <128Kbps).
6514 * Excludes 9600bps as it is the default value adversized
6515 * by pseudo-devices over ppp.
6516 */
6517 if (ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
6518 ifp->if_baudrate > 9600 && ifp->if_baudrate <= 128000) {
6519 tp->t_flags |= TF_SLOWLINK;
6520 }
6521
6522 /*
6523 * Offer == -1 means that we didn't receive SYN yet. Use 0 then.
6524 */
6525 if (offer == -1) {
6526 offer = rt->rt_rmx.rmx_filler[0];
6527 }
6528 /*
6529 * Offer == 0 means that there was no MSS on the SYN segment,
6530 * in this case we use tcp_mssdflt.
6531 */
6532 if (offer == 0) {
6533 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6534 } else {
6535 /*
6536 * Prevent DoS attack with too small MSS. Round up
6537 * to at least minmss.
6538 */
6539 offer = max(offer, tcp_minmss);
6540 /*
6541 * Sanity check: make sure that maxopd will be large
6542 * enough to allow some data on segments even is the
6543 * all the option space is used (40bytes). Otherwise
6544 * funny things may happen in tcp_output.
6545 */
6546 offer = max(offer, 64);
6547 }
6548 rt->rt_rmx.rmx_filler[0] = offer;
6549
6550 /*
6551 * While we're here, check if there's an initial rtt
6552 * or rttvar. Convert from the route-table units
6553 * to scaled multiples of the slow timeout timer.
6554 */
6555 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt) != 0) {
6556 tcp_getrt_rtt(tp, rt);
6557 } else {
6558 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCPTV_REXMTMIN;
6559 }
6560
6561 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
6562
6563 #if NECP
6564 // At this point, the mss is just the MTU. Adjust if necessary.
6565 mss = necp_socket_get_effective_mtu(inp, mss);
6566 #endif /* NECP */
6567
6568 mss -= min_protoh;
6569
6570 if (rt->rt_rmx.rmx_mtu == 0) {
6571 if (isipv6) {
6572 if (!isnetlocal) {
6573 mss = min(mss, tcp_v6mssdflt);
6574 }
6575 } else if (!isnetlocal) {
6576 mss = min(mss, tcp_mssdflt);
6577 }
6578 }
6579
6580 mss = min(mss, offer);
6581 /*
6582 * maxopd stores the maximum length of data AND options
6583 * in a segment; maxseg is the amount of data in a normal
6584 * segment. We need to store this value (maxopd) apart
6585 * from maxseg, because now every segment carries options
6586 * and thus we normally have somewhat less data in segments.
6587 */
6588 tp->t_maxopd = mss;
6589
6590 /*
6591 * origoffer==-1 indicates, that no segments were received yet.
6592 * In this case we just guess.
6593 */
6594 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
6595 (origoffer == -1 ||
6596 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)) {
6597 mss -= TCPOLEN_TSTAMP_APPA;
6598 }
6599
6600 #if MPTCP
6601 mss -= mptcp_adj_mss(tp, FALSE);
6602 #endif /* MPTCP */
6603 tp->t_maxseg = mss;
6604
6605 /*
6606 * Calculate corrected value for sb_max; ensure to upgrade the
6607 * numerator for large sb_max values else it will overflow.
6608 */
6609 sb_max_corrected = (sb_max * (u_int64_t)MCLBYTES) / (MSIZE + MCLBYTES);
6610
6611 /*
6612 * If there's a pipesize (ie loopback), change the socket
6613 * buffer to that size only if it's bigger than the current
6614 * sockbuf size. Make the socket buffers an integral
6615 * number of mss units; if the mss is larger than
6616 * the socket buffer, decrease the mss.
6617 */
6618 #if RTV_SPIPE
6619 bufsize = rt->rt_rmx.rmx_sendpipe;
6620 if (bufsize < so->so_snd.sb_hiwat)
6621 #endif
6622 bufsize = so->so_snd.sb_hiwat;
6623 if (bufsize < mss) {
6624 mss = bufsize;
6625 } else {
6626 bufsize = (((bufsize + mss - 1) / mss) * mss);
6627 if (bufsize > sb_max_corrected) {
6628 bufsize = sb_max_corrected;
6629 }
6630 (void)sbreserve(&so->so_snd, bufsize);
6631 }
6632 tp->t_maxseg = mss;
6633
6634 ASSERT(tp->t_maxseg);
6635
6636 /*
6637 * Update MSS using recommendation from link status report. This is
6638 * temporary
6639 */
6640 tcp_update_mss_locked(so, ifp);
6641
6642 #if RTV_RPIPE
6643 bufsize = rt->rt_rmx.rmx_recvpipe;
6644 if (bufsize < so->so_rcv.sb_hiwat)
6645 #endif
6646 bufsize = so->so_rcv.sb_hiwat;
6647 if (bufsize > mss) {
6648 bufsize = (((bufsize + mss - 1) / mss) * mss);
6649 if (bufsize > sb_max_corrected) {
6650 bufsize = sb_max_corrected;
6651 }
6652 (void)sbreserve(&so->so_rcv, bufsize);
6653 }
6654
6655 set_tcp_stream_priority(so);
6656
6657 if (rt->rt_rmx.rmx_ssthresh) {
6658 /*
6659 * There's some sort of gateway or interface
6660 * buffer limit on the path. Use this to set
6661 * slow-start threshold, but set the threshold to
6662 * no less than 2*mss.
6663 */
6664 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
6665 tcpstat.tcps_usedssthresh++;
6666 } else {
6667 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
6668 }
6669
6670 /*
6671 * Set the slow-start flight size depending on whether this
6672 * is a local network or not.
6673 */
6674 if (CC_ALGO(tp)->cwnd_init != NULL) {
6675 CC_ALGO(tp)->cwnd_init(tp);
6676 }
6677
6678 tcp_ccdbg_trace(tp, NULL, TCP_CC_CWND_INIT);
6679
6680 if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.rwnd_init != NULL) {
6681 tcp_cc_rledbat.rwnd_init(tp);
6682 }
6683
6684 /* Route locked during lookup above */
6685 RT_UNLOCK(rt);
6686 }
6687
6688 /*
6689 * Determine the MSS option to send on an outgoing SYN.
6690 */
6691 int
tcp_mssopt(struct tcpcb * tp)6692 tcp_mssopt(struct tcpcb *tp)
6693 {
6694 struct rtentry *rt;
6695 int mss;
6696 int isipv6;
6697 int min_protoh;
6698
6699 isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
6700 min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
6701 : sizeof(struct tcpiphdr);
6702
6703 if (isipv6) {
6704 rt = tcp_rtlookup6(tp->t_inpcb, IFSCOPE_NONE);
6705 } else {
6706 rt = tcp_rtlookup(tp->t_inpcb, IFSCOPE_NONE);
6707 }
6708 if (rt == NULL) {
6709 return isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6710 }
6711 /*
6712 * Slower link window correction:
6713 * If a value is specificied for slowlink_wsize use it for PPP links
6714 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
6715 * it is the default value adversized by pseudo-devices over ppp.
6716 */
6717 if (rt->rt_ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
6718 rt->rt_ifp->if_baudrate > 9600 && rt->rt_ifp->if_baudrate <= 128000) {
6719 tp->t_flags |= TF_SLOWLINK;
6720 }
6721
6722 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
6723 /* Route locked during lookup above */
6724 RT_UNLOCK(rt);
6725
6726 #if NECP
6727 // At this point, the mss is just the MTU. Adjust if necessary.
6728 mss = necp_socket_get_effective_mtu(tp->t_inpcb, mss);
6729 #endif /* NECP */
6730
6731 return mss - min_protoh;
6732 }
6733
6734 /*
6735 * On a partial ack arrives, force the retransmission of the
6736 * next unacknowledged segment. Do not clear tp->t_dupacks.
6737 * By setting snd_nxt to th_ack, this forces retransmission timer to
6738 * be started again.
6739 */
6740 static void
tcp_newreno_partial_ack(struct tcpcb * tp,struct tcphdr * th)6741 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
6742 {
6743 tcp_seq onxt = tp->snd_nxt;
6744 u_int32_t ocwnd = tp->snd_cwnd;
6745 tp->t_timer[TCPT_REXMT] = 0;
6746 tp->t_timer[TCPT_PTO] = 0;
6747 tp->t_rtttime = 0;
6748 tp->snd_nxt = th->th_ack;
6749 /*
6750 * Set snd_cwnd to one segment beyond acknowledged offset
6751 * (tp->snd_una has not yet been updated when this function
6752 * is called)
6753 */
6754 tp->snd_cwnd = tp->t_maxseg + BYTES_ACKED(th, tp);
6755 (void) tcp_output(tp);
6756 tp->snd_cwnd = ocwnd;
6757 if (SEQ_GT(onxt, tp->snd_nxt)) {
6758 tp->snd_nxt = onxt;
6759 }
6760 /*
6761 * Partial window deflation. Relies on fact that tp->snd_una
6762 * not updated yet.
6763 */
6764 if (tp->snd_cwnd > BYTES_ACKED(th, tp)) {
6765 tp->snd_cwnd -= BYTES_ACKED(th, tp);
6766 } else {
6767 tp->snd_cwnd = 0;
6768 }
6769 tp->snd_cwnd += tp->t_maxseg;
6770 }
6771
6772 /*
6773 * Drop a random TCP connection that hasn't been serviced yet and
6774 * is eligible for discard. There is a one in qlen chance that
6775 * we will return a null, saying that there are no dropable
6776 * requests. In this case, the protocol specific code should drop
6777 * the new request. This insures fairness.
6778 *
6779 * The listening TCP socket "head" must be locked
6780 */
6781 static int
tcp_dropdropablreq(struct socket * head)6782 tcp_dropdropablreq(struct socket *head)
6783 {
6784 struct socket *so, *sonext;
6785 unsigned int j, qlen;
6786 static uint32_t rnd = 0;
6787 static uint64_t old_runtime;
6788 static unsigned int cur_cnt, old_cnt;
6789 uint64_t now_sec, i;
6790 struct inpcb *inp = NULL;
6791 struct tcpcb *tp;
6792
6793 if ((head->so_options & SO_ACCEPTCONN) == 0) {
6794 return 0;
6795 }
6796
6797 if (TAILQ_EMPTY(&head->so_incomp)) {
6798 return 0;
6799 }
6800
6801 so_acquire_accept_list(head, NULL);
6802 socket_unlock(head, 0);
6803
6804 /*
6805 * Check if there is any socket in the incomp queue
6806 * that is closed because of a reset from the peer and is
6807 * waiting to be garbage collected. If so, pick that as
6808 * the victim
6809 */
6810 TAILQ_FOREACH_SAFE(so, &head->so_incomp, so_list, sonext) {
6811 inp = sotoinpcb(so);
6812 tp = intotcpcb(inp);
6813 if (tp != NULL && tp->t_state == TCPS_CLOSED &&
6814 so->so_head != NULL &&
6815 (so->so_state & (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) ==
6816 (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) {
6817 /*
6818 * The listen socket is already locked but we
6819 * can lock this socket here without lock ordering
6820 * issues because it is in the incomp queue and
6821 * is not visible to others.
6822 */
6823 if (socket_try_lock(so)) {
6824 so->so_usecount++;
6825 goto found_victim;
6826 } else {
6827 continue;
6828 }
6829 }
6830 }
6831
6832 so = TAILQ_FIRST(&head->so_incomp);
6833
6834 now_sec = net_uptime();
6835 if ((i = (now_sec - old_runtime)) != 0) {
6836 old_runtime = now_sec;
6837 old_cnt = cur_cnt / i;
6838 cur_cnt = 0;
6839 }
6840
6841 qlen = head->so_incqlen;
6842 if (rnd == 0) {
6843 rnd = RandomULong();
6844 }
6845
6846 if (++cur_cnt > qlen || old_cnt > qlen) {
6847 rnd = (314159 * rnd + 66329) & 0xffff;
6848 j = ((qlen + 1) * rnd) >> 16;
6849
6850 while (j-- && so) {
6851 so = TAILQ_NEXT(so, so_list);
6852 }
6853 }
6854 /* Find a connection that is not already closing (or being served) */
6855 while (so) {
6856 inp = (struct inpcb *)so->so_pcb;
6857
6858 sonext = TAILQ_NEXT(so, so_list);
6859
6860 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
6861 /*
6862 * Avoid the issue of a socket being accepted
6863 * by one input thread and being dropped by
6864 * another input thread. If we can't get a hold
6865 * on this mutex, then grab the next socket in
6866 * line.
6867 */
6868 if (socket_try_lock(so)) {
6869 so->so_usecount++;
6870 if ((so->so_usecount == 2) &&
6871 (so->so_state & SS_INCOMP) &&
6872 !(so->so_flags & SOF_INCOMP_INPROGRESS)) {
6873 break;
6874 } else {
6875 /*
6876 * don't use if being accepted or
6877 * used in any other way
6878 */
6879 in_pcb_checkstate(inp, WNT_RELEASE, 1);
6880 socket_unlock(so, 1);
6881 }
6882 } else {
6883 /*
6884 * do not try to lock the inp in
6885 * in_pcb_checkstate because the lock
6886 * is already held in some other thread.
6887 * Only drop the inp_wntcnt reference.
6888 */
6889 in_pcb_checkstate(inp, WNT_RELEASE, 1);
6890 }
6891 }
6892 so = sonext;
6893 }
6894 if (so == NULL) {
6895 socket_lock(head, 0);
6896 so_release_accept_list(head);
6897 return 0;
6898 }
6899
6900 /* Makes sure socket is still in the right state to be discarded */
6901
6902 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
6903 socket_unlock(so, 1);
6904 socket_lock(head, 0);
6905 so_release_accept_list(head);
6906 return 0;
6907 }
6908
6909 found_victim:
6910 if (so->so_usecount != 2 || !(so->so_state & SS_INCOMP)) {
6911 /* do not discard: that socket is being accepted */
6912 socket_unlock(so, 1);
6913 socket_lock(head, 0);
6914 so_release_accept_list(head);
6915 return 0;
6916 }
6917
6918 socket_lock(head, 0);
6919 TAILQ_REMOVE(&head->so_incomp, so, so_list);
6920 head->so_incqlen--;
6921 head->so_qlen--;
6922 so->so_state &= ~SS_INCOMP;
6923 so->so_flags |= SOF_OVERFLOW;
6924 so->so_head = NULL;
6925 so_release_accept_list(head);
6926 socket_unlock(head, 0);
6927
6928 socket_lock_assert_owned(so);
6929 tp = sototcpcb(so);
6930
6931 tcp_close(tp);
6932 if (inp->inp_wantcnt > 0 && inp->inp_wantcnt != WNT_STOPUSING) {
6933 /*
6934 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
6935 * doesn't require a lock, it could have happened while
6936 * we are holding the lock. This pcb will have to
6937 * be garbage collected later.
6938 * Release the reference held for so_incomp queue
6939 */
6940 VERIFY(so->so_usecount > 0);
6941 so->so_usecount--;
6942 socket_unlock(so, 1);
6943 } else {
6944 /*
6945 * Unlock this socket and leave the reference on.
6946 * We need to acquire the pcbinfo lock in order to
6947 * fully dispose it off
6948 */
6949 socket_unlock(so, 0);
6950
6951 lck_rw_lock_exclusive(&tcbinfo.ipi_lock);
6952
6953 socket_lock(so, 0);
6954 /* Release the reference held for so_incomp queue */
6955 VERIFY(so->so_usecount > 0);
6956 so->so_usecount--;
6957
6958 if (so->so_usecount != 1 ||
6959 (inp->inp_wantcnt > 0 &&
6960 inp->inp_wantcnt != WNT_STOPUSING)) {
6961 /*
6962 * There is an extra wantcount or usecount
6963 * that must have been added when the socket
6964 * was unlocked. This socket will have to be
6965 * garbage collected later
6966 */
6967 socket_unlock(so, 1);
6968 } else {
6969 /* Drop the reference held for this function */
6970 VERIFY(so->so_usecount > 0);
6971 so->so_usecount--;
6972
6973 in_pcbdispose(inp);
6974 }
6975 lck_rw_done(&tcbinfo.ipi_lock);
6976 }
6977 tcpstat.tcps_drops++;
6978
6979 socket_lock(head, 0);
6980 return 1;
6981 }
6982
6983 /* Set background congestion control on a socket */
6984 void
tcp_set_background_cc(struct socket * so)6985 tcp_set_background_cc(struct socket *so)
6986 {
6987 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
6988 }
6989
6990 /* Set foreground congestion control on a socket */
6991 void
tcp_set_foreground_cc(struct socket * so)6992 tcp_set_foreground_cc(struct socket *so)
6993 {
6994 if (tcp_use_newreno) {
6995 tcp_set_new_cc(so, TCP_CC_ALGO_NEWRENO_INDEX);
6996 #if (DEVELOPMENT || DEBUG)
6997 } else if (tcp_use_ledbat) {
6998 /* Only used for testing */
6999 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
7000 #endif
7001 } else {
7002 tcp_set_new_cc(so, TCP_CC_ALGO_CUBIC_INDEX);
7003 }
7004 }
7005
7006 static void
tcp_set_new_cc(struct socket * so,uint8_t cc_index)7007 tcp_set_new_cc(struct socket *so, uint8_t cc_index)
7008 {
7009 struct inpcb *inp = sotoinpcb(so);
7010 struct tcpcb *tp = intotcpcb(inp);
7011
7012 if (tp->tcp_cc_index != cc_index) {
7013 if (CC_ALGO(tp)->cleanup != NULL) {
7014 CC_ALGO(tp)->cleanup(tp);
7015 }
7016 tp->tcp_cc_index = cc_index;
7017
7018 tcp_cc_allocate_state(tp);
7019
7020 if (CC_ALGO(tp)->switch_to != NULL) {
7021 CC_ALGO(tp)->switch_to(tp);
7022 }
7023
7024 tcp_ccdbg_trace(tp, NULL, TCP_CC_CHANGE_ALGO);
7025 }
7026 }
7027
7028 void
tcp_set_recv_bg(struct socket * so)7029 tcp_set_recv_bg(struct socket *so)
7030 {
7031 if (!IS_TCP_RECV_BG(so)) {
7032 so->so_flags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
7033
7034 struct inpcb *inp = sotoinpcb(so);
7035 struct tcpcb *tp = intotcpcb(inp);
7036
7037 if (TCP_RLEDBAT_ENABLED(tp) && tcp_cc_rledbat.switch_to != NULL) {
7038 tcp_cc_rledbat.switch_to(tp);
7039 }
7040 }
7041 }
7042
7043 void
tcp_clear_recv_bg(struct socket * so)7044 tcp_clear_recv_bg(struct socket *so)
7045 {
7046 if (IS_TCP_RECV_BG(so)) {
7047 so->so_flags1 &= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG);
7048 }
7049 }
7050
7051 void
inp_fc_throttle_tcp(struct inpcb * inp)7052 inp_fc_throttle_tcp(struct inpcb *inp)
7053 {
7054 struct tcpcb *tp = inp->inp_ppcb;
7055
7056 if (!tcp_flow_control_response) {
7057 return;
7058 }
7059
7060 /*
7061 * Back off the slow-start threshold and enter
7062 * congestion avoidance phase
7063 */
7064 if (CC_ALGO(tp)->pre_fr != NULL) {
7065 CC_ALGO(tp)->pre_fr(tp);
7066 }
7067 }
7068
7069 void
inp_fc_unthrottle_tcp(struct inpcb * inp)7070 inp_fc_unthrottle_tcp(struct inpcb *inp)
7071 {
7072 struct tcpcb *tp = inp->inp_ppcb;
7073
7074 if (tcp_flow_control_response) {
7075 if (CC_ALGO(tp)->post_fr != NULL) {
7076 CC_ALGO(tp)->post_fr(tp, NULL);
7077 }
7078
7079 tp->t_bytes_acked = 0;
7080
7081 /*
7082 * Reset retransmit shift as we know that the reason
7083 * for delay in sending a packet is due to flow
7084 * control on the outgoing interface. There is no need
7085 * to backoff retransmit timer.
7086 */
7087 TCP_RESET_REXMT_STATE(tp);
7088
7089 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
7090
7091 /*
7092 * Start the output stream again. Since we are
7093 * not retransmitting data, do not reset the
7094 * retransmit timer or rtt calculation.
7095 */
7096 tcp_output(tp);
7097 return;
7098 }
7099
7100 /*
7101 * Back off the slow-start threshold and enter
7102 * congestion avoidance phase
7103 */
7104 if (CC_ALGO(tp)->pre_fr != NULL) {
7105 CC_ALGO(tp)->pre_fr(tp);
7106 }
7107
7108 tp->snd_cwnd = tp->snd_ssthresh;
7109 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
7110 /*
7111 * Restart counting for ABC as we changed the
7112 * congestion window just now.
7113 */
7114 tp->t_bytes_acked = 0;
7115
7116 /* Reset retransmit shift as we know that the reason
7117 * for delay in sending a packet is due to flow
7118 * control on the outgoing interface. There is no need
7119 * to backoff retransmit timer.
7120 */
7121 TCP_RESET_REXMT_STATE(tp);
7122
7123 /*
7124 * Start the output stream again. Since we are
7125 * not retransmitting data, do not reset the
7126 * retransmit timer or rtt calculation.
7127 */
7128 tcp_output(tp);
7129 }
7130
7131 static int
7132 tcp_getstat SYSCTL_HANDLER_ARGS
7133 {
7134 #pragma unused(oidp, arg1, arg2)
7135
7136 int error;
7137 struct tcpstat *stat;
7138 stat = &tcpstat;
7139 #if XNU_TARGET_OS_OSX
7140 struct tcpstat zero_stat;
7141
7142 if (tcp_disable_access_to_stats &&
7143 !kauth_cred_issuser(kauth_cred_get())) {
7144 bzero(&zero_stat, sizeof(zero_stat));
7145 stat = &zero_stat;
7146 }
7147
7148 #endif /* XNU_TARGET_OS_OSX */
7149
7150 if (req->oldptr == 0) {
7151 req->oldlen = (size_t)sizeof(struct tcpstat);
7152 }
7153
7154 error = SYSCTL_OUT(req, stat, MIN(sizeof(tcpstat), req->oldlen));
7155
7156 return error;
7157 }
7158
7159 /*
7160 * Checksum extended TCP header and data.
7161 */
7162 int
tcp_input_checksum(int af,struct mbuf * m,struct tcphdr * th,int off,int tlen)7163 tcp_input_checksum(int af, struct mbuf *m, struct tcphdr *th, int off, int tlen)
7164 {
7165 struct ifnet *ifp = m->m_pkthdr.rcvif;
7166
7167 switch (af) {
7168 case AF_INET: {
7169 struct ip *ip = mtod(m, struct ip *);
7170 struct ipovly *ipov = (struct ipovly *)ip;
7171
7172 /* ip_stripoptions() must have been called before we get here */
7173 ASSERT((ip->ip_hl << 2) == sizeof(*ip));
7174
7175 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
7176 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
7177 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
7178 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7179 th->th_sum = m->m_pkthdr.csum_rx_val;
7180 } else {
7181 uint32_t sum = m->m_pkthdr.csum_rx_val;
7182 uint32_t start = m->m_pkthdr.csum_rx_start;
7183 int32_t trailer = (m_pktlen(m) - (off + tlen));
7184
7185 /*
7186 * Perform 1's complement adjustment of octets
7187 * that got included/excluded in the hardware-
7188 * calculated checksum value. Ignore cases
7189 * where the value already includes the entire
7190 * IP header span, as the sum for those octets
7191 * would already be 0 by the time we get here;
7192 * IP has already performed its header checksum
7193 * checks. If we do need to adjust, restore
7194 * the original fields in the IP header when
7195 * computing the adjustment value. Also take
7196 * care of any trailing bytes and subtract out
7197 * their partial sum.
7198 */
7199 ASSERT(trailer >= 0);
7200 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
7201 ((start != 0 && start != off) || trailer)) {
7202 uint32_t swbytes = (uint32_t)trailer;
7203
7204 if (start < off) {
7205 ip->ip_len += sizeof(*ip);
7206 #if BYTE_ORDER != BIG_ENDIAN
7207 HTONS(ip->ip_len);
7208 HTONS(ip->ip_off);
7209 #endif /* BYTE_ORDER != BIG_ENDIAN */
7210 }
7211 /* callee folds in sum */
7212 sum = m_adj_sum16(m, start, off,
7213 tlen, sum);
7214 if (off > start) {
7215 swbytes += (off - start);
7216 } else {
7217 swbytes += (start - off);
7218 }
7219
7220 if (start < off) {
7221 #if BYTE_ORDER != BIG_ENDIAN
7222 NTOHS(ip->ip_off);
7223 NTOHS(ip->ip_len);
7224 #endif /* BYTE_ORDER != BIG_ENDIAN */
7225 ip->ip_len -= sizeof(*ip);
7226 }
7227
7228 if (swbytes != 0) {
7229 tcp_in_cksum_stats(swbytes);
7230 }
7231 if (trailer != 0) {
7232 m_adj(m, -trailer);
7233 }
7234 }
7235
7236 /* callee folds in sum */
7237 th->th_sum = in_pseudo(ip->ip_src.s_addr,
7238 ip->ip_dst.s_addr,
7239 sum + htonl(tlen + IPPROTO_TCP));
7240 }
7241 th->th_sum ^= 0xffff;
7242 } else {
7243 uint16_t ip_sum;
7244 int len;
7245 char b[9];
7246
7247 bcopy(ipov->ih_x1, b, sizeof(ipov->ih_x1));
7248 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
7249 ip_sum = ipov->ih_len;
7250 ipov->ih_len = (u_short)tlen;
7251 #if BYTE_ORDER != BIG_ENDIAN
7252 HTONS(ipov->ih_len);
7253 #endif
7254 len = sizeof(struct ip) + tlen;
7255 th->th_sum = in_cksum(m, len);
7256 bcopy(b, ipov->ih_x1, sizeof(ipov->ih_x1));
7257 ipov->ih_len = ip_sum;
7258
7259 tcp_in_cksum_stats(len);
7260 }
7261 break;
7262 }
7263 case AF_INET6: {
7264 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
7265
7266 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
7267 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
7268 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
7269 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7270 th->th_sum = m->m_pkthdr.csum_rx_val;
7271 } else {
7272 uint32_t sum = m->m_pkthdr.csum_rx_val;
7273 uint32_t start = m->m_pkthdr.csum_rx_start;
7274 int32_t trailer = (m_pktlen(m) - (off + tlen));
7275
7276 /*
7277 * Perform 1's complement adjustment of octets
7278 * that got included/excluded in the hardware-
7279 * calculated checksum value. Also take care
7280 * of any trailing bytes and subtract out their
7281 * partial sum.
7282 */
7283 ASSERT(trailer >= 0);
7284 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
7285 (start != off || trailer != 0)) {
7286 uint16_t s = 0, d = 0;
7287 uint32_t swbytes = (uint32_t)trailer;
7288
7289 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7290 s = ip6->ip6_src.s6_addr16[1];
7291 ip6->ip6_src.s6_addr16[1] = 0;
7292 }
7293 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7294 d = ip6->ip6_dst.s6_addr16[1];
7295 ip6->ip6_dst.s6_addr16[1] = 0;
7296 }
7297
7298 /* callee folds in sum */
7299 sum = m_adj_sum16(m, start, off,
7300 tlen, sum);
7301 if (off > start) {
7302 swbytes += (off - start);
7303 } else {
7304 swbytes += (start - off);
7305 }
7306
7307 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7308 ip6->ip6_src.s6_addr16[1] = s;
7309 }
7310 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7311 ip6->ip6_dst.s6_addr16[1] = d;
7312 }
7313
7314 if (swbytes != 0) {
7315 tcp_in6_cksum_stats(swbytes);
7316 }
7317 if (trailer != 0) {
7318 m_adj(m, -trailer);
7319 }
7320 }
7321
7322 th->th_sum = in6_pseudo(
7323 &ip6->ip6_src, &ip6->ip6_dst,
7324 sum + htonl(tlen + IPPROTO_TCP));
7325 }
7326 th->th_sum ^= 0xffff;
7327 } else {
7328 tcp_in6_cksum_stats(tlen);
7329 th->th_sum = in6_cksum(m, IPPROTO_TCP, off, tlen);
7330 }
7331 break;
7332 }
7333 default:
7334 VERIFY(0);
7335 /* NOTREACHED */
7336 }
7337
7338 if (th->th_sum != 0) {
7339 tcpstat.tcps_rcvbadsum++;
7340 IF_TCP_STATINC(ifp, badformat);
7341 return -1;
7342 }
7343
7344 return 0;
7345 }
7346
7347 #define DUMP_BUF_CHK() { \
7348 clen -= k; \
7349 if (clen < 1) \
7350 goto done; \
7351 c += k; \
7352 }
7353
7354 int
dump_tcp_reass_qlen(char * str,int str_len)7355 dump_tcp_reass_qlen(char *str, int str_len)
7356 {
7357 char *c = str;
7358 int k, clen = str_len;
7359
7360 if (tcp_reass_total_qlen != 0) {
7361 k = scnprintf(c, clen, "\ntcp reass qlen %d\n", tcp_reass_total_qlen);
7362 DUMP_BUF_CHK();
7363 }
7364
7365 done:
7366 return str_len - clen;
7367 }
7368
7369 uint32_t
tcp_reass_qlen_space(struct socket * so)7370 tcp_reass_qlen_space(struct socket *so)
7371 {
7372 uint32_t space = 0;
7373 struct inpcb *inp = sotoinpcb(so);
7374
7375 if (inp != NULL) {
7376 struct tcpcb *tp = intotcpcb(inp);
7377
7378 if (tp != NULL) {
7379 space = tp->t_reassq_mbcnt;
7380 }
7381 }
7382 return space;
7383 }
7384
7385
7386 SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats,
7387 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, tcp_getstat,
7388 "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
7389
7390 static int
7391 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
7392 {
7393 #pragma unused(arg1, arg2)
7394
7395 int error, val = tcprexmtthresh;
7396
7397 error = sysctl_handle_int(oidp, &val, 0, req);
7398 if (error || !req->newptr) {
7399 return error;
7400 }
7401
7402 /*
7403 * Constrain the number of duplicate ACKs
7404 * to consider for TCP fast retransmit
7405 * to either 2 or 3
7406 */
7407
7408 if (val < 2 || val > 3) {
7409 return EINVAL;
7410 }
7411
7412 tcprexmtthresh = (uint8_t)val;
7413
7414 return 0;
7415 }
7416
7417 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, rexmt_thresh, CTLTYPE_INT | CTLFLAG_RW |
7418 CTLFLAG_LOCKED, &tcprexmtthresh, 0, &sysctl_rexmtthresh, "I",
7419 "Duplicate ACK Threshold for Fast Retransmit");
7420