xref: /xnu-11215.1.10/bsd/netinet/tcp_output.c (revision 8d741a5de7ff4191bf97d57b9f54c2f6d4a15585)
1 /*
2  * Copyright (c) 2000-2024 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, 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_output.c	8.4 (Berkeley) 5/24/95
61  * $FreeBSD: src/sys/netinet/tcp_output.c,v 1.39.2.10 2001/07/07 04:30:38 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 #define _IP_VHL
71 
72 #include "tcp_includes.h"
73 
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/kernel.h>
77 #include <sys/sysctl.h>
78 #include <sys/mbuf.h>
79 #include <sys/domain.h>
80 #include <sys/protosw.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <os/ptrtools.h>
84 
85 #include <net/route.h>
86 #include <net/ntstat.h>
87 #include <net/if_var.h>
88 #include <net/if.h>
89 #include <net/if_types.h>
90 #include <net/dlil.h>
91 
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/in_var.h>
95 #include <netinet/in_tclass.h>
96 #include <netinet/ip.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/ip_var.h>
99 #include <mach/sdt.h>
100 #include <netinet6/in6_pcb.h>
101 #include <netinet/ip6.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet/tcp.h>
104 #include <netinet/tcp_cache.h>
105 #include <netinet/tcp_fsm.h>
106 #include <netinet/tcp_seq.h>
107 #include <netinet/tcp_timer.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet/tcpip.h>
110 #include <netinet/tcp_cc.h>
111 #include <netinet/tcp_log.h>
112 #include <sys/kdebug.h>
113 #include <mach/sdt.h>
114 
115 #if IPSEC
116 #include <netinet6/ipsec.h>
117 #endif /*IPSEC*/
118 
119 #if MPTCP
120 #include <netinet/mptcp_var.h>
121 #include <netinet/mptcp.h>
122 #include <netinet/mptcp_opt.h>
123 #include <netinet/mptcp_seq.h>
124 #endif
125 
126 #include <corecrypto/ccaes.h>
127 
128 #define DBG_LAYER_BEG           NETDBG_CODE(DBG_NETTCP, 1)
129 #define DBG_LAYER_END           NETDBG_CODE(DBG_NETTCP, 3)
130 #define DBG_FNC_TCP_OUTPUT      NETDBG_CODE(DBG_NETTCP, (4 << 8) | 1)
131 
132 SYSCTL_SKMEM_TCP_INT(OID_AUTO, path_mtu_discovery,
133     CTLFLAG_RW | CTLFLAG_LOCKED, int, path_mtu_discovery, 1,
134     "Enable Path MTU Discovery");
135 
136 SYSCTL_SKMEM_TCP_INT(OID_AUTO, local_slowstart_flightsize,
137     CTLFLAG_RW | CTLFLAG_LOCKED, int, ss_fltsz_local, 8,
138     "Slow start flight size for local networks");
139 
140 SYSCTL_SKMEM_TCP_INT(OID_AUTO, tso, CTLFLAG_RW | CTLFLAG_LOCKED,
141     int, tcp_do_tso, 1, "Enable TCP Segmentation Offload");
142 
143 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ecn_setup_percentage,
144     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ecn_setup_percentage, 100,
145     "Max ECN setup percentage");
146 
147 SYSCTL_SKMEM_TCP_INT(OID_AUTO, accurate_ecn,
148     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_acc_ecn, 0,
149     "Accurate ECN mode (0: disable, 1: enable Accurate ECN feedback");
150 
151 SYSCTL_SKMEM_TCP_INT(OID_AUTO, l4s,
152     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_l4s, 0,
153     "L4S mode (0: disable, 1: enable L4S");
154 
155 // TO BE REMOVED
156 SYSCTL_SKMEM_TCP_INT(OID_AUTO, do_ack_compression,
157     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_ack_compression, 1,
158     "Enable TCP ACK compression (on (cell only): 1, off: 0, on (all interfaces): 2)");
159 
160 SYSCTL_SKMEM_TCP_INT(OID_AUTO, ack_compression_rate,
161     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_ack_compression_rate, TCP_COMP_CHANGE_RATE,
162     "Rate at which we force sending new ACKs (in ms)");
163 
164 SYSCTL_SKMEM_TCP_INT(OID_AUTO, randomize_timestamps,
165     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_randomize_timestamps, 1,
166     "Randomize TCP timestamps to prevent tracking (on: 1, off: 0)");
167 
168 static int
169 sysctl_change_ecn_setting SYSCTL_HANDLER_ARGS
170 {
171 #pragma unused(oidp, arg1, arg2)
172 	int i, err = 0, changed = 0;
173 	ifnet_ref_t ifp;
174 
175 	err = sysctl_io_number(req, tcp_ecn_outbound, sizeof(int32_t),
176 	    &i, &changed);
177 	if (err != 0 || req->newptr == USER_ADDR_NULL) {
178 		return err;
179 	}
180 
181 	if (changed) {
182 		if ((tcp_ecn_outbound == 0 || tcp_ecn_outbound == 1) &&
183 		    (i == 0 || i == 1)) {
184 			tcp_ecn_outbound = i;
185 			SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn_initiate_out, tcp_ecn_outbound);
186 			return err;
187 		}
188 		if (tcp_ecn_outbound == 2 && (i == 0 || i == 1)) {
189 			/*
190 			 * Reset ECN enable flags on non-cellular
191 			 * interfaces so that the system default will take
192 			 * over
193 			 */
194 			ifnet_head_lock_shared();
195 			TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
196 				if (!IFNET_IS_CELLULAR(ifp)) {
197 					if_clear_eflags(ifp,
198 					    IFEF_ECN_ENABLE |
199 					    IFEF_ECN_DISABLE);
200 				}
201 			}
202 			ifnet_head_done();
203 		} else {
204 			/*
205 			 * Set ECN enable flags on non-cellular
206 			 * interfaces
207 			 */
208 			ifnet_head_lock_shared();
209 			TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
210 				if (!IFNET_IS_CELLULAR(ifp)) {
211 					if_set_eflags(ifp, IFEF_ECN_ENABLE);
212 					if_clear_eflags(ifp, IFEF_ECN_DISABLE);
213 				}
214 			}
215 			ifnet_head_done();
216 		}
217 		tcp_ecn_outbound = i;
218 		SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn_initiate_out, tcp_ecn_outbound);
219 	}
220 	/* Change the other one too as the work is done */
221 	if (i == 2 || tcp_ecn_inbound == 2) {
222 		tcp_ecn_inbound = i;
223 		SYSCTL_SKMEM_UPDATE_FIELD(tcp.ecn_negotiate_in, tcp_ecn_inbound);
224 	}
225 	return err;
226 }
227 
228 int     tcp_ecn_outbound = 2;
229 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, ecn_initiate_out,
230     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_ecn_outbound, 0,
231     sysctl_change_ecn_setting, "IU",
232     "Initiate ECN for outbound connections");
233 
234 int     tcp_ecn_inbound = 2;
235 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, ecn_negotiate_in,
236     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_ecn_inbound, 0,
237     sysctl_change_ecn_setting, "IU",
238     "Initiate ECN for inbound connections");
239 
240 SYSCTL_SKMEM_TCP_INT(OID_AUTO, packetchain,
241     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_packet_chaining, 50,
242     "Enable TCP output packet chaining");
243 
244 SYSCTL_SKMEM_TCP_INT(OID_AUTO, socket_unlocked_on_output,
245     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_output_unlocked, 1,
246     "Unlock TCP when sending packets down to IP");
247 
248 SYSCTL_SKMEM_TCP_INT(OID_AUTO, min_iaj_win,
249     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_min_iaj_win, MIN_IAJ_WIN,
250     "Minimum recv win based on inter-packet arrival jitter");
251 
252 SYSCTL_SKMEM_TCP_INT(OID_AUTO, acc_iaj_react_limit,
253     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_acc_iaj_react_limit,
254     ACC_IAJ_REACT_LIMIT, "Accumulated IAJ when receiver starts to react");
255 
256 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autosndbufinc,
257     CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_autosndbuf_inc,
258     8 * 1024, "Increment in send socket bufffer size");
259 
260 SYSCTL_SKMEM_TCP_INT(OID_AUTO, autosndbufmax,
261     CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_KERN, uint32_t, tcp_autosndbuf_max, 2 * 1024 * 1024,
262     "Maximum send socket buffer size");
263 
264 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rtt_recvbg,
265     CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_use_rtt_recvbg, 1,
266     "Use RTT for bg recv algorithm");
267 
268 SYSCTL_SKMEM_TCP_INT(OID_AUTO, recv_throttle_minwin,
269     CTLFLAG_RW | CTLFLAG_LOCKED, uint32_t, tcp_recv_throttle_minwin, 16 * 1024,
270     "Minimum recv win for throttling");
271 
272 SYSCTL_SKMEM_TCP_INT(OID_AUTO, enable_tlp,
273     CTLFLAG_RW | CTLFLAG_LOCKED,
274     int32_t, tcp_enable_tlp, 1, "Enable Tail loss probe");
275 
276 static int32_t packchain_newlist = 0;
277 static int32_t packchain_looped = 0;
278 static int32_t packchain_sent = 0;
279 
280 /* temporary: for testing */
281 #if IPSEC
282 extern int ipsec_bypass;
283 #endif
284 
285 extern int slowlink_wsize;      /* window correction for slow links */
286 
287 extern u_int32_t kipf_count;
288 
289 static int tcp_ip_output(struct socket *, struct tcpcb *, struct mbuf *,
290     int, struct mbuf *, int, int, boolean_t);
291 static int tcp_recv_throttle(struct tcpcb *tp);
292 
293 __attribute__((noinline))
294 static int32_t
tcp_tfo_check(struct tcpcb * tp,int32_t len)295 tcp_tfo_check(struct tcpcb *tp, int32_t len)
296 {
297 	struct socket *__single so = tp->t_inpcb->inp_socket;
298 	unsigned int optlen = 0;
299 	unsigned int cookie_len;
300 
301 	if (tp->t_flags & TF_NOOPT) {
302 		goto fallback;
303 	}
304 
305 	if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
306 	    !tcp_heuristic_do_tfo(tp)) {
307 		tp->t_tfo_stats |= TFO_S_HEURISTICS_DISABLE;
308 		tcpstat.tcps_tfo_heuristics_disable++;
309 		goto fallback;
310 	}
311 
312 	if (so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
313 		return len;
314 	}
315 
316 	optlen += TCPOLEN_MAXSEG;
317 
318 	if (tp->t_flags & TF_REQ_SCALE) {
319 		optlen += 4;
320 	}
321 
322 #if MPTCP
323 	if ((so->so_flags & SOF_MP_SUBFLOW) && mptcp_enable &&
324 	    (tp->t_rxtshift <= mptcp_mpcap_retries ||
325 	    (tptomptp(tp)->mpt_mpte->mpte_flags & MPTE_FORCE_ENABLE))) {
326 		optlen += sizeof(struct mptcp_mpcapable_opt_common) + sizeof(mptcp_key_t);
327 	}
328 #endif /* MPTCP */
329 
330 	if (tp->t_flags & TF_REQ_TSTMP) {
331 		optlen += TCPOLEN_TSTAMP_APPA;
332 	}
333 
334 	if (SACK_ENABLED(tp)) {
335 		optlen += TCPOLEN_SACK_PERMITTED;
336 	}
337 
338 	/* Now, decide whether to use TFO or not */
339 
340 	/* Don't even bother trying if there is no space at all... */
341 	if (MAX_TCPOPTLEN - optlen < TCPOLEN_FASTOPEN_REQ) {
342 		goto fallback;
343 	}
344 
345 	cookie_len = tcp_cache_get_cookie_len(tp);
346 	if (cookie_len == 0) {
347 		/* No cookie, so we request one */
348 		return 0;
349 	}
350 
351 	/* There is not enough space for the cookie, so we cannot do TFO */
352 	if (MAX_TCPOPTLEN - optlen < cookie_len) {
353 		goto fallback;
354 	}
355 
356 	/* Do not send SYN+data if there is more in the queue than MSS */
357 	if (so->so_snd.sb_cc > (tp->t_maxopd - MAX_TCPOPTLEN)) {
358 		goto fallback;
359 	}
360 
361 	/* Ok, everything looks good. We can go on and do TFO */
362 	return len;
363 
364 fallback:
365 	tcp_disable_tfo(tp);
366 	return 0;
367 }
368 
369 /* Returns the number of bytes written to the TCP option-space */
370 __attribute__((noinline))
371 static unsigned int
372 tcp_tfo_write_cookie_rep(struct tcpcb *tp, unsigned int optlen,
373     u_char *__counted_by(optlen + 2 + TFO_COOKIE_LEN_DEFAULT) opt)
374 {
375 	u_char out[CCAES_BLOCK_SIZE];
376 	unsigned ret = 0;
377 	u_char *bp;
378 
379 	if (MAX_TCPOPTLEN - optlen <
380 	    TCPOLEN_FASTOPEN_REQ + TFO_COOKIE_LEN_DEFAULT) {
381 		return ret;
382 	}
383 
384 	tcp_tfo_gen_cookie(tp->t_inpcb, out, sizeof(out));
385 
386 	bp = opt + optlen;
387 
388 	*bp++ = TCPOPT_FASTOPEN;
389 	*bp++ = 2 + TFO_COOKIE_LEN_DEFAULT;
390 	memcpy(bp, out, TFO_COOKIE_LEN_DEFAULT);
391 	ret += 2 + TFO_COOKIE_LEN_DEFAULT;
392 
393 	tp->t_tfo_stats |= TFO_S_COOKIE_SENT;
394 	tcpstat.tcps_tfo_cookie_sent++;
395 
396 	return ret;
397 }
398 
399 __attribute__((noinline))
400 static unsigned int
tcp_tfo_write_cookie(struct tcpcb * tp,unsigned int optlen,int32_t len,u_char * __counted_by (TCP_MAXOLEN)opt)401 tcp_tfo_write_cookie(struct tcpcb *tp, unsigned int optlen, int32_t len,
402     u_char *__counted_by(TCP_MAXOLEN) opt)
403 {
404 	uint8_t tfo_len;
405 	struct socket *__single so = tp->t_inpcb->inp_socket;
406 	unsigned ret = 0;
407 	int res;
408 	u_char *bp;
409 
410 	if (TCPOLEN_FASTOPEN_REQ > MAX_TCPOPTLEN - optlen) {
411 		return 0;
412 	}
413 	tfo_len = (uint8_t)(MAX_TCPOPTLEN - optlen - TCPOLEN_FASTOPEN_REQ);
414 
415 	if (so->so_flags1 & SOF1_DATA_AUTHENTICATED) {
416 		/* If there is some data, let's track it */
417 		if (len > 0) {
418 			tp->t_tfo_stats |= TFO_S_SYN_DATA_SENT;
419 			tcpstat.tcps_tfo_syn_data_sent++;
420 		}
421 
422 		return 0;
423 	}
424 
425 	bp = opt + optlen;
426 
427 	/*
428 	 * The cookie will be copied in the appropriate place within the
429 	 * TCP-option space. That way we avoid the need for an intermediate
430 	 * variable.
431 	 */
432 	res = tcp_cache_get_cookie(tp, bp + TCPOLEN_FASTOPEN_REQ, tfo_len, &tfo_len);
433 	if (res == 0) {
434 		*bp++ = TCPOPT_FASTOPEN;
435 		*bp++ = TCPOLEN_FASTOPEN_REQ;
436 		ret += TCPOLEN_FASTOPEN_REQ;
437 
438 		tp->t_tfo_flags |= TFO_F_COOKIE_REQ;
439 
440 		tp->t_tfo_stats |= TFO_S_COOKIE_REQ;
441 		tcpstat.tcps_tfo_cookie_req++;
442 	} else {
443 		*bp++ = TCPOPT_FASTOPEN;
444 		*bp++ = TCPOLEN_FASTOPEN_REQ + tfo_len;
445 
446 		ret += TCPOLEN_FASTOPEN_REQ + tfo_len;
447 
448 		tp->t_tfo_flags |= TFO_F_COOKIE_SENT;
449 
450 		/* If there is some data, let's track it */
451 		if (len > 0) {
452 			tp->t_tfo_stats |= TFO_S_SYN_DATA_SENT;
453 			tcpstat.tcps_tfo_syn_data_sent++;
454 		}
455 	}
456 
457 	return ret;
458 }
459 
460 static inline bool
tcp_send_ecn_flags_on_syn(struct tcpcb * tp)461 tcp_send_ecn_flags_on_syn(struct tcpcb *tp)
462 {
463 	/* We allow Accurate ECN negotiation on first retransmission as well */
464 	bool send_on_first_retrans = (tp->ecn_flags & TE_ACE_SETUPSENT) &&
465 	    (tp->t_rxtshift <= 1);
466 
467 	return !(tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) || send_on_first_retrans;
468 }
469 
470 void
tcp_set_ecn(struct tcpcb * tp,struct ifnet * ifp)471 tcp_set_ecn(struct tcpcb *tp, struct ifnet *ifp)
472 {
473 	boolean_t inbound;
474 
475 	/*
476 	 * Socket option has precedence
477 	 */
478 	if (tp->ecn_flags & TE_ECN_MODE_ENABLE) {
479 		tp->ecn_flags |= TE_ENABLE_ECN;
480 		goto check_heuristic;
481 	}
482 
483 	if (tp->ecn_flags & TE_ECN_MODE_DISABLE) {
484 		tp->ecn_flags &= ~TE_ENABLE_ECN;
485 		return;
486 	}
487 	/*
488 	 * Per interface setting comes next
489 	 */
490 	if (ifp != NULL) {
491 		if (ifp->if_eflags & IFEF_ECN_ENABLE) {
492 			tp->ecn_flags |= TE_ENABLE_ECN;
493 			goto check_heuristic;
494 		}
495 
496 		if (ifp->if_eflags & IFEF_ECN_DISABLE) {
497 			tp->ecn_flags &= ~TE_ENABLE_ECN;
498 			return;
499 		}
500 	}
501 	/*
502 	 * System wide settings come last
503 	 */
504 	inbound = (tp->t_inpcb->inp_socket->so_head != NULL);
505 	if ((inbound && tcp_ecn_inbound == 1) ||
506 	    (!inbound && tcp_ecn_outbound == 1)) {
507 		tp->ecn_flags |= TE_ENABLE_ECN;
508 		goto check_heuristic;
509 	} else {
510 		tp->ecn_flags &= ~TE_ENABLE_ECN;
511 	}
512 
513 	return;
514 
515 check_heuristic:
516 	if (TCP_ACC_ECN_ENABLED(tp)) {
517 		/* Allow ECN when Accurate ECN is enabled until heuristics are fixed */
518 		tp->ecn_flags |= TE_ENABLE_ECN;
519 		/* Set the accurate ECN state */
520 		if (tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_disabled) {
521 			tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_feature_enabled;
522 		}
523 		if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_feature_disabled) {
524 			tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_feature_enabled;
525 		}
526 	}
527 	if (!tcp_heuristic_do_ecn(tp) && !TCP_ACC_ECN_ENABLED(tp)) {
528 		/* Allow ECN when Accurate ECN is enabled until heuristics are fixed */
529 		tp->ecn_flags &= ~TE_ENABLE_ECN;
530 	}
531 	/*
532 	 * If the interface setting, system-level setting and heuristics
533 	 * allow to enable ECN, randomly select 5% of connections to
534 	 * enable it
535 	 */
536 	if ((tp->ecn_flags & (TE_ECN_MODE_ENABLE | TE_ECN_MODE_DISABLE
537 	    | TE_ENABLE_ECN)) == TE_ENABLE_ECN) {
538 		/*
539 		 * Use the random value in iss for randomizing
540 		 * this selection
541 		 */
542 		if ((tp->iss % 100) >= tcp_ecn_setup_percentage && !TCP_ACC_ECN_ENABLED(tp)) {
543 			/* Don't disable Accurate ECN randomly */
544 			tp->ecn_flags &= ~TE_ENABLE_ECN;
545 		}
546 	}
547 }
548 
549 uint32_t
tcp_flight_size(struct tcpcb * tp)550 tcp_flight_size(struct tcpcb *tp)
551 {
552 	int ret;
553 
554 	VERIFY(tp->sackhint.sack_bytes_acked >= 0);
555 	VERIFY(tp->sackhint.sack_bytes_rexmit >= 0);
556 
557 	/*
558 	 * RFC6675, SetPipe (), SACK'd bytes are discounted. All the rest is still in-flight.
559 	 */
560 	ret = tp->snd_nxt - tp->snd_una - tp->sackhint.sack_bytes_acked;
561 
562 	if (TCP_RACK_ENABLED(tp)) {
563 		/* In flight is bytes sent - bytes that left the network + bytes retransmitted */
564 		const uint32_t bytes_sent = SEQ_MAX(tp->snd_max, tp->snd_nxt) - tp->snd_una;
565 		const uint32_t bytes_not_in_flight = tp->bytes_sacked + tp->bytes_lost;
566 		ret = bytes_sent - bytes_not_in_flight + tp->bytes_retransmitted;
567 	}
568 
569 	if (ret < 0) {
570 		/* It shouldn't happen when RACK is enabled */
571 		if (TCP_RACK_ENABLED(tp)) {
572 			os_log_error(OS_LOG_DEFAULT, "flight_size (%d) can't be negative "
573 			    "(snd_nxt:%u snd_max:%u, snd_una:%u, sacked:%u lost:%u retransmitted:%u)",
574 			    ret, tp->snd_nxt, tp->snd_max, tp->snd_una,
575 			    tp->bytes_sacked, tp->bytes_lost, tp->bytes_retransmitted);
576 		}
577 		/*
578 		 * This happens when the RTO-timer fires because snd_nxt gets artificially
579 		 * decreased. If we then receive some SACK-blogs, sack_bytes_acked is
580 		 * going to be high.
581 		 */
582 		ret = 0;
583 	}
584 
585 	return ret;
586 }
587 
588 /*
589  * Either of ECT0 or ECT1 flag should be set
590  * when this function is called
591  */
592 static void
tcp_add_accecn_option(struct tcpcb * tp,uint16_t flags,uint32_t * __indexable lp,uint8_t * optlen)593 tcp_add_accecn_option(struct tcpcb *tp, uint16_t flags, uint32_t *__indexable lp, uint8_t *optlen)
594 {
595 	uint8_t max_len = TCP_MAXOLEN - *optlen;
596 	uint8_t len = TCPOLEN_ACCECN_EMPTY;
597 
598 	uint32_t e1b = (uint32_t)(tp->t_aecn.t_rcv_ect1_bytes & TCP_ACO_MASK);
599 	uint32_t e0b = (uint32_t)(tp->t_aecn.t_rcv_ect0_bytes & TCP_ACO_MASK);
600 	uint32_t ceb =  (uint32_t)(tp->t_aecn.t_rcv_ce_bytes & TCP_ACO_MASK);
601 
602 	if (max_len < TCPOLEN_ACCECN_EMPTY) {
603 		TCP_LOG(tp, "not enough space to add any AccECN option");
604 		return;
605 	}
606 
607 	if (!(flags & TH_SYN || (tp->ecn_flags & TE_ACE_FINAL_ACK_3WHS) ||
608 	    tp->snd_una == tp->iss + 1 ||
609 	    tp->ecn_flags & (TE_ACO_ECT1 | TE_ACO_ECT0))) {
610 		/*
611 		 * Since this is neither a SYN-ACK packet, nor the final ACK of
612 		 * the 3WHS (nor the first acked data segment) nor any of the ECT byte
613 		 * counter flags are set, no need to send the option.
614 		 */
615 		return;
616 	}
617 
618 	if ((flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
619 	    tp->t_rxtshift >= 1) {
620 		/*
621 		 * If this is a SYN-ACK retransmission (first),
622 		 * retry without AccECN option and just with ACE fields.
623 		 * From second retransmission onwards, we don't send any
624 		 * Accurate ECN state.
625 		 */
626 		return;
627 	}
628 
629 	if (max_len < (TCPOLEN_ACCECN_EMPTY + 1 * TCPOLEN_ACCECN_COUNTER)) {
630 		/* Can carry EMPTY option which can be used to test path in SYN-ACK packet */
631 		if (flags & TH_SYN) {
632 			*lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) |
633 			    (TCPOPT_NOP << 8) | TCPOPT_NOP);
634 			*optlen += len + 2; /* 2 NOPs */
635 			TCP_LOG(tp, "add empty AccECN option, optlen=%u", *optlen);
636 		}
637 	} else if (max_len < (TCPOLEN_ACCECN_EMPTY + 2 * TCPOLEN_ACCECN_COUNTER)) {
638 		/* Can carry one option */
639 		len += 1 * TCPOLEN_ACCECN_COUNTER;
640 		if (tp->ecn_flags & TE_ACO_ECT1) {
641 			*lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | ((e1b >> 8) & 0xffff));
642 			*lp++ = htonl(((e1b & 0xff) << 24) | (TCPOPT_NOP << 16) | (TCPOPT_NOP << 8) | TCPOPT_NOP);
643 		} else {
644 			*lp++ = htonl((TCPOPT_ACCECN0 << 24) | (len << 16) | ((e0b >> 8) & 0xffff));
645 			*lp++ = htonl(((e0b & 0xff) << 24) | (TCPOPT_NOP << 16) | (TCPOPT_NOP << 8) | TCPOPT_NOP);
646 		}
647 		*optlen += len + 3; /* 3 NOPs */
648 		TCP_LOG(tp, "add single counter for AccECN option, optlen=%u", *optlen);
649 	} else if (max_len < (TCPOLEN_ACCECN_EMPTY + 3 * TCPOLEN_ACCECN_COUNTER)) {
650 		/* Can carry two options */
651 		len += 2 * TCPOLEN_ACCECN_COUNTER;
652 		if (tp->ecn_flags & TE_ACO_ECT1) {
653 			*lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | ((e1b >> 8) & 0xffff));
654 			*lp++ = htonl(((e1b & 0xff) << 24) | (ceb & 0xffffff));
655 		} else {
656 			*lp++ = htonl((TCPOPT_ACCECN0 << 24) | (len << 16) | ((e0b >> 8) & 0xffff));
657 			*lp++ = htonl(((e0b & 0xff) << 24) | (ceb & 0xffffff));
658 		}
659 		*optlen += len; /* 0 NOPs */
660 		TCP_LOG(tp, "add 2 counters for AccECN option, optlen=%u", *optlen);
661 	} else {
662 		/*
663 		 * TCP option sufficient to hold full AccECN option
664 		 * but send counter that changed during the entire connection.
665 		 */
666 		len += 3 * TCPOLEN_ACCECN_COUNTER;
667 		/* Can carry all three options */
668 		if (tp->ecn_flags & TE_ACO_ECT1) {
669 			*lp++ = htonl((TCPOPT_ACCECN1 << 24) | (len << 16) | ((e1b >> 8) & 0xffff));
670 			*lp++ = htonl(((e1b & 0xff) << 24) | (ceb & 0xffffff));
671 			*lp++ = htonl(((e0b & 0xffffff) << 8) | TCPOPT_NOP);
672 		} else {
673 			*lp++ = htonl((TCPOPT_ACCECN0 << 24) | (len << 16) | ((e0b >> 8) & 0xffff));
674 			*lp++ = htonl(((e0b & 0xff) << 24) | (ceb & 0xffffff));
675 			*lp++ = htonl(((e1b & 0xffffff) << 8) | TCPOPT_NOP);
676 		}
677 		*optlen += len + 1; /* 1 NOP */
678 		TCP_LOG(tp, "add all 3 counters for AccECN option, optlen=%u", *optlen);
679 	}
680 }
681 
682 /*
683  * Tcp output routine: figure out what should be sent and send it.
684  *
685  * Returns:	0			Success
686  *		EADDRNOTAVAIL
687  *		ENOBUFS
688  *		EMSGSIZE
689  *		EHOSTUNREACH
690  *		ENETDOWN
691  *	ip_output_list:ENOMEM
692  *	ip_output_list:EADDRNOTAVAIL
693  *	ip_output_list:ENETUNREACH
694  *	ip_output_list:EHOSTUNREACH
695  *	ip_output_list:EACCES
696  *	ip_output_list:EMSGSIZE
697  *	ip_output_list:ENOBUFS
698  *	ip_output_list:???		[ignorable: mostly IPSEC/firewall/DLIL]
699  *	ip6_output_list:EINVAL
700  *	ip6_output_list:EOPNOTSUPP
701  *	ip6_output_list:EHOSTUNREACH
702  *	ip6_output_list:EADDRNOTAVAIL
703  *	ip6_output_list:ENETUNREACH
704  *	ip6_output_list:EMSGSIZE
705  *	ip6_output_list:ENOBUFS
706  *	ip6_output_list:???		[ignorable: mostly IPSEC/firewall/DLIL]
707  */
708 int
tcp_output(struct tcpcb * tp)709 tcp_output(struct tcpcb *tp)
710 {
711 	uint32_t tcp_now_local = os_access_once(tcp_now);
712 	struct inpcb *__single inp = tp->t_inpcb;
713 	struct socket *__single so = inp->inp_socket;
714 	int32_t len, recwin, sendwin, off;
715 	uint32_t max_len = 0;
716 	uint16_t flags;
717 	int error;
718 	mbuf_ref_t m;
719 	struct ip *ip = NULL;
720 	struct ip6_hdr *ip6 = NULL;
721 	struct tcphdr *th;
722 	u_char opt[TCP_MAXOLEN];
723 	unsigned int ipoptlen, optlen, hdrlen;
724 	int idle, sendalot, lost = 0;
725 	int sendalot_cnt = 0;
726 	int i, rack_sack_rxmit = 0;
727 	int tso = 0;
728 	int sack_bytes_rxmt;
729 	tcp_seq old_snd_nxt = 0;
730 	struct sackhole *p;
731 	struct tcp_seg_sent *seg;
732 #if IPSEC
733 	size_t ipsec_optlen = 0;
734 #endif /* IPSEC */
735 	int    idle_time = 0;
736 	struct mbuf *__single packetlist = NULL;
737 	struct mbuf *__single tp_inp_options = inp->inp_depend4.inp4_options;
738 	int isipv6 = inp->inp_vflag & INP_IPV6;
739 	int packchain_listadd = 0;
740 	int so_options = so->so_options;
741 	rtentry_ref_t rt;
742 	u_int32_t svc_flags = 0, allocated_len;
743 #if MPTCP
744 	boolean_t mptcp_acknow;
745 #endif /* MPTCP */
746 	stats_functional_type ifnet_count_type = stats_functional_type_none;
747 	boolean_t sack_rescue_rxt = FALSE;
748 	int sotc = so->so_traffic_class;
749 	boolean_t do_not_compress = FALSE;
750 	boolean_t sack_rxmted = FALSE;
751 
752 	/*
753 	 * Determine length of data that should be transmitted,
754 	 * and flags that will be used.
755 	 * If there is some data or critical controls (SYN, RST)
756 	 * to send, then transmit; otherwise, investigate further.
757 	 */
758 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
759 
760 	/* Since idle_time is signed integer, the following integer subtraction
761 	 * will take care of wrap around of tcp_now
762 	 */
763 	idle_time = tcp_now_local - tp->t_rcvtime;
764 	if (idle && idle_time >= TCP_IDLETIMEOUT(tp)) {
765 		if (CC_ALGO(tp)->after_idle != NULL &&
766 		    ((tp->tcp_cc_index != TCP_CC_ALGO_CUBIC_INDEX &&
767 		    tp->tcp_cc_index != TCP_CC_ALGO_PRAGUE_INDEX) ||
768 		    idle_time >= TCP_CC_CWND_NONVALIDATED_PERIOD)) {
769 			CC_ALGO(tp)->after_idle(tp);
770 			tcp_ccdbg_trace(tp, NULL, TCP_CC_IDLE_TIMEOUT);
771 		}
772 
773 		/*
774 		 * Do some other tasks that need to be done after
775 		 * idle time
776 		 */
777 		if (!SLIST_EMPTY(&tp->t_rxt_segments)) {
778 			tcp_rxtseg_clean(tp);
779 		}
780 
781 		/* If stretch ack was auto-disabled, re-evaluate it */
782 		tcp_cc_after_idle_stretchack(tp);
783 		tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
784 	}
785 	tp->t_flags &= ~TF_LASTIDLE;
786 	if (idle) {
787 		if (tp->t_flags & TF_MORETOCOME) {
788 			tp->t_flags |= TF_LASTIDLE;
789 			idle = 0;
790 		}
791 	}
792 #if MPTCP
793 	if (tp->t_mpflags & TMPF_RESET) {
794 		tcp_check_timer_state(tp);
795 		/*
796 		 * Once a RST has been sent for an MPTCP subflow,
797 		 * the subflow socket stays around until deleted.
798 		 * No packets such as FINs must be sent after RST.
799 		 */
800 		return 0;
801 	}
802 #endif /* MPTCP */
803 
804 again:
805 	tcp_now_local = os_access_once(tcp_now);
806 #if MPTCP
807 	mptcp_acknow = FALSE;
808 
809 	if (so->so_flags & SOF_MP_SUBFLOW && SEQ_LT(tp->snd_nxt, tp->snd_una)) {
810 		os_log_error(mptcp_log_handle, "%s - %lx: snd_nxt is %u and snd_una is %u, cnt %d\n",
811 		    __func__, (unsigned long)VM_KERNEL_ADDRPERM(tp->t_mpsub->mpts_mpte),
812 		    tp->snd_nxt, tp->snd_una, sendalot_cnt);
813 	}
814 #endif
815 	do_not_compress = FALSE;
816 	sendalot_cnt++;
817 
818 	KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_START, 0, 0, 0, 0, 0);
819 
820 	if (isipv6) {
821 		KERNEL_DEBUG(DBG_LAYER_BEG,
822 		    ((inp->inp_fport << 16) | inp->inp_lport),
823 		    (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
824 		    (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
825 		    sendalot, 0, 0);
826 	} else {
827 		KERNEL_DEBUG(DBG_LAYER_BEG,
828 		    ((inp->inp_fport << 16) | inp->inp_lport),
829 		    (((inp->inp_laddr.s_addr & 0xffff) << 16) |
830 		    (inp->inp_faddr.s_addr & 0xffff)),
831 		    sendalot, 0, 0);
832 	}
833 	/*
834 	 * If the route generation id changed, we need to check that our
835 	 * local (source) IP address is still valid. If it isn't either
836 	 * return error or silently do nothing (assuming the address will
837 	 * come back before the TCP connection times out).
838 	 */
839 	rt = inp->inp_route.ro_rt;
840 	if (rt != NULL && ROUTE_UNUSABLE(&tp->t_inpcb->inp_route)) {
841 		struct ifnet *ifp;
842 		struct in_ifaddr *ia = NULL;
843 		struct in6_ifaddr *ia6 = NULL;
844 		int found_srcaddr = 0;
845 
846 		/* disable multipages at the socket */
847 		somultipages(so, FALSE);
848 
849 		/* Disable TSO for the socket until we know more */
850 		tp->t_flags &= ~TF_TSO;
851 
852 		soif2kcl(so, FALSE);
853 
854 		if (isipv6) {
855 			ia6 = ifa_foraddr6(&inp->in6p_laddr);
856 			if (ia6 != NULL) {
857 				found_srcaddr = 1;
858 			}
859 		} else {
860 			ia = ifa_foraddr(inp->inp_laddr.s_addr);
861 			if (ia != NULL) {
862 				found_srcaddr = 1;
863 			}
864 		}
865 
866 		/* check that the source address is still valid */
867 		if (found_srcaddr == 0) {
868 			soevent(so,
869 			    (SO_FILT_HINT_LOCKED | SO_FILT_HINT_NOSRCADDR));
870 
871 			if (tp->t_state >= TCPS_CLOSE_WAIT) {
872 				tcp_drop(tp, EADDRNOTAVAIL);
873 				return EADDRNOTAVAIL;
874 			}
875 
876 			/*
877 			 * Set retransmit  timer if it wasn't set,
878 			 * reset Persist timer and shift register as the
879 			 * advertised peer window may not be valid anymore
880 			 */
881 			if (tp->t_timer[TCPT_REXMT] == 0) {
882 				tp->t_timer[TCPT_REXMT] =
883 				    OFFSET_FROM_START(tp, tp->t_rxtcur);
884 				if (tp->t_timer[TCPT_PERSIST] != 0) {
885 					tp->t_timer[TCPT_PERSIST] = 0;
886 					tp->t_persist_stop = 0;
887 					TCP_RESET_REXMT_STATE(tp);
888 				}
889 			}
890 
891 			if (tp->t_pktlist_head != NULL) {
892 				m_freem_list(tp->t_pktlist_head);
893 			}
894 			TCP_PKTLIST_CLEAR(tp);
895 
896 			/* drop connection if source address isn't available */
897 			if (so->so_flags & SOF_NOADDRAVAIL) {
898 				tcp_drop(tp, EADDRNOTAVAIL);
899 				return EADDRNOTAVAIL;
900 			} else {
901 				TCP_LOG_OUTPUT(tp, "no source address silently ignored");
902 				tcp_check_timer_state(tp);
903 				return 0; /* silently ignore, keep data in socket: address may be back */
904 			}
905 		}
906 		if (ia != NULL) {
907 			ifa_remref(&ia->ia_ifa);
908 		}
909 
910 		if (ia6 != NULL) {
911 			ifa_remref(&ia6->ia_ifa);
912 		}
913 
914 		/*
915 		 * Address is still valid; check for multipages capability
916 		 * again in case the outgoing interface has changed.
917 		 */
918 		RT_LOCK(rt);
919 		if ((ifp = rt->rt_ifp) != NULL) {
920 			somultipages(so, (ifp->if_hwassist & IFNET_MULTIPAGES));
921 			tcp_set_tso(tp, ifp);
922 			soif2kcl(so, (ifp->if_eflags & IFEF_2KCL));
923 			tcp_set_ecn(tp, ifp);
924 		}
925 		if (rt->rt_flags & RTF_UP) {
926 			RT_GENID_SYNC(rt);
927 		}
928 		/*
929 		 * See if we should do MTU discovery. Don't do it if:
930 		 *	1) it is disabled via the sysctl
931 		 *	2) the route isn't up
932 		 *	3) the MTU is locked (if it is, then discovery
933 		 *         has been disabled)
934 		 */
935 
936 		if (!path_mtu_discovery || ((rt != NULL) &&
937 		    (!(rt->rt_flags & RTF_UP) ||
938 		    (rt->rt_rmx.rmx_locks & RTV_MTU)))) {
939 			tp->t_flags &= ~TF_PMTUD;
940 		} else {
941 			tp->t_flags |= TF_PMTUD;
942 		}
943 
944 		RT_UNLOCK(rt);
945 	}
946 
947 	if (rt != NULL) {
948 		ifnet_count_type = IFNET_COUNT_TYPE(rt->rt_ifp);
949 	}
950 
951 	/*
952 	 * If we've recently taken a timeout, snd_max will be greater than
953 	 * snd_nxt.  There may be SACK information that allows us to avoid
954 	 * resending already delivered data.  Adjust snd_nxt accordingly.
955 	 * It is ok to use this function with RACK as well as it is estimating
956 	 * max_len based on a SACK hole.
957 	 */
958 	if (SACK_ENABLED(tp) && SEQ_LT(tp->snd_nxt, tp->snd_max)) {
959 		if (TCP_RACK_ENABLED(tp)) {
960 			/*
961 			 * Calculated in the same manner as when rack_in_recovery
962 			 * is set and new data is transmitted after retransmitted data
963 			 */
964 			int32_t cwin = tp->snd_cwnd - tcp_flight_size(tp);
965 			if (cwin > 0) {
966 				max_len = tcp_rack_adjust(tp, (uint32_t)cwin);
967 			}
968 		} else {
969 			max_len = tcp_sack_adjust(tp);
970 		}
971 	}
972 	sendalot = 0;
973 	off = tp->snd_nxt - tp->snd_una;
974 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
975 
976 	if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
977 		sendwin = min(sendwin, slowlink_wsize);
978 	}
979 
980 	flags = tcp_outflags[tp->t_state];
981 	/*
982 	 * Send any SACK-generated retransmissions.  If we're explicitly
983 	 * trying to send out new data (when sendalot is 1), bypass this
984 	 * function. If we retransmit in fast recovery mode, decrement
985 	 * snd_cwnd, since we're replacing a (future) new transmission
986 	 * with a retransmission now, and we previously incremented
987 	 * snd_cwnd in tcp_input().
988 	 */
989 	/*
990 	 * Still in sack recovery, reset rxmit flag to zero.
991 	 */
992 	rack_sack_rxmit = 0;
993 	sack_bytes_rxmt = 0;
994 	len = 0;
995 	p = NULL;
996 	seg = NULL;
997 
998 	if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp)) {
999 		int32_t cwin = min(tp->snd_wnd, tp->snd_cwnd) - tcp_flight_size(tp);
1000 		if (cwin <= 0 && sack_rxmted == FALSE) {
1001 			/* Allow to clock out at least on per period */
1002 			cwin = tp->t_maxseg;
1003 		}
1004 
1005 		sack_rxmted = TRUE;
1006 		if (cwin < 0) {
1007 			cwin = 0;
1008 		}
1009 
1010 		if (TCP_RACK_ENABLED(tp)) {
1011 			uint16_t rack_seg_len = 0;
1012 			if ((seg = tcp_rack_output(tp, cwin, &rack_seg_len)) != NULL) {
1013 				len = min(cwin, rack_seg_len);
1014 
1015 				if (len > 0) {
1016 					off = seg->start_seq - tp->snd_una;
1017 					rack_sack_rxmit = 1;
1018 					sendalot = 1;
1019 					tcpstat.tcps_rack_rexmits++;
1020 				} else {
1021 					seg = NULL;
1022 				}
1023 			}
1024 		} else if ((p = tcp_sack_output(tp, &sack_bytes_rxmt)) != NULL) {
1025 			/* Do not retransmit SACK segments beyond snd_recover */
1026 			if (SEQ_GT(p->end, tp->snd_recover)) {
1027 				/*
1028 				 * (At least) part of sack hole extends beyond
1029 				 * snd_recover. Check to see if we can rexmit data
1030 				 * for this hole.
1031 				 */
1032 				if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
1033 					/*
1034 					 * Can't rexmit any more data for this hole.
1035 					 * That data will be rexmitted in the next
1036 					 * sack recovery episode, when snd_recover
1037 					 * moves past p->rxmit.
1038 					 */
1039 					p = NULL;
1040 					goto after_sack_rexmit;
1041 				} else {
1042 					/* Can rexmit part of the current hole */
1043 					len = ((int32_t)min(cwin,
1044 					    tp->snd_recover - p->rxmit));
1045 				}
1046 			} else {
1047 				len = ((int32_t)min(cwin, p->end - p->rxmit));
1048 			}
1049 			if (len > 0) {
1050 				off = p->rxmit - tp->snd_una;
1051 				rack_sack_rxmit = 1;
1052 				sendalot = 1;
1053 				/*
1054 				 * Optimization to avoid double retransmission due to SACK recovery
1055 				 * and when tp->snd_nxt points to already retransmitted segments
1056 				 */
1057 				if (SEQ_LT(tp->snd_nxt, tp->snd_max) && SEQ_LEQ(tp->snd_nxt, p->rxmit) &&
1058 				    (uint32_t)len <= max_len) {
1059 					sendalot = 0;
1060 				}
1061 
1062 				tcpstat.tcps_sack_rexmits++;
1063 				tcpstat.tcps_sack_rexmit_bytes +=
1064 				    min(len, tp->t_maxseg);
1065 			} else {
1066 				len = 0;
1067 			}
1068 		}
1069 	}
1070 after_sack_rexmit:
1071 	/*
1072 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
1073 	 * state flags.
1074 	 */
1075 	if (tp->t_flags & TF_NEEDFIN) {
1076 		flags |= TH_FIN;
1077 	}
1078 
1079 	/*
1080 	 * If in persist timeout with window of 0, send 1 byte.
1081 	 * Otherwise, if window is small but nonzero
1082 	 * and timer expired, we will send what we can
1083 	 * and go to transmit state.
1084 	 */
1085 	if (tp->t_flagsext & TF_FORCE) {
1086 		if (sendwin == 0) {
1087 			/*
1088 			 * If we still have some data to send, then
1089 			 * clear the FIN bit.  Usually this would
1090 			 * happen below when it realizes that we
1091 			 * aren't sending all the data.  However,
1092 			 * if we have exactly 1 byte of unsent data,
1093 			 * then it won't clear the FIN bit below,
1094 			 * and if we are in persist state, we wind
1095 			 * up sending the packet without recording
1096 			 * that we sent the FIN bit.
1097 			 *
1098 			 * We can't just blindly clear the FIN bit,
1099 			 * because if we don't have any more data
1100 			 * to send then the probe will be the FIN
1101 			 * itself.
1102 			 */
1103 			if (off < so->so_snd.sb_cc) {
1104 				flags &= ~TH_FIN;
1105 			}
1106 			sendwin = 1;
1107 		} else {
1108 			tp->t_timer[TCPT_PERSIST] = 0;
1109 			tp->t_persist_stop = 0;
1110 			TCP_RESET_REXMT_STATE(tp);
1111 		}
1112 	}
1113 
1114 	/*
1115 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
1116 	 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
1117 	 * a negative length.  This can also occur when TCP opens up
1118 	 * its congestion window while receiving additional duplicate
1119 	 * acks after fast-retransmit because TCP will reset snd_nxt
1120 	 * to snd_max after the fast-retransmit.
1121 	 *
1122 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
1123 	 * be set to snd_una, the offset will be 0, and the length may
1124 	 * wind up 0.
1125 	 *
1126 	 * If sack_rxmit or rack_rxmit is true we are retransmitting from
1127 	 * the scoreboard in which case len is already set.
1128 	 */
1129 	bool rack_in_recovery = TCP_RACK_ENABLED(tp) && IN_FASTRECOVERY(tp);
1130 	if (rack_sack_rxmit == 0) {
1131 		if (sack_bytes_rxmt == 0 && !rack_in_recovery) {
1132 			len = min(so->so_snd.sb_cc, sendwin) - off;
1133 		} else {
1134 			int32_t cwin = tp->snd_cwnd - tcp_flight_size(tp);
1135 			if (cwin < 0) {
1136 				cwin = 0;
1137 			}
1138 			/*
1139 			 * We are inside of a SACK recovery episode and are
1140 			 * sending new data, having retransmitted all the
1141 			 * data possible in the scoreboard.
1142 			 */
1143 			len = min(so->so_snd.sb_cc, tp->snd_wnd) - off;
1144 			/*
1145 			 * Don't remove this (len > 0) check !
1146 			 * We explicitly check for len > 0 here (although it
1147 			 * isn't really necessary), to work around a gcc
1148 			 * optimization issue - to force gcc to compute
1149 			 * len above. Without this check, the computation
1150 			 * of len is bungled by the optimizer.
1151 			 */
1152 			if (len > 0) {
1153 				len = imin(len, cwin);
1154 			} else {
1155 				len = 0;
1156 			}
1157 			/*
1158 			 * At this point SACK recovery can not send any
1159 			 * data from scoreboard or any new data. Check
1160 			 * if we can do a rescue retransmit towards the
1161 			 * tail end of recovery window.
1162 			 * We don't do rescue retransmit for RACK.
1163 			 */
1164 			if (len == 0 && cwin > 0 &&
1165 			    SEQ_LT(tp->snd_fack, tp->snd_recover) &&
1166 			    !(tp->t_flagsext & TF_RESCUE_RXT) && !TCP_RACK_ENABLED(tp)) {
1167 				len = min((tp->snd_recover - tp->snd_fack),
1168 				    tp->t_maxseg);
1169 				len = imin(len, cwin);
1170 				old_snd_nxt = tp->snd_nxt;
1171 				sack_rescue_rxt = TRUE;
1172 				tp->snd_nxt = tp->snd_recover - len;
1173 				/*
1174 				 * If FIN has been sent, snd_max
1175 				 * must have been advanced to cover it.
1176 				 */
1177 				if ((tp->t_flags & TF_SENTFIN) &&
1178 				    tp->snd_max == tp->snd_recover) {
1179 					tp->snd_nxt--;
1180 				}
1181 
1182 				off = tp->snd_nxt - tp->snd_una;
1183 				sendalot = 0;
1184 				tp->t_flagsext |= TF_RESCUE_RXT;
1185 			}
1186 		}
1187 	}
1188 
1189 	if (max_len != 0 && len > 0) {
1190 		len = min(len, max_len);
1191 	}
1192 
1193 	/*
1194 	 * Lop off SYN bit if it has already been sent.  However, if this
1195 	 * is SYN-SENT state and if segment contains data and if we don't
1196 	 * know that foreign host supports TAO, suppress sending segment.
1197 	 */
1198 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
1199 		if (tp->t_state == TCPS_SYN_RECEIVED && TFO_ENABLED(tp) && tp->snd_nxt == tp->snd_una + 1) {
1200 			/* We are sending the SYN again! */
1201 			off--;
1202 			len++;
1203 		} else {
1204 			if (tp->t_state != TCPS_SYN_RECEIVED || TFO_ENABLED(tp)) {
1205 				flags &= ~TH_SYN;
1206 			}
1207 
1208 			off--;
1209 			len++;
1210 			if (len > 0 && tp->t_state == TCPS_SYN_SENT) {
1211 				while (inp->inp_sndinprog_cnt == 0 &&
1212 				    tp->t_pktlist_head != NULL) {
1213 					packetlist = tp->t_pktlist_head;
1214 					packchain_listadd = tp->t_lastchain;
1215 					packchain_sent++;
1216 					TCP_PKTLIST_CLEAR(tp);
1217 
1218 					error = tcp_ip_output(so, tp, packetlist,
1219 					    packchain_listadd, tp_inp_options,
1220 					    (so_options & SO_DONTROUTE),
1221 					    (rack_sack_rxmit || (sack_bytes_rxmt != 0)),
1222 					    isipv6);
1223 				}
1224 
1225 				/*
1226 				 * tcp was closed while we were in ip,
1227 				 * resume close
1228 				 */
1229 				if (inp->inp_sndinprog_cnt == 0 &&
1230 				    (tp->t_flags & TF_CLOSING)) {
1231 					tp->t_flags &= ~TF_CLOSING;
1232 					(void) tcp_close(tp);
1233 				} else {
1234 					tcp_check_timer_state(tp);
1235 				}
1236 				KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END,
1237 				    0, 0, 0, 0, 0);
1238 				return 0;
1239 			}
1240 		}
1241 	}
1242 
1243 	/*
1244 	 * Be careful not to send data and/or FIN on SYN segments.
1245 	 * This measure is needed to prevent interoperability problems
1246 	 * with not fully conformant TCP implementations.
1247 	 *
1248 	 * In case of TFO, we handle the setting of the len in
1249 	 * tcp_tfo_check. In case TFO is not enabled, never ever send
1250 	 * SYN+data.
1251 	 */
1252 	if ((flags & TH_SYN) && !TFO_ENABLED(tp)) {
1253 		len = 0;
1254 		flags &= ~TH_FIN;
1255 	}
1256 
1257 	/*
1258 	 * Don't send a RST with data.
1259 	 */
1260 	if (flags & TH_RST) {
1261 		len = 0;
1262 	}
1263 
1264 	if ((flags & TH_SYN) && tp->t_state <= TCPS_SYN_SENT && TFO_ENABLED(tp)) {
1265 		len = tcp_tfo_check(tp, len);
1266 	}
1267 
1268 	/*
1269 	 * The check here used to be (len < 0). Some times len is zero
1270 	 * when the congestion window is closed and we need to check
1271 	 * if persist timer has to be set in that case. But don't set
1272 	 * persist until connection is established.
1273 	 */
1274 	if (len <= 0 && !(flags & TH_SYN)) {
1275 		/*
1276 		 * If FIN has been sent but not acked,
1277 		 * but we haven't been called to retransmit,
1278 		 * len will be < 0.  Otherwise, window shrank
1279 		 * after we sent into it.  If window shrank to 0,
1280 		 * cancel pending retransmit, pull snd_nxt back
1281 		 * to (closed) window, and set the persist timer
1282 		 * if it isn't already going.  If the window didn't
1283 		 * close completely, just wait for an ACK.
1284 		 */
1285 		len = 0;
1286 		if (sendwin == 0) {
1287 			tp->t_timer[TCPT_REXMT] = 0;
1288 			tp->t_timer[TCPT_PTO] = 0;
1289 			TCP_RESET_REXMT_STATE(tp);
1290 			tp->snd_nxt = tp->snd_una;
1291 			off = 0;
1292 			if (tp->t_timer[TCPT_PERSIST] == 0) {
1293 				tcp_setpersist(tp);
1294 			}
1295 		}
1296 	}
1297 
1298 	/*
1299 	 * Automatic sizing of send socket buffer. Increase the send
1300 	 * socket buffer size if all of the following criteria are met
1301 	 *	1. the receiver has enough buffer space for this data
1302 	 *	2. send buffer is filled to 7/8th with data (so we actually
1303 	 *	   have data to make use of it);
1304 	 *	3. our send window (slow start and congestion controlled) is
1305 	 *	   larger than sent but unacknowledged data in send buffer.
1306 	 */
1307 	if (!INP_WAIT_FOR_IF_FEEDBACK(inp) && !IN_FASTRECOVERY(tp) &&
1308 	    (so->so_snd.sb_flags & (SB_AUTOSIZE | SB_TRIM)) == SB_AUTOSIZE) {
1309 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
1310 		    so->so_snd.sb_cc >= (so->so_snd.sb_hiwat / 8 * 7) &&
1311 		    sendwin >= (so->so_snd.sb_cc - (tp->snd_nxt - tp->snd_una))) {
1312 			if (sbreserve(&so->so_snd,
1313 			    min(so->so_snd.sb_hiwat + tcp_autosndbuf_inc,
1314 			    tcp_autosndbuf_max)) == 1) {
1315 				so->so_snd.sb_idealsize = so->so_snd.sb_hiwat;
1316 			}
1317 		}
1318 	}
1319 
1320 	/*
1321 	 * Truncate to the maximum segment length or enable TCP Segmentation
1322 	 * Offloading (if supported by hardware) and ensure that FIN is removed
1323 	 * if the length no longer contains the last data byte.
1324 	 *
1325 	 * TSO may only be used if we are in a pure bulk sending state.
1326 	 * The presence of TCP-MD5, SACK retransmits, SACK advertizements,
1327 	 * filters and IP options, as well as disabling hardware checksum
1328 	 * offload prevent using TSO.  With TSO the TCP header is the same
1329 	 * (except for the sequence number) for all generated packets.  This
1330 	 * makes it impossible to transmit any options which vary per generated
1331 	 * segment or packet.
1332 	 *
1333 	 * The length of TSO bursts is limited to TCP_MAXWIN.  That limit and
1334 	 * removal of FIN (if not already catched here) are handled later after
1335 	 * the exact length of the TCP options are known.
1336 	 */
1337 #if IPSEC
1338 	/*
1339 	 * Pre-calculate here as we save another lookup into the darknesses
1340 	 * of IPsec that way and can actually decide if TSO is ok.
1341 	 */
1342 	if (ipsec_bypass == 0) {
1343 		ipsec_optlen = ipsec_hdrsiz_tcp(tp);
1344 	}
1345 #endif
1346 	if (len > tp->t_maxseg) {
1347 		if ((tp->t_flags & TF_TSO) && tcp_do_tso && hwcksum_tx &&
1348 		    kipf_count == 0 &&
1349 		    tp->rcv_numsacks == 0 && rack_sack_rxmit == 0 &&
1350 		    sack_bytes_rxmt == 0 &&
1351 		    inp->inp_options == NULL &&
1352 		    inp->in6p_options == NULL
1353 #if IPSEC
1354 		    && ipsec_optlen == 0
1355 #endif
1356 		    ) {
1357 			tso = 1;
1358 			sendalot = 0;
1359 		} else {
1360 			len = tp->t_maxseg;
1361 			sendalot = 1;
1362 			tso = 0;
1363 		}
1364 	} else {
1365 		tso = 0;
1366 	}
1367 
1368 	/* Send one segment or less as a tail loss probe */
1369 	if (tp->t_flagsext & TF_SENT_TLPROBE) {
1370 		len = min(len, tp->t_maxseg);
1371 		sendalot = 0;
1372 		tso = 0;
1373 	}
1374 
1375 #if MPTCP
1376 	if (so->so_flags & SOF_MP_SUBFLOW && off < 0) {
1377 		os_log_error(mptcp_log_handle, "%s - %lx: offset is negative! len %d off %d\n",
1378 		    __func__, (unsigned long)VM_KERNEL_ADDRPERM(tp->t_mpsub->mpts_mpte),
1379 		    len, off);
1380 	}
1381 
1382 	if ((so->so_flags & SOF_MP_SUBFLOW) &&
1383 	    !(tp->t_mpflags & TMPF_TCP_FALLBACK)) {
1384 		int newlen = len;
1385 		struct mptcb *mp_tp = tptomptp(tp);
1386 		if (tp->t_state >= TCPS_ESTABLISHED &&
1387 		    (tp->t_mpflags & TMPF_SND_MPPRIO ||
1388 		    tp->t_mpflags & TMPF_SND_REM_ADDR ||
1389 		    tp->t_mpflags & TMPF_SND_MPFAIL ||
1390 		    (tp->t_mpflags & TMPF_SND_KEYS &&
1391 		    mp_tp->mpt_version == MPTCP_VERSION_0) ||
1392 		    tp->t_mpflags & TMPF_SND_JACK ||
1393 		    tp->t_mpflags & TMPF_MPTCP_ECHO_ADDR)) {
1394 			if (len > 0) {
1395 				len = 0;
1396 				tso = 0;
1397 			}
1398 			/*
1399 			 * On a new subflow, don't try to send again, because
1400 			 * we are still waiting for the fourth ack.
1401 			 */
1402 			if (!(tp->t_mpflags & TMPF_PREESTABLISHED)) {
1403 				sendalot = 1;
1404 			}
1405 			mptcp_acknow = TRUE;
1406 		} else {
1407 			mptcp_acknow = FALSE;
1408 		}
1409 		/*
1410 		 * The contiguous bytes in the subflow socket buffer can be
1411 		 * discontiguous at the MPTCP level. Since only one DSS
1412 		 * option can be sent in one packet, reduce length to match
1413 		 * the contiguous MPTCP level. Set sendalot to send remainder.
1414 		 */
1415 		if (len > 0 && off >= 0) {
1416 			newlen = mptcp_adj_sendlen(so, off);
1417 		}
1418 
1419 		if (newlen < len) {
1420 			len = newlen;
1421 			if (len <= tp->t_maxseg) {
1422 				tso = 0;
1423 			}
1424 		}
1425 	}
1426 #endif /* MPTCP */
1427 
1428 	if (rack_sack_rxmit) {
1429 		if (TCP_RACK_ENABLED(tp)) {
1430 			if (SEQ_LT(seg->start_seq + len, tp->snd_una + so->so_snd.sb_cc)) {
1431 				flags &= ~TH_FIN;
1432 			}
1433 		} else {
1434 			if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc)) {
1435 				flags &= ~TH_FIN;
1436 			}
1437 		}
1438 	} else {
1439 		if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc)) {
1440 			flags &= ~TH_FIN;
1441 		}
1442 	}
1443 	/*
1444 	 * Compare available window to amount of window
1445 	 * known to peer (as advertised window less
1446 	 * next expected input).  If the difference is at least two
1447 	 * max size segments, or at least 25% of the maximum possible
1448 	 * window, then want to send a window update to peer.
1449 	 */
1450 	recwin = tcp_sbspace(tp);
1451 
1452 	if (!(so->so_flags & SOF_MP_SUBFLOW)) {
1453 		if (recwin < (int32_t)(so->so_rcv.sb_hiwat / 4) &&
1454 		    recwin < (int)tp->t_maxseg) {
1455 			recwin = 0;
1456 		}
1457 	} else {
1458 		struct mptcb *mp_tp = tptomptp(tp);
1459 		struct socket *mp_so = mptetoso(mp_tp->mpt_mpte);
1460 
1461 		if (recwin < (int32_t)(mp_so->so_rcv.sb_hiwat / 4) &&
1462 		    recwin < (int)tp->t_maxseg) {
1463 			recwin = 0;
1464 		}
1465 	}
1466 
1467 #if TRAFFIC_MGT
1468 	if (tcp_recv_bg == 1 || IS_TCP_RECV_BG(so)) {
1469 		/*
1470 		 * Timestamp MUST be supported to use rledbat unless we haven't
1471 		 * yet negotiated it.
1472 		 */
1473 		if (TCP_RLEDBAT_ENABLED(tp) || (tcp_rledbat && tp->t_state <
1474 		    TCPS_ESTABLISHED)) {
1475 			if (recwin > 0 && tcp_cc_rledbat.get_rlwin != NULL) {
1476 				/* Min of flow control window and rledbat window */
1477 				recwin = imin(recwin, tcp_cc_rledbat.get_rlwin(tp));
1478 			}
1479 		} else if (recwin > 0 && tcp_recv_throttle(tp)) {
1480 			uint32_t min_iaj_win = tcp_min_iaj_win * tp->t_maxseg;
1481 			uint32_t bg_rwintop = tp->rcv_adv;
1482 			if (SEQ_LT(bg_rwintop, tp->rcv_nxt + min_iaj_win)) {
1483 				bg_rwintop =  tp->rcv_nxt + min_iaj_win;
1484 			}
1485 			recwin = imin((int32_t)(bg_rwintop - tp->rcv_nxt),
1486 			    recwin);
1487 			if (recwin < 0) {
1488 				recwin = 0;
1489 			}
1490 		}
1491 	}
1492 #endif /* TRAFFIC_MGT */
1493 
1494 	if (recwin > (int32_t)(TCP_MAXWIN << tp->rcv_scale)) {
1495 		recwin = (int32_t)(TCP_MAXWIN << tp->rcv_scale);
1496 	}
1497 
1498 	if (!(so->so_flags & SOF_MP_SUBFLOW)) {
1499 		if (recwin < (int32_t)(tp->rcv_adv - tp->rcv_nxt)) {
1500 			recwin = (int32_t)(tp->rcv_adv - tp->rcv_nxt);
1501 		}
1502 	} else {
1503 		struct mptcb *mp_tp = tptomptp(tp);
1504 		int64_t recwin_announced = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
1505 
1506 		/* Don't remove what we announced at the MPTCP-layer */
1507 		VERIFY(recwin_announced < INT32_MAX && recwin_announced > INT32_MIN);
1508 		if (recwin < (int32_t)recwin_announced) {
1509 			recwin = (int32_t)recwin_announced;
1510 		}
1511 	}
1512 
1513 	/*
1514 	 * Sender silly window avoidance.   We transmit under the following
1515 	 * conditions when len is non-zero:
1516 	 *
1517 	 *	- we've timed out (e.g. persist timer)
1518 	 *	- we need to retransmit
1519 	 *	- We have a full segment (or more with TSO)
1520 	 *	- This is the last buffer in a write()/send() and we are
1521 	 *	  either idle or running NODELAY
1522 	 *	- we have more then 1/2 the maximum send window's worth of
1523 	 *	  data (receiver may be limited the window size)
1524 	 */
1525 	if (len) {
1526 		if (tp->t_flagsext & TF_FORCE) {
1527 			goto send;
1528 		}
1529 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
1530 			if (TCP_RACK_ENABLED(tp) && rack_sack_rxmit == 0) {
1531 				len = min(len, tp->snd_max - tp->snd_nxt);
1532 			}
1533 			goto send;
1534 		}
1535 		if (rack_sack_rxmit) {
1536 			goto send;
1537 		}
1538 
1539 		/*
1540 		 * If this here is the first segment after SYN/ACK and TFO
1541 		 * is being used, then we always send it, regardless of Nagle,...
1542 		 */
1543 		if (tp->t_state == TCPS_SYN_RECEIVED &&
1544 		    TFO_ENABLED(tp) &&
1545 		    (tp->t_tfo_flags & TFO_F_COOKIE_VALID) &&
1546 		    tp->snd_nxt == tp->iss + 1) {
1547 			goto send;
1548 		}
1549 
1550 		/*
1551 		 * Send new data on the connection only if it is
1552 		 * not flow controlled
1553 		 */
1554 		if (!INP_WAIT_FOR_IF_FEEDBACK(inp) ||
1555 		    tp->t_state != TCPS_ESTABLISHED) {
1556 			if (off + len == tp->snd_wnd) {
1557 				/* We are limited by the receiver's window... */
1558 				if (tp->t_rcvwnd_limited_start_time == 0) {
1559 					tp->t_rcvwnd_limited_start_time = net_uptime_us();
1560 				}
1561 			} else {
1562 				/* We are no more limited by the receiver's window... */
1563 				if (tp->t_rcvwnd_limited_start_time != 0) {
1564 					uint64_t now = net_uptime_us();
1565 
1566 					ASSERT(now >= tp->t_rcvwnd_limited_start_time);
1567 
1568 					tp->t_rcvwnd_limited_total_time += (now - tp->t_rcvwnd_limited_start_time);
1569 
1570 					tp->t_rcvwnd_limited_start_time = 0;
1571 				}
1572 			}
1573 
1574 			if (len >= tp->t_maxseg) {
1575 				goto send;
1576 			}
1577 
1578 			if (!(tp->t_flags & TF_MORETOCOME) &&
1579 			    (idle || tp->t_flags & TF_NODELAY ||
1580 			    (tp->t_flags & TF_MAXSEGSNT) ||
1581 			    ALLOW_LIMITED_TRANSMIT(tp)) &&
1582 			    (tp->t_flags & TF_NOPUSH) == 0 &&
1583 			    (len + off >= so->so_snd.sb_cc ||
1584 			    /*
1585 			     * MPTCP needs to respect the DSS-mappings. So, it
1586 			     * may be sending data that *could* have been
1587 			     * coalesced, but cannot because of
1588 			     * mptcp_adj_sendlen().
1589 			     */
1590 			    so->so_flags & SOF_MP_SUBFLOW)) {
1591 				goto send;
1592 			}
1593 			if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
1594 				goto send;
1595 			}
1596 		} else {
1597 			tcpstat.tcps_fcholdpacket++;
1598 		}
1599 	}
1600 
1601 	if (recwin > 0) {
1602 		/*
1603 		 * "adv" is the amount we can increase the window,
1604 		 * taking into account that we are limited by
1605 		 * TCP_MAXWIN << tp->rcv_scale.
1606 		 */
1607 		int32_t adv, oldwin = 0;
1608 		adv = imin(recwin, (int)TCP_MAXWIN << tp->rcv_scale) -
1609 		    (tp->rcv_adv - tp->rcv_nxt);
1610 
1611 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
1612 			oldwin = tp->rcv_adv - tp->rcv_nxt;
1613 		}
1614 
1615 		if (tcp_ack_strategy == TCP_ACK_STRATEGY_LEGACY) {
1616 			if (adv >= (int32_t) (2 * tp->t_maxseg)) {
1617 				/*
1618 				 * Update only if the resulting scaled value of
1619 				 * the window changed, or if there is a change in
1620 				 * the sequence since the last ack. This avoids
1621 				 * what appears as dupe ACKS (see rdar://5640997)
1622 				 *
1623 				 * If streaming is detected avoid sending too many
1624 				 * window updates. We will depend on the delack
1625 				 * timer to send a window update when needed.
1626 				 *
1627 				 * If there is more data to read, don't send an ACK.
1628 				 * Otherwise we will end up sending many ACKs if the
1629 				 * application is doing micro-reads.
1630 				 */
1631 				if (!(tp->t_flags & TF_STRETCHACK) &&
1632 				    (tp->last_ack_sent != tp->rcv_nxt ||
1633 				    ((oldwin + adv) >> tp->rcv_scale) >
1634 				    (oldwin >> tp->rcv_scale))) {
1635 					goto send;
1636 				}
1637 			}
1638 		} else {
1639 			if (adv >= (int32_t) (2 * tp->t_maxseg)) {
1640 				/*
1641 				 * ACK every second full-sized segment, if the
1642 				 * ACK is advancing or the window becomes bigger
1643 				 */
1644 				if (so->so_rcv.sb_cc < so->so_rcv.sb_lowat &&
1645 				    (tp->last_ack_sent != tp->rcv_nxt ||
1646 				    ((oldwin + adv) >> tp->rcv_scale) >
1647 				    (oldwin >> tp->rcv_scale))) {
1648 					goto send;
1649 				}
1650 			} else if (tp->t_flags & TF_DELACK) {
1651 				/*
1652 				 * If we delayed the ACK and the window
1653 				 * is not advancing by a lot (< 2MSS), ACK
1654 				 * immediately if the last incoming packet had
1655 				 * the push flag set and we emptied the buffer.
1656 				 *
1657 				 * This takes care of a sender doing small
1658 				 * repeated writes with Nagle enabled.
1659 				 */
1660 				if (so->so_rcv.sb_cc == 0 &&
1661 				    tp->last_ack_sent != tp->rcv_nxt &&
1662 				    (tp->t_flagsext & TF_LAST_IS_PSH)) {
1663 					goto send;
1664 				}
1665 			}
1666 		}
1667 		if (4 * adv >= (int32_t) so->so_rcv.sb_hiwat) {
1668 			goto send;
1669 		}
1670 
1671 		/*
1672 		 * Make sure that the delayed ack timer is set if
1673 		 * we delayed sending a window update because of
1674 		 * streaming detection.
1675 		 */
1676 		if (tcp_ack_strategy == TCP_ACK_STRATEGY_LEGACY &&
1677 		    (tp->t_flags & TF_STRETCHACK) &&
1678 		    !(tp->t_flags & TF_DELACK)) {
1679 			tp->t_flags |= TF_DELACK;
1680 			tp->t_timer[TCPT_DELACK] =
1681 			    OFFSET_FROM_START(tp, tcp_delack);
1682 		}
1683 	}
1684 
1685 	/*
1686 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data. ACKNOW
1687 	 * is also a catch-all for the retransmit timer timeout case.
1688 	 */
1689 	if (tp->t_flags & TF_ACKNOW) {
1690 		if (tp->t_forced_acks > 0) {
1691 			tp->t_forced_acks--;
1692 		}
1693 		goto send;
1694 	}
1695 	if ((flags & TH_RST) || (flags & TH_SYN)) {
1696 		goto send;
1697 	}
1698 	if (SEQ_GT(tp->snd_up, tp->snd_una)) {
1699 		goto send;
1700 	}
1701 #if MPTCP
1702 	if (mptcp_acknow) {
1703 		goto send;
1704 	}
1705 #endif /* MPTCP */
1706 	/*
1707 	 * If our state indicates that FIN should be sent
1708 	 * and we have not yet done so, then we need to send.
1709 	 */
1710 	if ((flags & TH_FIN) &&
1711 	    (!(tp->t_flags & TF_SENTFIN) || tp->snd_nxt == tp->snd_una)) {
1712 		goto send;
1713 	}
1714 	/*
1715 	 * In SACK, it is possible for tcp_output to fail to send a segment
1716 	 * after the retransmission timer has been turned off.  Make sure
1717 	 * that the retransmission timer is set.
1718 	 */
1719 	if (SACK_ENABLED(tp) && (tp->t_state >= TCPS_ESTABLISHED) &&
1720 	    SEQ_GT(tp->snd_max, tp->snd_una) &&
1721 	    tp->t_timer[TCPT_REXMT] == 0 &&
1722 	    tp->t_timer[TCPT_PERSIST] == 0) {
1723 		tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
1724 		    tp->t_rxtcur);
1725 		goto just_return;
1726 	}
1727 	/*
1728 	 * TCP window updates are not reliable, rather a polling protocol
1729 	 * using ``persist'' packets is used to insure receipt of window
1730 	 * updates.  The three ``states'' for the output side are:
1731 	 *	idle			not doing retransmits or persists
1732 	 *	persisting		to move a small or zero window
1733 	 *	(re)transmitting	and thereby not persisting
1734 	 *
1735 	 * tp->t_timer[TCPT_PERSIST]
1736 	 *	is set when we are in persist state.
1737 	 * tp->t_force
1738 	 *	is set when we are called to send a persist packet.
1739 	 * tp->t_timer[TCPT_REXMT]
1740 	 *	is set when we are retransmitting
1741 	 * The output side is idle when both timers are zero.
1742 	 *
1743 	 * If send window is too small, there is data to transmit, and no
1744 	 * retransmit or persist is pending, then go to persist state.
1745 	 * If nothing happens soon, send when timer expires:
1746 	 * if window is nonzero, transmit what we can,
1747 	 * otherwise force out a byte.
1748 	 */
1749 	if (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&
1750 	    tp->t_timer[TCPT_PERSIST] == 0) {
1751 		TCP_RESET_REXMT_STATE(tp);
1752 		tcp_setpersist(tp);
1753 	}
1754 just_return:
1755 	/*
1756 	 * If there is no reason to send a segment, just return.
1757 	 * but if there is some packets left in the packet list, send them now.
1758 	 */
1759 	while (inp->inp_sndinprog_cnt == 0 &&
1760 	    tp->t_pktlist_head != NULL) {
1761 		packetlist = tp->t_pktlist_head;
1762 		packchain_listadd = tp->t_lastchain;
1763 		packchain_sent++;
1764 		TCP_PKTLIST_CLEAR(tp);
1765 
1766 		error = tcp_ip_output(so, tp, packetlist,
1767 		    packchain_listadd,
1768 		    tp_inp_options, (so_options & SO_DONTROUTE),
1769 		    (rack_sack_rxmit || (sack_bytes_rxmt != 0)), isipv6);
1770 	}
1771 	/* tcp was closed while we were in ip; resume close */
1772 	if (inp->inp_sndinprog_cnt == 0 &&
1773 	    (tp->t_flags & TF_CLOSING)) {
1774 		tp->t_flags &= ~TF_CLOSING;
1775 		(void) tcp_close(tp);
1776 	} else {
1777 		tcp_check_timer_state(tp);
1778 	}
1779 	KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
1780 	return 0;
1781 
1782 send:
1783 	/*
1784 	 * Set TF_MAXSEGSNT flag if the segment size is greater than
1785 	 * the max segment size.
1786 	 */
1787 	if (len > 0) {
1788 		do_not_compress = TRUE;
1789 
1790 		if (len >= tp->t_maxseg) {
1791 			tp->t_flags |= TF_MAXSEGSNT;
1792 		} else {
1793 			tp->t_flags &= ~TF_MAXSEGSNT;
1794 		}
1795 	}
1796 	/*
1797 	 * If we are connected and no segment has been ACKed or SACKed yet and we
1798 	 * hit a retransmission timeout, then we should disable AccECN option
1799 	 * for the rest of the connection.
1800 	 */
1801 	if (TCP_ACC_ECN_ON(tp) && tp->t_state == TCPS_ESTABLISHED &&
1802 	    tp->snd_una == tp->iss + 1 && (tp->snd_fack == tp->iss)
1803 	    && tp->t_rxtshift > 0) {
1804 		if ((tp->ecn_flags & TE_RETRY_WITHOUT_ACO) == 0) {
1805 			tp->ecn_flags |= TE_RETRY_WITHOUT_ACO;
1806 		}
1807 	}
1808 	/*
1809 	 * Before ESTABLISHED, force sending of initial options
1810 	 * unless TCP set not to do any options.
1811 	 * NOTE: we assume that the IP/TCP header plus TCP options
1812 	 * always fit in a single mbuf, leaving room for a maximum
1813 	 * link header, i.e.
1814 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
1815 	 */
1816 	optlen = 0;
1817 	if (isipv6) {
1818 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1819 	} else {
1820 		hdrlen = sizeof(struct tcpiphdr);
1821 	}
1822 	if (flags & TH_SYN) {
1823 		tp->snd_nxt = tp->iss;
1824 		tp->snd_fack = tp->iss;
1825 		if ((tp->t_flags & TF_NOOPT) == 0) {
1826 			u_short mss;
1827 
1828 			opt[0] = TCPOPT_MAXSEG;
1829 			opt[1] = TCPOLEN_MAXSEG;
1830 			mss = htons((u_short) tcp_mssopt(tp));
1831 			(void)memcpy(opt + 2, &mss, sizeof(mss));
1832 			optlen = TCPOLEN_MAXSEG;
1833 
1834 			if ((tp->t_flags & TF_REQ_SCALE) &&
1835 			    ((flags & TH_ACK) == 0 ||
1836 			    (tp->t_flags & TF_RCVD_SCALE))) {
1837 				*((u_int32_t *)(void *)(opt + optlen)) = htonl(
1838 					TCPOPT_NOP << 24 |
1839 					        TCPOPT_WINDOW << 16 |
1840 					        TCPOLEN_WINDOW << 8 |
1841 					        tp->request_r_scale);
1842 				optlen += 4;
1843 			}
1844 #if MPTCP
1845 			if (mptcp_enable && (so->so_flags & SOF_MP_SUBFLOW)) {
1846 				optlen = mptcp_setup_syn_opts(so, opt, optlen);
1847 			}
1848 #endif /* MPTCP */
1849 		}
1850 	}
1851 
1852 	/*
1853 	 * Send a timestamp and echo-reply if this is a SYN and our side
1854 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
1855 	 * and our peer have sent timestamps in our SYN's.
1856 	 */
1857 	if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
1858 	    (flags & TH_RST) == 0 &&
1859 	    ((flags & TH_ACK) == 0 ||
1860 	    (tp->t_flags & TF_RCVD_TSTMP))) {
1861 		u_int32_t *lp = (u_int32_t *)(void *)(opt + optlen);
1862 
1863 		/* Form timestamp option as shown in appendix A of RFC 1323. */
1864 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1865 		*lp++ = htonl(tcp_now_local + tp->t_ts_offset);
1866 		*lp   = htonl(tp->ts_recent);
1867 		optlen += TCPOLEN_TSTAMP_APPA;
1868 	}
1869 
1870 	if (SACK_ENABLED(tp) && ((tp->t_flags & TF_NOOPT) == 0)) {
1871 		/*
1872 		 * Tack on the SACK permitted option *last*.
1873 		 * And do padding of options after tacking this on.
1874 		 * This is because of MSS, TS, WinScale and Signatures are
1875 		 * all present, we have just 2 bytes left for the SACK
1876 		 * permitted option, which is just enough.
1877 		 */
1878 		/*
1879 		 * If this is the first SYN of connection (not a SYN
1880 		 * ACK), include SACK permitted option.  If this is a
1881 		 * SYN ACK, include SACK permitted option if peer has
1882 		 * already done so. This is only for active connect,
1883 		 * since the syncache takes care of the passive connect.
1884 		 */
1885 		if ((flags & TH_SYN) &&
1886 		    (!(flags & TH_ACK) || (tp->t_flags & TF_SACK_PERMIT))) {
1887 			u_char *bp;
1888 			bp = (u_char *)opt + optlen;
1889 
1890 			*bp++ = TCPOPT_SACK_PERMITTED;
1891 			*bp++ = TCPOLEN_SACK_PERMITTED;
1892 			optlen += TCPOLEN_SACK_PERMITTED;
1893 		}
1894 	}
1895 #if MPTCP
1896 	if (so->so_flags & SOF_MP_SUBFLOW) {
1897 		/*
1898 		 * Its important to piggyback acks with data as ack only packets
1899 		 * may get lost and data packets that don't send Data ACKs
1900 		 * still advance the subflow level ACK and therefore make it
1901 		 * hard for the remote end to recover in low cwnd situations.
1902 		 */
1903 		if (len != 0) {
1904 			tp->t_mpflags |= (TMPF_SEND_DSN |
1905 			    TMPF_MPTCP_ACKNOW);
1906 		} else {
1907 			tp->t_mpflags |= TMPF_MPTCP_ACKNOW;
1908 		}
1909 		optlen = mptcp_setup_opts(tp, off, &opt[0], optlen, flags,
1910 		    len, &mptcp_acknow, &do_not_compress);
1911 		tp->t_mpflags &= ~TMPF_SEND_DSN;
1912 	}
1913 #endif /* MPTCP */
1914 
1915 	if (TFO_ENABLED(tp) && !(tp->t_flags & TF_NOOPT) &&
1916 	    (flags & (TH_SYN | TH_ACK)) == TH_SYN) {
1917 		optlen += tcp_tfo_write_cookie(tp, optlen, len, opt);
1918 	}
1919 
1920 	if (TFO_ENABLED(tp) &&
1921 	    (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
1922 	    (tp->t_tfo_flags & TFO_F_OFFER_COOKIE)) {
1923 		optlen += tcp_tfo_write_cookie_rep(tp, optlen, opt);
1924 	}
1925 
1926 	if (SACK_ENABLED(tp) && ((tp->t_flags & TF_NOOPT) == 0)) {
1927 		/*
1928 		 * Send SACKs if necessary.  This should be the last
1929 		 * option processed.  Only as many SACKs are sent as
1930 		 * are permitted by the maximum options size.
1931 		 *
1932 		 * In general, SACK blocks consume 8*n+2 bytes.
1933 		 * So a full size SACK blocks option is 34 bytes
1934 		 * (to generate 4 SACK blocks).  At a minimum,
1935 		 * we need 10 bytes (to generate 1 SACK block).
1936 		 * If TCP Timestamps (12 bytes) and TCP Signatures
1937 		 * (18 bytes) are both present, we'll just have
1938 		 * 10 bytes for SACK options 40 - (12 + 18).
1939 		 */
1940 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
1941 		    (tp->t_flags & TF_SACK_PERMIT) &&
1942 		    (tp->rcv_numsacks > 0 || TCP_SEND_DSACK_OPT(tp)) &&
1943 		    MAX_TCPOPTLEN - optlen >= TCPOLEN_SACK + 2) {
1944 			unsigned int sackoptlen = 0;
1945 			int nsack, padlen;
1946 			u_char *bp = (u_char *)opt + optlen;
1947 			u_int32_t *lp;
1948 
1949 			nsack = (MAX_TCPOPTLEN - optlen - 2) / TCPOLEN_SACK;
1950 			/*
1951 			 * Send lesser SACK blocks when we want
1952 			 * to send the smallest recommended AccECN Option
1953 			 * if the space wouldn't permit sending all blocks.
1954 			 */
1955 			if (nsack > 2 && TCP_ACC_ECN_ON(tp) &&
1956 			    (tp->ecn_flags & TE_RETRY_WITHOUT_ACO) == 0 &&
1957 			    tp->ecn_flags & (TE_ACO_ECT1 | TE_ACO_ECT0)) {
1958 				nsack--;
1959 			}
1960 			nsack = min(nsack, (tp->rcv_numsacks +
1961 			    (TCP_SEND_DSACK_OPT(tp) ? 1 : 0)));
1962 			sackoptlen = (2 + nsack * TCPOLEN_SACK);
1963 			VERIFY(sackoptlen < UINT8_MAX);
1964 
1965 			/*
1966 			 * First we need to pad options so that the
1967 			 * SACK blocks can start at a 4-byte boundary
1968 			 * (sack option and length are at a 2 byte offset).
1969 			 */
1970 			padlen = (MAX_TCPOPTLEN - optlen - sackoptlen) % 4;
1971 			optlen += padlen;
1972 			while (padlen-- > 0) {
1973 				*bp++ = TCPOPT_NOP;
1974 			}
1975 
1976 			tcpstat.tcps_sack_send_blocks++;
1977 			*bp++ = TCPOPT_SACK;
1978 			*bp++ = (uint8_t)sackoptlen;
1979 			lp = (u_int32_t *)(void *)bp;
1980 
1981 			/*
1982 			 * First block of SACK option should represent
1983 			 * DSACK. Prefer to send SACK information if there
1984 			 * is space for only one SACK block. This will
1985 			 * allow for faster recovery.
1986 			 */
1987 			if (TCP_SEND_DSACK_OPT(tp) && nsack > 0 &&
1988 			    (tp->rcv_numsacks == 0 || nsack > 1)) {
1989 				*lp++ = htonl(tp->t_dsack_lseq);
1990 				*lp++ = htonl(tp->t_dsack_rseq);
1991 				tcpstat.tcps_dsack_sent++;
1992 				tp->t_dsack_sent++;
1993 				nsack--;
1994 			}
1995 			VERIFY(nsack == 0 || tp->rcv_numsacks >= nsack);
1996 			for (i = 0; i < nsack; i++) {
1997 				struct sackblk sack = tp->sackblks[i];
1998 				*lp++ = htonl(sack.start);
1999 				*lp++ = htonl(sack.end);
2000 			}
2001 			optlen += sackoptlen;
2002 
2003 			/* Make sure we didn't write too much */
2004 			VERIFY((u_char *)lp - opt <= MAX_TCPOPTLEN);
2005 		}
2006 	}
2007 
2008 	/*
2009 	 * AccECN option - after SACK
2010 	 * Don't send on <SYN>,
2011 	 * send only on <SYN,ACK> before ACCECN is negotiated or
2012 	 * when doing an AccECN session. Don't send AccECN option
2013 	 * if retransmitting a SYN-ACK or a data segment
2014 	 */
2015 	if ((TCP_ACC_ECN_ON(tp) ||
2016 	    (TCP_ACC_ECN_ENABLED(tp) && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)))
2017 	    && ((tp->ecn_flags & TE_RETRY_WITHOUT_ACO) == 0)) {
2018 		uint32_t *lp = (uint32_t *)(void *)(opt + optlen);
2019 		/* lp will become outdated after options are added */
2020 		tcp_add_accecn_option(tp, flags, lp, (uint8_t *)&optlen);
2021 	}
2022 	/* Pad TCP options to a 4 byte boundary */
2023 	if (optlen < MAX_TCPOPTLEN && (optlen % sizeof(u_int32_t))) {
2024 		int pad = sizeof(u_int32_t) - (optlen % sizeof(u_int32_t));
2025 		u_char *bp = (u_char *)opt + optlen;
2026 
2027 		optlen += pad;
2028 		while (pad) {
2029 			*bp++ = TCPOPT_EOL;
2030 			pad--;
2031 		}
2032 	}
2033 
2034 	/*
2035 	 * For Accurate ECN, send ACE flag based on r.cep, if
2036 	 * We have completed handshake and are in ESTABLISHED state, and
2037 	 * This is not the final ACK of 3WHS.
2038 	 */
2039 	if (TCP_ACC_ECN_ON(tp) && TCPS_HAVEESTABLISHED(tp->t_state) &&
2040 	    (tp->ecn_flags & TE_ACE_FINAL_ACK_3WHS) == 0) {
2041 		uint8_t ace = tp->t_aecn.t_rcv_ce_packets & TCP_ACE_MASK;
2042 		if (ace & 0x01) {
2043 			flags |= TH_ECE;
2044 		} else {
2045 			flags &= ~TH_ECE;
2046 		}
2047 		if (ace & 0x02) {
2048 			flags |= TH_CWR;
2049 		} else {
2050 			flags &= ~TH_CWR;
2051 		}
2052 		if (ace & 0x04) {
2053 			flags |= TH_AE;
2054 		} else {
2055 			flags &= ~TH_AE;
2056 		}
2057 	}
2058 
2059 	/*
2060 	 * RFC 3168 states that:
2061 	 * - If you ever sent an ECN-setup SYN/SYN-ACK you must be prepared
2062 	 * to handle the TCP ECE flag, even if you also later send a
2063 	 * non-ECN-setup SYN/SYN-ACK.
2064 	 * - If you ever send a non-ECN-setup SYN/SYN-ACK, you must not set
2065 	 * the ip ECT flag.
2066 	 *
2067 	 * It is not clear how the ECE flag would ever be set if you never
2068 	 * set the IP ECT flag on outbound packets. All the same, we use
2069 	 * the TE_SETUPSENT to indicate that we have committed to handling
2070 	 * the TCP ECE flag correctly. We use the TE_SENDIPECT to indicate
2071 	 * whether or not we should set the IP ECT flag on outbound packet
2072 	 *
2073 	 * For a SYN-ACK, send an ECN setup SYN-ACK
2074 	 *
2075 	 * Below we send ECN for three different handhshake states:
2076 	 * 1. Server received SYN and is sending a SYN-ACK (state->TCPS_SYN_RECEIVED)
2077 	 *    - both classic and Accurate ECN have special encoding
2078 	 * 2. Client is sending SYN packet (state->SYN_SENT)
2079 	 *    - both classic and Accurate ECN have special encoding
2080 	 * 3. Client is sending final ACK of 3WHS (state->ESTABLISHED)
2081 	 *    - Only Accurate ECN has special encoding
2082 	 */
2083 	if ((flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) &&
2084 	    (tp->ecn_flags & TE_ENABLE_ECN)) {
2085 		/* Server received either legacy or Accurate ECN setup SYN */
2086 		if (tp->ecn_flags & (TE_SETUPRECEIVED | TE_ACE_SETUPRECEIVED)) {
2087 			if (tcp_send_ecn_flags_on_syn(tp)) {
2088 				if (TCP_ACC_ECN_ENABLED(tp) && (tp->ecn_flags & TE_ACE_SETUPRECEIVED)) {
2089 					/*
2090 					 * Accurate ECN mode is on. Initialize packet and byte counters
2091 					 * for the server sending SYN-ACK. Although s_cep will be initialized
2092 					 * during input processing of ACK of SYN-ACK, initialize here as well
2093 					 * in case ACK gets lost.
2094 					 *
2095 					 * Non-zero initial values are used to
2096 					 * support a stateless handshake (see
2097 					 * Section 5.1 of AccECN draft) and to be
2098 					 * distinct from cases where the fields
2099 					 * are incorrectly zeroed.
2100 					 */
2101 					tp->t_aecn.t_rcv_ce_packets = 5;
2102 					tp->t_aecn.t_snd_ce_packets = 5;
2103 
2104 					/* Initialize CE byte counter to 0 */
2105 					tp->t_aecn.t_rcv_ce_bytes = tp->t_aecn.t_snd_ce_bytes = 0;
2106 
2107 					if (tp->ecn_flags & TE_ACE_SETUP_NON_ECT) {
2108 						tp->t_prev_ace_flags = TH_CWR;
2109 						flags |= tp->t_prev_ace_flags;
2110 						/* Remove the setup flag as it is also used for final ACK */
2111 						tp->ecn_flags &= ~TE_ACE_SETUP_NON_ECT;
2112 						tcpstat.tcps_ecn_ace_syn_not_ect++;
2113 					} else if (tp->ecn_flags & TE_ACE_SETUP_ECT1) {
2114 						tp->t_prev_ace_flags = (TH_CWR | TH_ECE);
2115 						flags |= tp->t_prev_ace_flags;
2116 						tp->ecn_flags &= ~TE_ACE_SETUP_ECT1;
2117 						tcpstat.tcps_ecn_ace_syn_ect1++;
2118 					} else if (tp->ecn_flags & TE_ACE_SETUP_ECT0) {
2119 						tp->t_prev_ace_flags = TH_AE;
2120 						flags |= tp->t_prev_ace_flags;
2121 						tp->ecn_flags &= ~TE_ACE_SETUP_ECT0;
2122 						tcpstat.tcps_ecn_ace_syn_ect0++;
2123 					} else if (tp->ecn_flags & TE_ACE_SETUP_CE) {
2124 						tp->t_prev_ace_flags = (TH_AE | TH_CWR);
2125 						flags |= tp->t_prev_ace_flags;
2126 						tp->ecn_flags &= ~TE_ACE_SETUP_CE;
2127 						/*
2128 						 * Receive counter is updated on
2129 						 * all acceptable packets except
2130 						 * CE on SYN packets (SYN=1, ACK=0)
2131 						 */
2132 						tcpstat.tcps_ecn_ace_syn_ce++;
2133 					} else {
2134 						if (tp->t_prev_ace_flags != 0) {
2135 							/* Set the flags for retransmitted SYN-ACK same as the previous one */
2136 							flags |= tp->t_prev_ace_flags;
2137 						} else {
2138 							/* We shouldn't come here */
2139 							panic("ECN flags (0x%x) not set correctly", tp->ecn_flags);
2140 						}
2141 					}
2142 					/*
2143 					 * We now send ECT1 packets when
2144 					 * L4S and Accurate ECN mode is on
2145 					 */
2146 					tp->ecn_flags |= TE_ACE_SETUPSENT;
2147 					if (TCP_L4S_ENABLED(tp)) {
2148 						tp->ecn_flags |= TE_SENDIPECT;
2149 					}
2150 				} else if (tp->ecn_flags & TE_SETUPRECEIVED) {
2151 					/*
2152 					 * Setting TH_ECE makes this an ECN-setup
2153 					 * SYN-ACK
2154 					 */
2155 					flags |= TH_ECE;
2156 					/*
2157 					 * Record that we sent the ECN-setup and
2158 					 * default to setting IP ECT.
2159 					 */
2160 					tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
2161 				}
2162 				tcpstat.tcps_ecn_server_setup++;
2163 				tcpstat.tcps_ecn_server_success++;
2164 			} else {
2165 				/*
2166 				 * For classic ECN, we sent an ECN-setup SYN-ACK but it was
2167 				 * dropped. Fallback to non-ECN-setup
2168 				 * SYN-ACK and clear flag to indicate that
2169 				 * we should not send data with IP ECT set
2170 				 *
2171 				 * Pretend we didn't receive an
2172 				 * ECN-setup SYN.
2173 				 *
2174 				 * We already incremented the counter
2175 				 * assuming that the ECN setup will
2176 				 * succeed. Decrementing here
2177 				 * tcps_ecn_server_success to correct it.
2178 				 *
2179 				 * For Accurate ECN, we don't yet remove TE_ACE_SETUPRECEIVED
2180 				 * as the client might have received Accurate ECN SYN-ACK.
2181 				 * We decide Accurate ECN's state on processing last ACK from the client.
2182 				 */
2183 				if (tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) {
2184 					tcpstat.tcps_ecn_lost_synack++;
2185 					tcpstat.tcps_ecn_server_success--;
2186 					tp->ecn_flags |= TE_LOST_SYNACK;
2187 				}
2188 				if (!TCP_ACC_ECN_ENABLED(tp)) {
2189 					/* Do this only for classic ECN. */
2190 					tp->ecn_flags &=
2191 					    ~(TE_SETUPRECEIVED | TE_SENDIPECT |
2192 					    TE_SENDCWR);
2193 				}
2194 			}
2195 		}
2196 	} else if ((flags & (TH_SYN | TH_ACK)) == TH_SYN &&
2197 	    (tp->ecn_flags & TE_ENABLE_ECN)) {
2198 		if (tcp_send_ecn_flags_on_syn(tp)) {
2199 			if (TCP_ACC_ECN_ENABLED(tp)) {
2200 				/*
2201 				 * We are negotiating AccECN in SYN.
2202 				 * We only set TE_SENDIPECT after the handshake
2203 				 * is complete.
2204 				 */
2205 				flags |= TH_ACE;
2206 				tp->ecn_flags |= (TE_ACE_SETUPSENT);
2207 			} else {
2208 				/*
2209 				 * Setting TH_ECE and TH_CWR makes this an
2210 				 * ECN-setup SYN
2211 				 */
2212 				flags |= (TH_ECE | TH_CWR);
2213 				/*
2214 				 * Record that we sent the ECN-setup and default to
2215 				 * setting IP ECT.
2216 				 */
2217 				tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
2218 			}
2219 			tcpstat.tcps_ecn_client_setup++;
2220 			tp->ecn_flags |= TE_CLIENT_SETUP;
2221 		} else {
2222 			/*
2223 			 * We sent an ECN-setup SYN but it was dropped.
2224 			 * Fall back to non-ECN and clear flag indicating
2225 			 * we should send data with IP ECT set.
2226 			 */
2227 			if (tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) {
2228 				tcpstat.tcps_ecn_lost_syn++;
2229 				tp->ecn_flags |= TE_LOST_SYN;
2230 			}
2231 			tp->ecn_flags &= ~TE_SENDIPECT;
2232 		}
2233 	} else if (TCP_ACC_ECN_ON(tp) && (tp->ecn_flags & TE_ACE_FINAL_ACK_3WHS) &&
2234 	    len == 0 && (flags & (TH_FLAGS_ALL)) == TH_ACK) {
2235 		/*
2236 		 * Client has processed SYN-ACK and moved to ESTABLISHED.
2237 		 * This is the final ACK of 3WHS. If ACC_ECN has been negotiated,
2238 		 * then send the handshake encoding as per Table 3 of Accurate ECN draft.
2239 		 * We are clearing the ACE flags just in case if they were set before.
2240 		 * TODO: if client has to carry data in the 3WHS ACK, then we need to send a pure ACK first
2241 		 */
2242 		flags &= ~(TH_AE | TH_CWR | TH_ECE);
2243 		if (tp->ecn_flags & TE_ACE_SETUP_NON_ECT) {
2244 			flags |= TH_CWR;
2245 			tp->ecn_flags &= ~TE_ACE_SETUP_NON_ECT;
2246 		} else if (tp->ecn_flags & TE_ACE_SETUP_ECT1) {
2247 			flags |= (TH_CWR | TH_ECE);
2248 			tp->ecn_flags &= ~TE_ACE_SETUP_ECT1;
2249 		} else if (tp->ecn_flags & TE_ACE_SETUP_ECT0) {
2250 			flags |= TH_AE;
2251 			tp->ecn_flags &= ~TE_ACE_SETUP_ECT0;
2252 		} else if (tp->ecn_flags & TE_ACE_SETUP_CE) {
2253 			flags |= (TH_AE | TH_CWR);
2254 			tp->ecn_flags &= ~TE_ACE_SETUP_CE;
2255 		}
2256 		tp->ecn_flags &= ~(TE_ACE_FINAL_ACK_3WHS);
2257 	}
2258 
2259 	/*
2260 	 * Check if we should set the TCP CWR flag.
2261 	 * CWR flag is sent when we reduced the congestion window because
2262 	 * we received a TCP ECE or we performed a fast retransmit. We
2263 	 * never set the CWR flag on retransmitted packets. We only set
2264 	 * the CWR flag on data packets. Pure acks don't have this set.
2265 	 */
2266 	if ((tp->ecn_flags & TE_SENDCWR) != 0 && len != 0 &&
2267 	    !SEQ_LT(tp->snd_nxt, tp->snd_max) && !rack_sack_rxmit) {
2268 		flags |= TH_CWR;
2269 		tp->ecn_flags &= ~TE_SENDCWR;
2270 	}
2271 
2272 	/*
2273 	 * Check if we should set the TCP ECE flag.
2274 	 */
2275 	if ((tp->ecn_flags & TE_SENDECE) != 0 && len == 0) {
2276 		flags |= TH_ECE;
2277 		tcpstat.tcps_ecn_sent_ece++;
2278 	}
2279 
2280 	hdrlen += optlen;
2281 
2282 	/* Reset DSACK sequence numbers */
2283 	tp->t_dsack_lseq = 0;
2284 	tp->t_dsack_rseq = 0;
2285 
2286 	if (isipv6) {
2287 		ipoptlen = ip6_optlen(inp);
2288 	} else {
2289 		if (tp_inp_options) {
2290 			ipoptlen = tp_inp_options->m_len -
2291 			    offsetof(struct ipoption, ipopt_list);
2292 		} else {
2293 			ipoptlen = 0;
2294 		}
2295 	}
2296 #if IPSEC
2297 	ipoptlen += ipsec_optlen;
2298 #endif
2299 
2300 	/*
2301 	 * Adjust data length if insertion of options will
2302 	 * bump the packet length beyond the t_maxopd length.
2303 	 * Clear the FIN bit because we cut off the tail of
2304 	 * the segment.
2305 	 *
2306 	 * When doing TSO limit a burst to TCP_MAXWIN minus the
2307 	 * IP, TCP and Options length to keep ip->ip_len from
2308 	 * overflowing.  Prevent the last segment from being
2309 	 * fractional thus making them all equal sized and set
2310 	 * the flag to continue sending.  TSO is disabled when
2311 	 * IP options or IPSEC are present.
2312 	 */
2313 	if (len + optlen + ipoptlen > tp->t_maxopd) {
2314 		/*
2315 		 * If there is still more to send,
2316 		 * don't close the connection.
2317 		 */
2318 		flags &= ~TH_FIN;
2319 		if (tso) {
2320 			int32_t tso_maxlen;
2321 
2322 			tso_maxlen = tp->tso_max_segment_size ?
2323 			    tp->tso_max_segment_size : TCP_MAXWIN;
2324 
2325 			/* hdrlen includes optlen */
2326 			if (len > tso_maxlen - hdrlen) {
2327 				len = tso_maxlen - hdrlen;
2328 				sendalot = 1;
2329 			} else if (tp->t_flags & TF_NEEDFIN) {
2330 				sendalot = 1;
2331 			}
2332 
2333 			if (len % (tp->t_maxopd - optlen) != 0) {
2334 				len = len - (len % (tp->t_maxopd - optlen));
2335 				sendalot = 1;
2336 			}
2337 		} else {
2338 			len = tp->t_maxopd - optlen - ipoptlen;
2339 			sendalot = 1;
2340 		}
2341 	}
2342 
2343 	if (max_linkhdr + hdrlen > MCLBYTES) {
2344 		panic("tcphdr too big");
2345 	}
2346 
2347 	/* Check if there is enough data in the send socket
2348 	 * buffer to start measuring bandwidth
2349 	 */
2350 	if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
2351 	    (tp->t_bwmeas != NULL) &&
2352 	    (tp->t_flagsext & TF_BWMEAS_INPROGRESS) == 0) {
2353 		tp->t_bwmeas->bw_size = min(min(
2354 			    (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)),
2355 			    tp->snd_cwnd), tp->snd_wnd);
2356 		if (tp->t_bwmeas->bw_minsize > 0 &&
2357 		    tp->t_bwmeas->bw_size < tp->t_bwmeas->bw_minsize) {
2358 			tp->t_bwmeas->bw_size = 0;
2359 		}
2360 		if (tp->t_bwmeas->bw_maxsize > 0) {
2361 			tp->t_bwmeas->bw_size = min(tp->t_bwmeas->bw_size,
2362 			    tp->t_bwmeas->bw_maxsize);
2363 		}
2364 		if (tp->t_bwmeas->bw_size > 0) {
2365 			tp->t_flagsext |= TF_BWMEAS_INPROGRESS;
2366 			tp->t_bwmeas->bw_start = tp->snd_max;
2367 			tp->t_bwmeas->bw_ts = tcp_now_local;
2368 		}
2369 	}
2370 
2371 	VERIFY(inp->inp_flowhash != 0);
2372 	/*
2373 	 * Grab a header mbuf, attaching a copy of data to
2374 	 * be transmitted, and initialize the header from
2375 	 * the template for sends on this connection.
2376 	 */
2377 	if (len) {
2378 		/* Remember what the last head-of-line packet-size was */
2379 		if (tp->t_pmtud_lastseg_size == 0 && tp->snd_nxt == tp->snd_una) {
2380 			ASSERT(len + optlen + ipoptlen <= IP_MAXPACKET);
2381 			tp->t_pmtud_lastseg_size = (uint16_t)(len + optlen + ipoptlen);
2382 		}
2383 		if ((tp->t_flagsext & TF_FORCE) && len == 1) {
2384 			tcpstat.tcps_sndprobe++;
2385 		} else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || rack_sack_rxmit) {
2386 			tcpstat.tcps_sndrexmitpack++;
2387 			tcpstat.tcps_sndrexmitbyte += len;
2388 			if (nstat_collect) {
2389 				nstat_route_tx(inp->inp_route.ro_rt, 1,
2390 				    len, NSTAT_TX_FLAG_RETRANSMIT);
2391 				INP_ADD_STAT(inp, ifnet_count_type,
2392 				    txpackets, 1);
2393 				INP_ADD_STAT(inp, ifnet_count_type,
2394 				    txbytes, len);
2395 				tp->t_stat.txretransmitbytes += len;
2396 				tp->t_stat.rxmitpkts++;
2397 			}
2398 			if (tp->ecn_flags & TE_SENDIPECT) {
2399 				tp->t_ecn_capable_packets_lost++;
2400 			}
2401 		} else {
2402 			tcpstat.tcps_sndpack++;
2403 			tcpstat.tcps_sndbyte += len;
2404 
2405 			if (nstat_collect) {
2406 				INP_ADD_STAT(inp, ifnet_count_type,
2407 				    txpackets, 1);
2408 				INP_ADD_STAT(inp, ifnet_count_type,
2409 				    txbytes, len);
2410 			}
2411 			if (tp->ecn_flags & TE_SENDIPECT) {
2412 				tp->t_ecn_capable_packets_sent++;
2413 			}
2414 			inp_decr_sndbytes_unsent(so, len);
2415 		}
2416 		inp_set_activity_bitmap(inp);
2417 #if MPTCP
2418 		if (tp->t_mpflags & TMPF_MPTCP_TRUE) {
2419 			tcpstat.tcps_mp_sndpacks++;
2420 			tcpstat.tcps_mp_sndbytes += len;
2421 		}
2422 #endif /* MPTCP */
2423 		/*
2424 		 * try to use the new interface that allocates all
2425 		 * the necessary mbuf hdrs under 1 mbuf lock and
2426 		 * avoids rescanning the socket mbuf list if
2427 		 * certain conditions are met.  This routine can't
2428 		 * be used in the following cases...
2429 		 * 1) the protocol headers exceed the capacity of
2430 		 * of a single mbuf header's data area (no cluster attached)
2431 		 * 2) the length of the data being transmitted plus
2432 		 * the protocol headers fits into a single mbuf header's
2433 		 * data area (no cluster attached)
2434 		 */
2435 		m = NULL;
2436 
2437 		/* minimum length we are going to allocate */
2438 		allocated_len = MHLEN;
2439 		if (MHLEN < hdrlen + max_linkhdr) {
2440 			MGETHDR(m, M_DONTWAIT, MT_HEADER);
2441 			if (m == NULL) {
2442 				error = ENOBUFS;
2443 				goto out;
2444 			}
2445 			MCLGET(m, M_DONTWAIT);
2446 			if ((m->m_flags & M_EXT) == 0) {
2447 				m_freem(m);
2448 				error = ENOBUFS;
2449 				goto out;
2450 			}
2451 			m->m_data += max_linkhdr;
2452 			m->m_len = hdrlen;
2453 			allocated_len = MCLBYTES;
2454 		}
2455 		if (len <= allocated_len - hdrlen - max_linkhdr) {
2456 			if (m == NULL) {
2457 				VERIFY(allocated_len <= MHLEN);
2458 				MGETHDR(m, M_DONTWAIT, MT_HEADER);
2459 				if (m == NULL) {
2460 					error = ENOBUFS;
2461 					goto out;
2462 				}
2463 				m->m_data += max_linkhdr;
2464 				m->m_len = hdrlen;
2465 			}
2466 			/* makes sure we still have data left to be sent at this point */
2467 			if (so->so_snd.sb_mb == NULL || off < 0) {
2468 				if (m != NULL) {
2469 					m_freem(m);
2470 				}
2471 				error = 0; /* should we return an error? */
2472 				goto out;
2473 			}
2474 			m_copydata(so->so_snd.sb_mb, off, (int) len,
2475 			    mtod(m, caddr_t) + hdrlen);
2476 			m->m_len += len;
2477 		} else {
2478 			uint32_t copymode;
2479 			/*
2480 			 * Retain packet header metadata at the socket
2481 			 * buffer if this is is an MPTCP subflow,
2482 			 * otherwise move it.
2483 			 */
2484 			copymode = M_COPYM_MOVE_HDR;
2485 #if MPTCP
2486 			if (so->so_flags & SOF_MP_SUBFLOW) {
2487 				copymode = M_COPYM_NOOP_HDR;
2488 			}
2489 #endif /* MPTCP */
2490 			if (m != NULL) {
2491 				if (so->so_snd.sb_flags & SB_SENDHEAD) {
2492 					VERIFY(so->so_snd.sb_flags & SB_SENDHEAD);
2493 					VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2494 
2495 					m->m_next = m_copym_mode(so->so_snd.sb_mb,
2496 					    off, (int)len, M_DONTWAIT,
2497 					    &so->so_snd.sb_sendhead,
2498 					    &so->so_snd.sb_sendoff, copymode);
2499 
2500 					VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2501 				} else {
2502 					m->m_next = m_copym_mode(so->so_snd.sb_mb,
2503 					    off, (int)len, M_DONTWAIT,
2504 					    NULL, NULL, copymode);
2505 				}
2506 				if (m->m_next == NULL) {
2507 					(void) m_free(m);
2508 					error = ENOBUFS;
2509 					goto out;
2510 				}
2511 			} else {
2512 				/*
2513 				 * make sure we still have data left
2514 				 * to be sent at this point
2515 				 */
2516 				if (so->so_snd.sb_mb == NULL) {
2517 					error = 0; /* should we return an error? */
2518 					goto out;
2519 				}
2520 
2521 				/*
2522 				 * m_copym_with_hdrs will always return the
2523 				 * last mbuf pointer and the offset into it that
2524 				 * it acted on to fullfill the current request,
2525 				 * whether a valid 'hint' was passed in or not.
2526 				 */
2527 				if (so->so_snd.sb_flags & SB_SENDHEAD) {
2528 					VERIFY(so->so_snd.sb_flags & SB_SENDHEAD);
2529 					VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2530 
2531 					m = m_copym_with_hdrs(so->so_snd.sb_mb,
2532 					    off, len, M_DONTWAIT, &so->so_snd.sb_sendhead,
2533 					    &so->so_snd.sb_sendoff, copymode);
2534 
2535 					VERIFY(so->so_snd.sb_sendoff <= so->so_snd.sb_cc);
2536 				} else {
2537 					m = m_copym_with_hdrs(so->so_snd.sb_mb,
2538 					    off, len, M_DONTWAIT, NULL,
2539 					    NULL, copymode);
2540 				}
2541 				if (m == NULL) {
2542 					error = ENOBUFS;
2543 					goto out;
2544 				}
2545 				m->m_data += max_linkhdr;
2546 				m->m_len = hdrlen;
2547 			}
2548 		}
2549 		/*
2550 		 * If we're sending everything we've got, set PUSH.
2551 		 * (This will keep happy those implementations which only
2552 		 * give data to the user when a buffer fills or
2553 		 * a PUSH comes in.)
2554 		 *
2555 		 * On SYN-segments we should not add the PUSH-flag.
2556 		 */
2557 		if (off + len == so->so_snd.sb_cc && !(flags & TH_SYN)) {
2558 			flags |= TH_PUSH;
2559 		}
2560 	} else {
2561 		if (tp->t_flags & TF_ACKNOW) {
2562 			tcpstat.tcps_sndacks++;
2563 		} else if (flags & (TH_SYN | TH_FIN | TH_RST)) {
2564 			tcpstat.tcps_sndctrl++;
2565 		} else if (SEQ_GT(tp->snd_up, tp->snd_una)) {
2566 			tcpstat.tcps_sndurg++;
2567 		} else {
2568 			tcpstat.tcps_sndwinup++;
2569 		}
2570 
2571 		MGETHDR(m, M_DONTWAIT, MT_HEADER);      /* MAC-OK */
2572 		if (m == NULL) {
2573 			error = ENOBUFS;
2574 			goto out;
2575 		}
2576 		if (MHLEN < (hdrlen + max_linkhdr)) {
2577 			MCLGET(m, M_DONTWAIT);
2578 			if ((m->m_flags & M_EXT) == 0) {
2579 				m_freem(m);
2580 				error = ENOBUFS;
2581 				goto out;
2582 			}
2583 		}
2584 		m->m_data += max_linkhdr;
2585 		m->m_len = hdrlen;
2586 	}
2587 	m->m_pkthdr.rcvif = 0;
2588 	m_add_crumb(m, PKT_CRUMB_TCP_OUTPUT);
2589 
2590 	/* Any flag other than pure-ACK: Do not compress! */
2591 	if (flags & ~(TH_ACK)) {
2592 		do_not_compress = TRUE;
2593 	}
2594 
2595 	if (tp->rcv_scale == 0) {
2596 		do_not_compress = TRUE;
2597 	}
2598 
2599 	if (do_not_compress) {
2600 		m->m_pkthdr.comp_gencnt = 0;
2601 	} else {
2602 		if (TSTMP_LT(tp->t_comp_lastinc + tcp_ack_compression_rate, tcp_now_local)) {
2603 			tp->t_comp_gencnt++;
2604 			/* 0 means no compression, thus jump this */
2605 			if (tp->t_comp_gencnt <= TCP_ACK_COMPRESSION_DUMMY) {
2606 				tp->t_comp_gencnt = TCP_ACK_COMPRESSION_DUMMY + 1;
2607 			}
2608 			tp->t_comp_lastinc = tcp_now_local;
2609 		}
2610 		m->m_pkthdr.comp_gencnt = tp->t_comp_gencnt;
2611 	}
2612 
2613 	if (isipv6) {
2614 		ip6 = mtod(m, struct ip6_hdr *);
2615 		th = (struct tcphdr *)(void *)(ip6 + 1);
2616 		tcp_fillheaders(m, tp, ip6, th);
2617 
2618 		if (TCP_L4S_ENABLED(tp) && TCP_ACC_ECN_ON(tp)) {
2619 			/* We send ECT1 for ALL packets (data, control, fast retransmits, RTO) */
2620 			if ((tp->ecn_flags & TE_SENDIPECT) != 0 && !(flags & TH_SYN)) {
2621 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT1 << 20);
2622 				uint64_t tx_time = tcp_pacer_get_packet_tx_time(tp, (uint16_t)len);
2623 				if (tx_time) {
2624 					tcp_set_mbuf_tx_time(m, tx_time);
2625 				}
2626 			}
2627 		} else {
2628 			if ((tp->ecn_flags & TE_SENDIPECT) != 0 && len &&
2629 			    !SEQ_LT(tp->snd_nxt, tp->snd_max) && !rack_sack_rxmit) {
2630 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
2631 			}
2632 		}
2633 		svc_flags |= PKT_SCF_IPV6;
2634 #if PF_ECN
2635 		m_pftag(m)->pftag_hdr = (void *)ip6;
2636 		m_pftag(m)->pftag_flags |= PF_TAG_HDR_INET6;
2637 #endif /* PF_ECN */
2638 	} else {
2639 		ip = mtod(m, struct ip *);
2640 		th = (struct tcphdr *)(void *)(ip + 1);
2641 		/* this picks up the pseudo header (w/o the length) */
2642 		tcp_fillheaders(m, tp, ip, th);
2643 
2644 		if (TCP_L4S_ENABLED(tp) && TCP_ACC_ECN_ON(tp)) {
2645 			/* We send ECT1 for ALL packets (data, control, fast retransmits, RTO) */
2646 			if ((tp->ecn_flags & TE_SENDIPECT) != 0 && !(flags & TH_SYN)) {
2647 				ip->ip_tos |= IPTOS_ECN_ECT1;
2648 				uint64_t tx_time = tcp_pacer_get_packet_tx_time(tp, (uint16_t)len);
2649 				if (tx_time) {
2650 					tcp_set_mbuf_tx_time(m, tx_time);
2651 				}
2652 			}
2653 		} else {
2654 			if ((tp->ecn_flags & TE_SENDIPECT) != 0 && len &&
2655 			    !SEQ_LT(tp->snd_nxt, tp->snd_max) &&
2656 			    !rack_sack_rxmit && !(flags & TH_SYN)) {
2657 				ip->ip_tos |= IPTOS_ECN_ECT0;
2658 			}
2659 		}
2660 #if PF_ECN
2661 		m_pftag(m)->pftag_hdr = (void *)ip;
2662 		m_pftag(m)->pftag_flags |= PF_TAG_HDR_INET;
2663 #endif /* PF_ECN */
2664 	}
2665 
2666 	/*
2667 	 * Fill in fields, remembering maximum advertised
2668 	 * window for use in delaying messages about window sizes.
2669 	 * If resending a FIN, be sure not to use a new sequence number.
2670 	 */
2671 	if ((flags & TH_FIN) && (tp->t_flags & TF_SENTFIN) &&
2672 	    tp->snd_nxt == tp->snd_max) {
2673 		tp->snd_nxt--;
2674 	}
2675 	/*
2676 	 * If we are doing retransmissions, then snd_nxt will
2677 	 * not reflect the first unsent octet.  For ACK only
2678 	 * packets, we do not want the sequence number of the
2679 	 * retransmitted packet, we want the sequence number
2680 	 * of the next unsent octet.  So, if there is no data
2681 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
2682 	 * when filling in ti_seq.  But if we are in persist
2683 	 * state, snd_max might reflect one byte beyond the
2684 	 * right edge of the window, so use snd_nxt in that
2685 	 * case, since we know we aren't doing a retransmission.
2686 	 * (retransmit and persist are mutually exclusive...)
2687 	 *
2688 	 * Note the state of this retransmit segment to detect spurious
2689 	 * retransmissions.
2690 	 */
2691 	if (rack_sack_rxmit == 0) {
2692 		if (len || (flags & (TH_SYN | TH_FIN)) ||
2693 		    tp->t_timer[TCPT_PERSIST]) {
2694 			th->th_seq = htonl(tp->snd_nxt);
2695 			if (len > 0) {
2696 				m->m_pkthdr.tx_start_seq = tp->snd_nxt;
2697 				m->m_pkthdr.pkt_flags |= PKTF_START_SEQ;
2698 			}
2699 			if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
2700 				if (SACK_ENABLED(tp) && len > 1 &&
2701 				    !(tp->t_flagsext & TF_SENT_TLPROBE)) {
2702 					tcp_rxtseg_insert(tp, tp->snd_nxt,
2703 					    (tp->snd_nxt + len - 1));
2704 				}
2705 				if (len > 0) {
2706 					m->m_pkthdr.pkt_flags |=
2707 					    PKTF_TCP_REXMT;
2708 				}
2709 			}
2710 		} else {
2711 			th->th_seq = htonl(tp->snd_max);
2712 		}
2713 	} else {
2714 		/* Use RACK if enabled otherwise use SACK */
2715 		if (TCP_RACK_ENABLED(tp)) {
2716 			th->th_seq = htonl(seg->start_seq);
2717 			tcp_rxtseg_insert(tp, seg->start_seq, (seg->start_seq + len - 1));
2718 		} else {
2719 			th->th_seq = htonl(p->rxmit);
2720 			tcp_rxtseg_insert(tp, p->rxmit, (p->rxmit + len - 1));
2721 			p->rxmit += len;
2722 			tp->sackhint.sack_bytes_rexmit += len;
2723 		}
2724 		if (len > 0) {
2725 			m->m_pkthdr.tx_start_seq = ntohl(th->th_seq);
2726 			m->m_pkthdr.pkt_flags |=
2727 			    (PKTF_TCP_REXMT | PKTF_START_SEQ);
2728 		}
2729 	}
2730 	th->th_ack = htonl(tp->rcv_nxt);
2731 	tp->last_ack_sent = tp->rcv_nxt;
2732 	if (optlen) {
2733 		bcopy(opt, th + 1, optlen);
2734 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
2735 	}
2736 	/* Separate AE from flags */
2737 	th->th_flags = (flags & (TH_FLAGS_ALL));
2738 	th->th_x2 = (flags & (TH_AE)) >> 8;
2739 	th->th_win = htons((u_short) (recwin >> tp->rcv_scale));
2740 	tp->t_last_recwin = recwin;
2741 	if (!(so->so_flags & SOF_MP_SUBFLOW)) {
2742 		if (recwin > 0 && SEQ_LT(tp->rcv_adv, tp->rcv_nxt + recwin)) {
2743 			tp->rcv_adv = tp->rcv_nxt + recwin;
2744 		}
2745 	} else {
2746 		struct mptcb *mp_tp = tptomptp(tp);
2747 		if (recwin > 0) {
2748 			tp->rcv_adv = tp->rcv_nxt + recwin;
2749 		}
2750 
2751 		if (recwin > 0 && MPTCP_SEQ_LT(mp_tp->mpt_rcvadv, mp_tp->mpt_rcvnxt + recwin)) {
2752 			mp_tp->mpt_rcvadv = mp_tp->mpt_rcvnxt + recwin;
2753 		}
2754 	}
2755 
2756 	/*
2757 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
2758 	 * a 0 window.  This may cause the remote transmitter to stall.  This
2759 	 * flag tells soreceive() to disable delayed acknowledgements when
2760 	 * draining the buffer.  This can occur if the receiver is attempting
2761 	 * to read more data then can be buffered prior to transmitting on
2762 	 * the connection.
2763 	 */
2764 	if (th->th_win == 0) {
2765 		tp->t_flags |= TF_RXWIN0SENT;
2766 	} else {
2767 		tp->t_flags &= ~TF_RXWIN0SENT;
2768 	}
2769 
2770 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
2771 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
2772 		th->th_flags |= TH_URG;
2773 	} else {
2774 		/*
2775 		 * If no urgent pointer to send, then we pull
2776 		 * the urgent pointer to the left edge of the send window
2777 		 * so that it doesn't drift into the send window on sequence
2778 		 * number wraparound.
2779 		 */
2780 		tp->snd_up = tp->snd_una;               /* drag it along */
2781 	}
2782 
2783 	/*
2784 	 * Put TCP length in extended header, and then
2785 	 * checksum extended header and data.
2786 	 */
2787 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
2788 
2789 	/*
2790 	 * If this is potentially the last packet on the stream, then mark
2791 	 * it in order to enable some optimizations in the underlying
2792 	 * layers
2793 	 */
2794 	if (tp->t_state != TCPS_ESTABLISHED &&
2795 	    (tp->t_state == TCPS_CLOSING || tp->t_state == TCPS_TIME_WAIT
2796 	    || tp->t_state == TCPS_LAST_ACK || (th->th_flags & TH_RST))) {
2797 		m->m_pkthdr.pkt_flags |= PKTF_LAST_PKT;
2798 	}
2799 
2800 	if (isipv6) {
2801 		/*
2802 		 * ip6_plen is not need to be filled now, and will be filled
2803 		 * in ip6_output.
2804 		 */
2805 		m->m_pkthdr.csum_flags = CSUM_TCPIPV6;
2806 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2807 		if (len + optlen) {
2808 			th->th_sum = in_addword(th->th_sum,
2809 			    htons((u_short)(optlen + len)));
2810 		}
2811 	} else {
2812 		m->m_pkthdr.csum_flags = CSUM_TCP;
2813 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2814 		if (len + optlen) {
2815 			th->th_sum = in_addword(th->th_sum,
2816 			    htons((u_short)(optlen + len)));
2817 		}
2818 	}
2819 
2820 	/*
2821 	 * Enable TSO and specify the size of the segments.
2822 	 * The TCP pseudo header checksum is always provided.
2823 	 */
2824 	if (tso) {
2825 		if (isipv6) {
2826 			m->m_pkthdr.csum_flags |= CSUM_TSO_IPV6;
2827 		} else {
2828 			m->m_pkthdr.csum_flags |= CSUM_TSO_IPV4;
2829 		}
2830 
2831 		m->m_pkthdr.tso_segsz = tp->t_maxopd - optlen;
2832 	} else {
2833 		m->m_pkthdr.tso_segsz = 0;
2834 	}
2835 
2836 	/*
2837 	 * In transmit state, time the transmission and arrange for
2838 	 * the retransmit.  In persist state, just set snd_max.
2839 	 */
2840 	if (!(tp->t_flagsext & TF_FORCE)
2841 	    || tp->t_timer[TCPT_PERSIST] == 0) {
2842 		tcp_seq startseq = tp->snd_nxt;
2843 
2844 		/*
2845 		 * Advance snd_nxt over sequence space of this segment.
2846 		 */
2847 		if (flags & (TH_SYN | TH_FIN)) {
2848 			if (flags & TH_SYN) {
2849 				tp->snd_nxt++;
2850 			}
2851 			if ((flags & TH_FIN) &&
2852 			    !(tp->t_flags & TF_SENTFIN)) {
2853 				tp->snd_nxt++;
2854 				tp->t_flags |= TF_SENTFIN;
2855 			}
2856 		}
2857 		if (rack_sack_rxmit) {
2858 			goto timer;
2859 		}
2860 		if (sack_rescue_rxt == TRUE) {
2861 			tp->snd_nxt = old_snd_nxt;
2862 			sack_rescue_rxt = FALSE;
2863 			tcpstat.tcps_pto_in_recovery++;
2864 		} else {
2865 			tp->snd_nxt += len;
2866 		}
2867 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
2868 			tp->snd_max = tp->snd_nxt;
2869 			tp->t_sndtime = tcp_now_local;
2870 			/*
2871 			 * Time this transmission if not a retransmission and
2872 			 * not currently timing anything.
2873 			 */
2874 			if (tp->t_rtttime == 0) {
2875 				tp->t_rtttime = tcp_now_local;
2876 				tp->t_rtseq = startseq;
2877 				tcpstat.tcps_segstimed++;
2878 
2879 				/* update variables related to pipe ack */
2880 				tp->t_pipeack_lastuna = tp->snd_una;
2881 			}
2882 		}
2883 
2884 		/*
2885 		 * Set retransmit timer if not currently set,
2886 		 * and not doing an ack or a keep-alive probe.
2887 		 */
2888 timer:
2889 		if (tp->t_timer[TCPT_REXMT] == 0 &&
2890 		    ((rack_sack_rxmit && tp->snd_nxt != tp->snd_max) ||
2891 		    tp->snd_nxt != tp->snd_una || (flags & TH_FIN))) {
2892 			if (tp->t_timer[TCPT_PERSIST]) {
2893 				tp->t_timer[TCPT_PERSIST] = 0;
2894 				tp->t_persist_stop = 0;
2895 				TCP_RESET_REXMT_STATE(tp);
2896 			}
2897 			tp->t_timer[TCPT_REXMT] =
2898 			    OFFSET_FROM_START(tp, tp->t_rxtcur);
2899 		}
2900 
2901 		/*
2902 		 * Set tail loss probe timeout if new data is being
2903 		 * transmitted. This will be supported only when
2904 		 * SACK option is enabled on a connection.
2905 		 *
2906 		 * Every time new data is sent PTO will get reset.
2907 		 */
2908 		if (tcp_enable_tlp && len != 0 && tp->t_state == TCPS_ESTABLISHED &&
2909 		    SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
2910 		    tp->snd_nxt == tp->snd_max &&
2911 		    SEQ_GT(tp->snd_nxt, tp->snd_una) &&
2912 		    tp->t_rxtshift == 0 &&
2913 		    (tp->t_flagsext & (TF_SENT_TLPROBE | TF_PKTS_REORDERED)) == 0) {
2914 			uint32_t pto, srtt;
2915 
2916 			srtt = tp->t_srtt >> TCP_RTT_SHIFT;
2917 			pto = 2 * srtt;
2918 			if ((tp->snd_max - tp->snd_una) <= tp->t_maxseg) {
2919 				pto += tcp_delack;
2920 			} else {
2921 				pto += 2;
2922 			}
2923 
2924 			/* if RTO is less than PTO, choose RTO instead */
2925 			if (tp->t_rxtcur < pto) {
2926 				pto = tp->t_rxtcur;
2927 			}
2928 
2929 			tp->t_timer[TCPT_PTO] = OFFSET_FROM_START(tp, pto);
2930 		}
2931 	} else {
2932 		/*
2933 		 * Persist case, update snd_max but since we are in
2934 		 * persist mode (no window) we do not update snd_nxt.
2935 		 */
2936 		int xlen = len;
2937 		if (flags & TH_SYN) {
2938 			++xlen;
2939 		}
2940 		if ((flags & TH_FIN) &&
2941 		    !(tp->t_flags & TF_SENTFIN)) {
2942 			++xlen;
2943 			tp->t_flags |= TF_SENTFIN;
2944 		}
2945 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max)) {
2946 			tp->snd_max = tp->snd_nxt + len;
2947 			tp->t_sndtime = tcp_now_local;
2948 		}
2949 	}
2950 
2951 	/*
2952 	 * Fill in IP length and desired time to live and
2953 	 * send to IP level.  There should be a better way
2954 	 * to handle ttl and tos; we could keep them in
2955 	 * the template, but need a way to checksum without them.
2956 	 */
2957 	/*
2958 	 * m->m_pkthdr.len should have been set before cksum calcuration,
2959 	 * because in6_cksum() need it.
2960 	 */
2961 	if (isipv6) {
2962 		/*
2963 		 * we separately set hoplimit for every segment, since the
2964 		 * user might want to change the value via setsockopt.
2965 		 * Also, desired default hop limit might be changed via
2966 		 * Neighbor Discovery.
2967 		 */
2968 		ip6->ip6_hlim = in6_selecthlim(inp, inp->in6p_route.ro_rt ?
2969 		    inp->in6p_route.ro_rt->rt_ifp : NULL);
2970 
2971 		/* Don't set ECT bit if requested by an app */
2972 
2973 		/* Set ECN bits for testing purposes */
2974 		if (tp->ecn_flags & TE_FORCE_ECT1) {
2975 			ip6->ip6_flow |= htonl(IPTOS_ECN_ECT1 << 20);
2976 		} else if (tp->ecn_flags & TE_FORCE_ECT0) {
2977 			ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
2978 		}
2979 
2980 		KERNEL_DEBUG(DBG_LAYER_BEG,
2981 		    ((inp->inp_fport << 16) | inp->inp_lport),
2982 		    (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
2983 		    (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
2984 		    sendalot, 0, 0);
2985 	} else {
2986 		ASSERT(m->m_pkthdr.len <= IP_MAXPACKET);
2987 		ip->ip_len = (u_short)m->m_pkthdr.len;
2988 		ip->ip_ttl = inp->inp_ip_ttl;   /* XXX */
2989 
2990 		/* Don't set ECN bit if requested by an app */
2991 		ip->ip_tos |= (inp->inp_ip_tos & ~IPTOS_ECN_MASK);
2992 
2993 		/* Set ECN bits for testing purposes */
2994 		if (tp->ecn_flags & TE_FORCE_ECT1) {
2995 			ip->ip_tos |= IPTOS_ECN_ECT1;
2996 		} else if (tp->ecn_flags & TE_FORCE_ECT0) {
2997 			ip->ip_tos |= IPTOS_ECN_ECT0;
2998 		}
2999 
3000 		KERNEL_DEBUG(DBG_LAYER_BEG,
3001 		    ((inp->inp_fport << 16) | inp->inp_lport),
3002 		    (((inp->inp_laddr.s_addr & 0xffff) << 16) |
3003 		    (inp->inp_faddr.s_addr & 0xffff)), 0, 0, 0);
3004 	}
3005 
3006 	/*
3007 	 * See if we should do MTU discovery.
3008 	 * Look at the flag updated on the following criterias:
3009 	 *	1) Path MTU discovery is authorized by the sysctl
3010 	 *	2) The route isn't set yet (unlikely but could happen)
3011 	 *	3) The route is up
3012 	 *	4) the MTU is not locked (if it is, then discovery has been
3013 	 *	   disabled for that route)
3014 	 */
3015 	if (!isipv6) {
3016 		if (path_mtu_discovery && (tp->t_flags & TF_PMTUD)) {
3017 			ip->ip_off |= IP_DF;
3018 		}
3019 	}
3020 
3021 #if NECP
3022 	{
3023 		necp_kernel_policy_id policy_id;
3024 		necp_kernel_policy_id skip_policy_id;
3025 		u_int32_t route_rule_id;
3026 		u_int32_t pass_flags;
3027 		if (!necp_socket_is_allowed_to_send_recv(inp, NULL, 0, &policy_id, &route_rule_id, &skip_policy_id, &pass_flags)) {
3028 			TCP_LOG_DROP_NECP(isipv6 ? (void *)ip6 : (void *)ip, th, tp, true);
3029 			m_freem(m);
3030 			error = EHOSTUNREACH;
3031 			goto out;
3032 		}
3033 		necp_mark_packet_from_socket(m, inp, policy_id, route_rule_id, skip_policy_id, pass_flags);
3034 
3035 		if (net_qos_policy_restricted != 0) {
3036 			necp_socket_update_qos_marking(inp, inp->inp_route.ro_rt, route_rule_id);
3037 		}
3038 	}
3039 #endif /* NECP */
3040 
3041 #if IPSEC
3042 	if (inp->inp_sp != NULL) {
3043 		ipsec_setsocket(m, so);
3044 	}
3045 #endif /*IPSEC*/
3046 
3047 	/*
3048 	 * The socket is kept locked while sending out packets in ip_output, even if packet chaining is not active.
3049 	 */
3050 	lost = 0;
3051 
3052 	/*
3053 	 * Embed the flow hash in pkt hdr and mark the packet as
3054 	 * capable of flow controlling
3055 	 */
3056 	m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB;
3057 	m->m_pkthdr.pkt_flowid = inp->inp_flowhash;
3058 	m->m_pkthdr.pkt_flags |= (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC | PKTF_FLOW_ADV);
3059 	m->m_pkthdr.pkt_proto = IPPROTO_TCP;
3060 	m->m_pkthdr.tx_tcp_pid = so->last_pid;
3061 	if (so->so_flags & SOF_DELEGATED) {
3062 		m->m_pkthdr.tx_tcp_e_pid = so->e_pid;
3063 	} else {
3064 		m->m_pkthdr.tx_tcp_e_pid = 0;
3065 	}
3066 
3067 	m->m_nextpkt = NULL;
3068 
3069 	if (inp->inp_last_outifp != NULL &&
3070 	    !(inp->inp_last_outifp->if_flags & IFF_LOOPBACK)) {
3071 		/* Hint to prioritize this packet if
3072 		 * 1. if the packet has no data
3073 		 * 2. the interface supports transmit-start model and did
3074 		 *    not disable ACK prioritization.
3075 		 * 3. Only ACK flag is set.
3076 		 * 4. there is no outstanding data on this connection.
3077 		 */
3078 		if (len == 0 && (inp->inp_last_outifp->if_eflags & (IFEF_TXSTART | IFEF_NOACKPRI)) == IFEF_TXSTART) {
3079 			if (th->th_flags == TH_ACK &&
3080 			    tp->snd_una == tp->snd_max &&
3081 			    tp->t_timer[TCPT_REXMT] == 0) {
3082 				svc_flags |= PKT_SCF_TCP_ACK;
3083 			}
3084 			if (th->th_flags & TH_SYN) {
3085 				svc_flags |= PKT_SCF_TCP_SYN;
3086 			}
3087 		}
3088 		set_packet_service_class(m, so, sotc, svc_flags);
3089 	} else {
3090 		/*
3091 		 * Optimization for loopback just set the mbuf
3092 		 * service class
3093 		 */
3094 		(void) m_set_service_class(m, so_tc2msc(sotc));
3095 	}
3096 
3097 	if ((th->th_flags & TH_SYN) && tp->t_syn_sent < UINT8_MAX) {
3098 		tp->t_syn_sent++;
3099 	}
3100 	if ((th->th_flags & TH_FIN) && tp->t_fin_sent < UINT8_MAX) {
3101 		tp->t_fin_sent++;
3102 	}
3103 	if ((th->th_flags & TH_RST) && tp->t_rst_sent < UINT8_MAX) {
3104 		tp->t_rst_sent++;
3105 	}
3106 	TCP_LOG_TH_FLAGS(isipv6 ? (void *)ip6 : (void *)ip, th, tp, true,
3107 	    inp->inp_last_outifp != NULL ? inp->inp_last_outifp :
3108 	    inp->inp_boundifp);
3109 
3110 	tp->t_pktlist_sentlen += len;
3111 	tp->t_lastchain++;
3112 
3113 	if (isipv6) {
3114 		DTRACE_TCP5(send, struct mbuf *, m, struct inpcb *, inp,
3115 		    struct ip6 *, ip6, struct tcpcb *, tp, struct tcphdr *,
3116 		    th);
3117 	} else {
3118 		DTRACE_TCP5(send, struct mbuf *, m, struct inpcb *, inp,
3119 		    struct ip *, ip, struct tcpcb *, tp, struct tcphdr *, th);
3120 	}
3121 
3122 	if (tp->t_pktlist_head != NULL) {
3123 		tp->t_pktlist_tail->m_nextpkt = m;
3124 		tp->t_pktlist_tail = m;
3125 	} else {
3126 		packchain_newlist++;
3127 		tp->t_pktlist_head = tp->t_pktlist_tail = m;
3128 	}
3129 
3130 	/* Append segment to time-ordered list and RB tree used for RACK */
3131 	if (TCP_RACK_ENABLED(tp) && len) {
3132 		uint8_t retransmit_flag = 0;
3133 		if (tp->t_flagsext & TF_SENT_TLPROBE) {
3134 			/* Only set the at least once retransmitted flag */
3135 			retransmit_flag = (m->m_pkthdr.pkt_flags & PKTF_TCP_REXMT) ? TCP_SEGMENT_RETRANSMITTED_ATLEAST_ONCE : 0;
3136 		} else {
3137 			/* Set both RACK and EVER retransmitted flags */
3138 			retransmit_flag = (m->m_pkthdr.pkt_flags & PKTF_TCP_REXMT) ? TCP_SEGMENT_RETRANSMITTED : 0;
3139 		}
3140 		tcp_seg_sent_insert(tp, seg, ntohl(th->th_seq), ntohl(th->th_seq) + len, tcp_now_local, retransmit_flag);
3141 	}
3142 
3143 	if (sendalot == 0 || (tp->t_state != TCPS_ESTABLISHED) ||
3144 	    (tp->t_flags & TF_ACKNOW) ||
3145 	    (tp->t_flagsext & TF_FORCE) ||
3146 	    tp->t_lastchain >= tcp_packet_chaining) {
3147 		error = 0;
3148 		while (inp->inp_sndinprog_cnt == 0 &&
3149 		    tp->t_pktlist_head != NULL) {
3150 			packetlist = tp->t_pktlist_head;
3151 			packchain_listadd = tp->t_lastchain;
3152 			packchain_sent++;
3153 			lost = tp->t_pktlist_sentlen;
3154 			TCP_PKTLIST_CLEAR(tp);
3155 
3156 			error = tcp_ip_output(so, tp, packetlist,
3157 			    packchain_listadd, tp_inp_options,
3158 			    (so_options & SO_DONTROUTE),
3159 			    (rack_sack_rxmit || (sack_bytes_rxmt != 0)), isipv6);
3160 			if (error) {
3161 				/*
3162 				 * Take into account the rest of unsent
3163 				 * packets in the packet list for this tcp
3164 				 * into "lost", since we're about to free
3165 				 * the whole list below.
3166 				 */
3167 				lost += tp->t_pktlist_sentlen;
3168 				break;
3169 			} else {
3170 				lost = 0;
3171 			}
3172 		}
3173 		/* tcp was closed while we were in ip; resume close */
3174 		if (inp->inp_sndinprog_cnt == 0 &&
3175 		    (tp->t_flags & TF_CLOSING)) {
3176 			tp->t_flags &= ~TF_CLOSING;
3177 			(void) tcp_close(tp);
3178 			return 0;
3179 		}
3180 	} else {
3181 		error = 0;
3182 		packchain_looped++;
3183 		tcpstat.tcps_sndtotal++;
3184 
3185 		goto again;
3186 	}
3187 	if (error) {
3188 		/*
3189 		 * Assume that the packets were lost, so back out the
3190 		 * sequence number advance, if any.  Note that the "lost"
3191 		 * variable represents the amount of user data sent during
3192 		 * the recent call to ip_output_list() plus the amount of
3193 		 * user data in the packet list for this tcp at the moment.
3194 		 */
3195 		if (!(tp->t_flagsext & TF_FORCE)
3196 		    || tp->t_timer[TCPT_PERSIST] == 0) {
3197 			/*
3198 			 * No need to check for TH_FIN here because
3199 			 * the TF_SENTFIN flag handles that case.
3200 			 */
3201 			if ((flags & TH_SYN) == 0) {
3202 				/*
3203 				 * RACK will mark these segments lost on its own
3204 				 * when new ACK arrives, no need to adjust anything here.
3205 				 * In fact doing so would be wrong, as RACK segments are
3206 				 * ordered in time (not sequence number).
3207 				 */
3208 				if (rack_sack_rxmit && !TCP_RACK_ENABLED(tp)) {
3209 					if (SEQ_GT((p->rxmit - lost),
3210 					    tp->snd_una)) {
3211 						p->rxmit -= lost;
3212 
3213 						if (SEQ_LT(p->rxmit, p->start)) {
3214 							p->rxmit = p->start;
3215 						}
3216 					} else {
3217 						lost = p->rxmit - tp->snd_una;
3218 						p->rxmit = tp->snd_una;
3219 
3220 						if (SEQ_LT(p->rxmit, p->start)) {
3221 							p->rxmit = p->start;
3222 						}
3223 					}
3224 					tp->sackhint.sack_bytes_rexmit -= lost;
3225 					if (tp->sackhint.sack_bytes_rexmit < 0) {
3226 						tp->sackhint.sack_bytes_rexmit = 0;
3227 					}
3228 				} else {
3229 					if (SEQ_GT((tp->snd_nxt - lost),
3230 					    tp->snd_una)) {
3231 						tp->snd_nxt -= lost;
3232 					} else {
3233 						tp->snd_nxt = tp->snd_una;
3234 					}
3235 				}
3236 			}
3237 		}
3238 out:
3239 		if (tp->t_pktlist_head != NULL) {
3240 			m_freem_list(tp->t_pktlist_head);
3241 		}
3242 		TCP_PKTLIST_CLEAR(tp);
3243 
3244 		if (error == ENOBUFS) {
3245 			/*
3246 			 * Set retransmit timer if not currently set
3247 			 * when we failed to send a segment that can be
3248 			 * retransmitted (i.e. not pure ack or rst)
3249 			 */
3250 			if (tp->t_timer[TCPT_REXMT] == 0 &&
3251 			    tp->t_timer[TCPT_PERSIST] == 0 &&
3252 			    (len != 0 || (flags & (TH_SYN | TH_FIN)) != 0 ||
3253 			    so->so_snd.sb_cc > 0)) {
3254 				tp->t_timer[TCPT_REXMT] =
3255 				    OFFSET_FROM_START(tp, tp->t_rxtcur);
3256 			}
3257 			tp->snd_cwnd = tp->t_maxseg;
3258 			tp->t_bytes_acked = 0;
3259 			tcp_check_timer_state(tp);
3260 			KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3261 
3262 			TCP_LOG_OUTPUT(tp, "error ENOBUFS silently handled");
3263 
3264 			tcp_ccdbg_trace(tp, NULL, TCP_CC_OUTPUT_ERROR);
3265 			return 0;
3266 		}
3267 		if (error == EMSGSIZE) {
3268 			/*
3269 			 * ip_output() will have already fixed the route
3270 			 * for us.  tcp_mtudisc() will, as its last action,
3271 			 * initiate retransmission, so it is important to
3272 			 * not do so here.
3273 			 *
3274 			 * If TSO was active we either got an interface
3275 			 * without TSO capabilits or TSO was turned off.
3276 			 * Disable it for this connection as too and
3277 			 * immediatly retry with MSS sized segments generated
3278 			 * by this function.
3279 			 */
3280 			if (tso) {
3281 				tp->t_flags &= ~TF_TSO;
3282 			}
3283 
3284 			tcp_mtudisc(inp, 0);
3285 			tcp_check_timer_state(tp);
3286 
3287 			TCP_LOG_OUTPUT(tp, "error EMSGSIZE silently handled");
3288 
3289 			KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3290 			return 0;
3291 		}
3292 		/*
3293 		 * Unless this is due to interface restriction policy,
3294 		 * treat EHOSTUNREACH/ENETDOWN/EADDRNOTAVAIL as a soft error.
3295 		 */
3296 		if ((error == EHOSTUNREACH || error == ENETDOWN || error == EADDRNOTAVAIL) &&
3297 		    TCPS_HAVERCVDSYN(tp->t_state) &&
3298 		    !inp_restricted_send(inp, inp->inp_last_outifp)) {
3299 			tp->t_softerror = error;
3300 			TCP_LOG_OUTPUT(tp, "soft error %d silently handled", error);
3301 			error = 0;
3302 		} else {
3303 			TCP_LOG_OUTPUT(tp, "error %d", error);
3304 		}
3305 		tcp_check_timer_state(tp);
3306 		KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3307 		return error;
3308 	}
3309 
3310 	tcpstat.tcps_sndtotal++;
3311 
3312 	KERNEL_DEBUG(DBG_FNC_TCP_OUTPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3313 	if (sendalot) {
3314 		goto again;
3315 	}
3316 
3317 	tcp_check_timer_state(tp);
3318 
3319 	return 0;
3320 }
3321 
3322 static int
tcp_ip_output(struct socket * so,struct tcpcb * tp,struct mbuf * pkt,int cnt,struct mbuf * opt,int flags,int sack_in_progress,boolean_t isipv6)3323 tcp_ip_output(struct socket *so, struct tcpcb *tp, struct mbuf *pkt,
3324     int cnt, struct mbuf *opt, int flags, int sack_in_progress, boolean_t isipv6)
3325 {
3326 	int error = 0;
3327 	boolean_t chain;
3328 	boolean_t unlocked = FALSE;
3329 	boolean_t ifdenied = FALSE;
3330 	struct inpcb *__single inp = tp->t_inpcb;
3331 	struct ifnet *__single outif = NULL;
3332 	bool check_qos_marking_again = (so->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE) ? FALSE : TRUE;
3333 
3334 	union {
3335 		struct route _ro;
3336 		struct route_in6 _ro6;
3337 	} route_u_ = {};
3338 #define ro route_u_._ro
3339 #define ro6 route_u_._ro6
3340 
3341 	union {
3342 		struct ip_out_args _ipoa;
3343 		struct ip6_out_args _ip6oa;
3344 	} out_args_u_ = {};
3345 #define ipoa out_args_u_._ipoa
3346 #define ip6oa out_args_u_._ip6oa
3347 
3348 	if (isipv6) {
3349 		ip6oa.ip6oa_boundif = IFSCOPE_NONE;
3350 		ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
3351 		ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
3352 		ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3353 	} else {
3354 		ipoa.ipoa_boundif = IFSCOPE_NONE;
3355 		ipoa.ipoa_flags = IPOAF_SELECT_SRCIF | IPOAF_BOUND_SRCADDR;
3356 		ipoa.ipoa_sotc = SO_TC_UNSPEC;
3357 		ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3358 	}
3359 
3360 	struct flowadv *__single adv =
3361 	    (isipv6 ? &ip6oa.ip6oa_flowadv : &ipoa.ipoa_flowadv);
3362 
3363 	/* If socket was bound to an ifindex, tell ip_output about it */
3364 	if (inp->inp_flags & INP_BOUND_IF) {
3365 		if (isipv6) {
3366 			ip6oa.ip6oa_boundif = inp->inp_boundifp->if_index;
3367 			ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
3368 		} else {
3369 			ipoa.ipoa_boundif = inp->inp_boundifp->if_index;
3370 			ipoa.ipoa_flags |= IPOAF_BOUND_IF;
3371 		}
3372 	} else if (!in6_embedded_scope && isipv6 && (IN6_IS_SCOPE_EMBED(&inp->in6p_faddr))) {
3373 		ip6oa.ip6oa_boundif = inp->inp_fifscope;
3374 		ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
3375 	}
3376 
3377 	if (INP_NO_CELLULAR(inp)) {
3378 		if (isipv6) {
3379 			ip6oa.ip6oa_flags |=  IP6OAF_NO_CELLULAR;
3380 		} else {
3381 			ipoa.ipoa_flags |=  IPOAF_NO_CELLULAR;
3382 		}
3383 	}
3384 	if (INP_NO_EXPENSIVE(inp)) {
3385 		if (isipv6) {
3386 			ip6oa.ip6oa_flags |=  IP6OAF_NO_EXPENSIVE;
3387 		} else {
3388 			ipoa.ipoa_flags |=  IPOAF_NO_EXPENSIVE;
3389 		}
3390 	}
3391 	if (INP_NO_CONSTRAINED(inp)) {
3392 		if (isipv6) {
3393 			ip6oa.ip6oa_flags |=  IP6OAF_NO_CONSTRAINED;
3394 		} else {
3395 			ipoa.ipoa_flags |=  IPOAF_NO_CONSTRAINED;
3396 		}
3397 	}
3398 	if (INP_AWDL_UNRESTRICTED(inp)) {
3399 		if (isipv6) {
3400 			ip6oa.ip6oa_flags |=  IP6OAF_AWDL_UNRESTRICTED;
3401 		} else {
3402 			ipoa.ipoa_flags |=  IPOAF_AWDL_UNRESTRICTED;
3403 		}
3404 	}
3405 	if (INP_INTCOPROC_ALLOWED(inp) && isipv6) {
3406 		ip6oa.ip6oa_flags |=  IP6OAF_INTCOPROC_ALLOWED;
3407 	}
3408 	if (INP_MANAGEMENT_ALLOWED(inp)) {
3409 		if (isipv6) {
3410 			ip6oa.ip6oa_flags |=  IP6OAF_MANAGEMENT_ALLOWED;
3411 		} else {
3412 			ipoa.ipoa_flags |=  IPOAF_MANAGEMENT_ALLOWED;
3413 		}
3414 	}
3415 	if (isipv6) {
3416 		ip6oa.ip6oa_sotc = so->so_traffic_class;
3417 		ip6oa.ip6oa_netsvctype = so->so_netsvctype;
3418 		ip6oa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
3419 	} else {
3420 		ipoa.ipoa_sotc = so->so_traffic_class;
3421 		ipoa.ipoa_netsvctype = so->so_netsvctype;
3422 		ipoa.qos_marking_gencount = inp->inp_policyresult.results.qos_marking_gencount;
3423 	}
3424 	if ((so->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
3425 		if (isipv6) {
3426 			ip6oa.ip6oa_flags |= IP6OAF_QOSMARKING_ALLOWED;
3427 		} else {
3428 			ipoa.ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
3429 		}
3430 	}
3431 	if (check_qos_marking_again) {
3432 		if (isipv6) {
3433 			ip6oa.ip6oa_flags |= IP6OAF_REDO_QOSMARKING_POLICY;
3434 		} else {
3435 			ipoa.ipoa_flags |= IPOAF_REDO_QOSMARKING_POLICY;
3436 		}
3437 	}
3438 	if (isipv6) {
3439 		flags |= IPV6_OUTARGS;
3440 	} else {
3441 		flags |= IP_OUTARGS;
3442 	}
3443 
3444 	/* Copy the cached route and take an extra reference */
3445 	if (isipv6) {
3446 		in6p_route_copyout(inp, &ro6);
3447 	} else {
3448 		inp_route_copyout(inp, &ro);
3449 	}
3450 #if (DEBUG || DEVELOPMENT)
3451 	if ((so->so_flags & SOF_MARK_WAKE_PKT) && pkt != NULL) {
3452 		so->so_flags &= ~SOF_MARK_WAKE_PKT;
3453 		pkt->m_pkthdr.pkt_flags |= PKTF_WAKE_PKT;
3454 	}
3455 #endif /* (DEBUG || DEVELOPMENT) */
3456 
3457 	/*
3458 	 * Make sure ACK/DELACK conditions are cleared before
3459 	 * we unlock the socket.
3460 	 */
3461 	tp->last_ack_sent = tp->rcv_nxt;
3462 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
3463 	tp->t_timer[TCPT_DELACK] = 0;
3464 	tp->t_unacksegs = 0;
3465 	tp->t_unacksegs_ce = 0;
3466 
3467 	/* Increment the count of outstanding send operations */
3468 	inp->inp_sndinprog_cnt++;
3469 
3470 	/*
3471 	 * If allowed, unlock TCP socket while in IP
3472 	 * but only if the connection is established and
3473 	 * in a normal mode where reentrancy on the tcpcb won't be
3474 	 * an issue:
3475 	 * - there is no SACK episode
3476 	 * - we're not in Fast Recovery mode
3477 	 * - if we're not sending from an upcall.
3478 	 */
3479 	if (tcp_output_unlocked && !so->so_upcallusecount &&
3480 	    (tp->t_state == TCPS_ESTABLISHED) && (sack_in_progress == 0) &&
3481 	    !IN_FASTRECOVERY(tp) && !(so->so_flags & SOF_MP_SUBFLOW)) {
3482 		unlocked = TRUE;
3483 		socket_unlock(so, 0);
3484 	}
3485 
3486 	/*
3487 	 * Don't send down a chain of packets when:
3488 	 * - TCP chaining is disabled
3489 	 * - there is an IPsec rule set
3490 	 * - there is a non default rule set for the firewall
3491 	 */
3492 
3493 	chain = tcp_packet_chaining > 1
3494 #if IPSEC
3495 	    && ipsec_bypass
3496 #endif
3497 	;         // I'm important, not extraneous
3498 
3499 	while (pkt != NULL) {
3500 		struct mbuf *npkt = pkt->m_nextpkt;
3501 
3502 		if (!chain) {
3503 			pkt->m_nextpkt = NULL;
3504 			/*
3505 			 * If we are not chaining, make sure to set the packet
3506 			 * list count to 0 so that IP takes the right path;
3507 			 * this is important for cases such as IPsec where a
3508 			 * single mbuf might result in multiple mbufs as part
3509 			 * of the encapsulation.  If a non-zero count is passed
3510 			 * down to IP, the head of the chain might change and
3511 			 * we could end up skipping it (thus generating bogus
3512 			 * packets).  Fixing it in IP would be desirable, but
3513 			 * for now this would do it.
3514 			 */
3515 			cnt = 0;
3516 		}
3517 		if (isipv6) {
3518 			error = ip6_output_list(pkt, cnt,
3519 			    inp->in6p_outputopts, &ro6, flags, NULL, NULL,
3520 			    &ip6oa);
3521 			ifdenied = (ip6oa.ip6oa_flags & IP6OAF_R_IFDENIED);
3522 		} else {
3523 			error = ip_output_list(pkt, cnt, opt, &ro, flags, NULL,
3524 			    &ipoa);
3525 			ifdenied = (ipoa.ipoa_flags & IPOAF_R_IFDENIED);
3526 		}
3527 
3528 		if (chain || error) {
3529 			/*
3530 			 * If we sent down a chain then we are done since
3531 			 * the callee had taken care of everything; else
3532 			 * we need to free the rest of the chain ourselves.
3533 			 */
3534 			if (!chain) {
3535 				m_freem_list(npkt);
3536 			}
3537 			break;
3538 		}
3539 		pkt = npkt;
3540 	}
3541 
3542 	if (unlocked) {
3543 		socket_lock(so, 0);
3544 	}
3545 
3546 	/*
3547 	 * Enter flow controlled state if the connection is established
3548 	 * and is not in recovery. Flow control is allowed only if there
3549 	 * is outstanding data.
3550 	 *
3551 	 * A connection will enter suspended state even if it is in
3552 	 * recovery.
3553 	 */
3554 	if (((adv->code == FADV_FLOW_CONTROLLED && !IN_FASTRECOVERY(tp)) ||
3555 	    adv->code == FADV_SUSPENDED) &&
3556 	    !(tp->t_flags & TF_CLOSING) &&
3557 	    tp->t_state == TCPS_ESTABLISHED &&
3558 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
3559 		int rc;
3560 		rc = inp_set_fc_state(inp, adv->code);
3561 
3562 		if (rc == 1) {
3563 			tcp_ccdbg_trace(tp, NULL,
3564 			    ((adv->code == FADV_FLOW_CONTROLLED) ?
3565 			    TCP_CC_FLOW_CONTROL : TCP_CC_SUSPEND));
3566 			if (adv->code == FADV_FLOW_CONTROLLED) {
3567 				TCP_LOG_OUTPUT(tp, "flow controlled");
3568 			} else {
3569 				TCP_LOG_OUTPUT(tp, "flow suspended");
3570 			}
3571 		}
3572 	}
3573 
3574 	/*
3575 	 * When an interface queue gets suspended, some of the
3576 	 * packets are dropped. Return ENOBUFS, to update the
3577 	 * pcb state.
3578 	 */
3579 	if (adv->code == FADV_SUSPENDED) {
3580 		error = ENOBUFS;
3581 	}
3582 
3583 	VERIFY(inp->inp_sndinprog_cnt > 0);
3584 	if (--inp->inp_sndinprog_cnt == 0) {
3585 		inp->inp_flags &= ~(INP_FC_FEEDBACK);
3586 		if (inp->inp_sndingprog_waiters > 0) {
3587 			wakeup(&inp->inp_sndinprog_cnt);
3588 		}
3589 	}
3590 
3591 	if (isipv6) {
3592 		/*
3593 		 * When an NECP IP tunnel policy forces the outbound interface,
3594 		 * ip6_output_list() informs the transport layer what is the actual
3595 		 * outgoing interface
3596 		 */
3597 		if (ip6oa.ip6oa_flags & IP6OAF_BOUND_IF) {
3598 			outif = ifindex2ifnet[ip6oa.ip6oa_boundif];
3599 		} else if (ro6.ro_rt != NULL) {
3600 			outif = ro6.ro_rt->rt_ifp;
3601 		}
3602 	} else {
3603 		if (ro.ro_rt != NULL) {
3604 			outif = ro.ro_rt->rt_ifp;
3605 		}
3606 	}
3607 	if (check_qos_marking_again) {
3608 		uint32_t qos_marking_gencount;
3609 		bool allow_qos_marking;
3610 		if (isipv6) {
3611 			qos_marking_gencount = ip6oa.qos_marking_gencount;
3612 			allow_qos_marking = ip6oa.ip6oa_flags & IP6OAF_QOSMARKING_ALLOWED ? TRUE : FALSE;
3613 		} else {
3614 			qos_marking_gencount = ipoa.qos_marking_gencount;
3615 			allow_qos_marking = ipoa.ipoa_flags & IPOAF_QOSMARKING_ALLOWED ? TRUE : FALSE;
3616 		}
3617 		inp->inp_policyresult.results.qos_marking_gencount = qos_marking_gencount;
3618 		if (allow_qos_marking == TRUE) {
3619 			inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
3620 		} else {
3621 			inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
3622 		}
3623 	}
3624 
3625 	if (outif != NULL && outif != inp->inp_last_outifp) {
3626 		/* Update the send byte count */
3627 		if (so->so_snd.sb_cc > 0 && so->so_snd.sb_flags & SB_SNDBYTE_CNT) {
3628 			inp_decr_sndbytes_total(so, so->so_snd.sb_cc);
3629 			inp_decr_sndbytes_allunsent(so, tp->snd_una);
3630 			so->so_snd.sb_flags &= ~SB_SNDBYTE_CNT;
3631 		}
3632 		inp->inp_last_outifp = outif;
3633 #if SKYWALK
3634 		if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
3635 			netns_set_ifnet(&inp->inp_netns_token, inp->inp_last_outifp);
3636 		}
3637 #endif /* SKYWALK */
3638 	}
3639 
3640 	if (error != 0 && ifdenied &&
3641 	    (INP_NO_CELLULAR(inp) || INP_NO_EXPENSIVE(inp) || INP_NO_CONSTRAINED(inp))) {
3642 		soevent(so,
3643 		    (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
3644 	}
3645 
3646 	/* Synchronize cached PCB route & options */
3647 	if (isipv6) {
3648 		in6p_route_copyin(inp, &ro6);
3649 	} else {
3650 		inp_route_copyin(inp, &ro);
3651 	}
3652 
3653 	if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift == 0 &&
3654 	    tp->t_inpcb->inp_route.ro_rt != NULL) {
3655 		/* If we found the route and there is an rtt on it
3656 		 * reset the retransmit timer
3657 		 */
3658 		tcp_getrt_rtt(tp, tp->t_inpcb->in6p_route.ro_rt);
3659 		tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
3660 	}
3661 	return error;
3662 #undef ro
3663 #undef ro6
3664 #undef ipoa
3665 #undef ip6oa
3666 }
3667 
3668 int tcptv_persmin_val = TCPTV_PERSMIN;
3669 
3670 void
tcp_setpersist(struct tcpcb * tp)3671 tcp_setpersist(struct tcpcb *tp)
3672 {
3673 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
3674 
3675 	/* If a PERSIST_TIMER option was set we will limit the
3676 	 * time the persist timer will be active for that connection
3677 	 * in order to avoid DOS by using zero window probes.
3678 	 * see rdar://5805356
3679 	 */
3680 
3681 	if (tp->t_persist_timeout != 0 &&
3682 	    tp->t_timer[TCPT_PERSIST] == 0 &&
3683 	    tp->t_persist_stop == 0) {
3684 		tp->t_persist_stop = tcp_now + tp->t_persist_timeout;
3685 	}
3686 
3687 	/*
3688 	 * Start/restart persistance timer.
3689 	 */
3690 	TCPT_RANGESET(tp->t_timer[TCPT_PERSIST],
3691 	    t * tcp_backoff[tp->t_rxtshift],
3692 	    tcptv_persmin_val, TCPTV_PERSMAX, 0);
3693 	tp->t_timer[TCPT_PERSIST] = OFFSET_FROM_START(tp, tp->t_timer[TCPT_PERSIST]);
3694 
3695 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT) {
3696 		tp->t_rxtshift++;
3697 	}
3698 }
3699 
3700 static int
tcp_recv_throttle(struct tcpcb * tp)3701 tcp_recv_throttle(struct tcpcb *tp)
3702 {
3703 	uint32_t base_rtt, newsize;
3704 	struct sockbuf *__single sbrcv = &tp->t_inpcb->inp_socket->so_rcv;
3705 
3706 	if (tcp_use_rtt_recvbg == 1 &&
3707 	    TSTMP_SUPPORTED(tp)) {
3708 		/*
3709 		 * Timestamps are supported on this connection. Use
3710 		 * RTT to look for an increase in latency.
3711 		 */
3712 
3713 		/*
3714 		 * If the connection is already being throttled, leave it
3715 		 * in that state until rtt comes closer to base rtt
3716 		 */
3717 		if (tp->t_flagsext & TF_RECV_THROTTLE) {
3718 			return 1;
3719 		}
3720 
3721 		base_rtt = get_base_rtt(tp);
3722 
3723 		if (base_rtt != 0 && tp->t_rttcur != 0) {
3724 			/*
3725 			 * if latency increased on a background flow,
3726 			 * return 1 to start throttling.
3727 			 */
3728 			if (tp->t_rttcur > (base_rtt + target_qdelay)) {
3729 				tp->t_flagsext |= TF_RECV_THROTTLE;
3730 				if (tp->t_recv_throttle_ts == 0) {
3731 					tp->t_recv_throttle_ts = tcp_now;
3732 				}
3733 				/*
3734 				 * Reduce the recv socket buffer size to
3735 				 * minimize latecy.
3736 				 */
3737 				if (sbrcv->sb_idealsize >
3738 				    tcp_recv_throttle_minwin) {
3739 					newsize = sbrcv->sb_idealsize >> 1;
3740 					/* Set a minimum of 16 K */
3741 					newsize =
3742 					    max(newsize,
3743 					    tcp_recv_throttle_minwin);
3744 					sbrcv->sb_idealsize = newsize;
3745 				}
3746 				return 1;
3747 			} else {
3748 				return 0;
3749 			}
3750 		}
3751 	}
3752 
3753 	/*
3754 	 * Timestamps are not supported or there is no good RTT
3755 	 * measurement. Use IPDV in this case.
3756 	 */
3757 	if (tp->acc_iaj > tcp_acc_iaj_react_limit) {
3758 		return 1;
3759 	}
3760 
3761 	return 0;
3762 }
3763