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