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