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