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