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