xref: /freebsd/sys/netinet/tcp_output.c (revision 624e87b673064ae228b79cde11b82f1ad7502bc3)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 #include "opt_kern_tls.h"
41 #include "opt_tcpdebug.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/arb.h>
46 #include <sys/domain.h>
47 #ifdef TCP_HHOOK
48 #include <sys/hhook.h>
49 #endif
50 #include <sys/kernel.h>
51 #ifdef KERN_TLS
52 #include <sys/ktls.h>
53 #endif
54 #include <sys/lock.h>
55 #include <sys/mbuf.h>
56 #include <sys/mutex.h>
57 #include <sys/protosw.h>
58 #include <sys/qmath.h>
59 #include <sys/sdt.h>
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
62 #include <sys/sysctl.h>
63 #include <sys/stats.h>
64 
65 #include <net/if.h>
66 #include <net/route.h>
67 #include <net/vnet.h>
68 
69 #include <netinet/in.h>
70 #include <netinet/in_kdtrace.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/ip.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/ip_var.h>
75 #include <netinet/ip_options.h>
76 #ifdef INET6
77 #include <netinet6/in6_pcb.h>
78 #include <netinet/ip6.h>
79 #include <netinet6/ip6_var.h>
80 #endif
81 #include <netinet/tcp.h>
82 #define	TCPOUTFLAGS
83 #include <netinet/tcp_fsm.h>
84 #include <netinet/tcp_log_buf.h>
85 #include <netinet/tcp_seq.h>
86 #include <netinet/tcp_timer.h>
87 #include <netinet/tcp_var.h>
88 #include <netinet/tcpip.h>
89 #include <netinet/cc/cc.h>
90 #include <netinet/tcp_fastopen.h>
91 #ifdef TCPPCAP
92 #include <netinet/tcp_pcap.h>
93 #endif
94 #ifdef TCPDEBUG
95 #include <netinet/tcp_debug.h>
96 #endif
97 #ifdef TCP_OFFLOAD
98 #include <netinet/tcp_offload.h>
99 #endif
100 
101 #include <netipsec/ipsec_support.h>
102 
103 #include <machine/in_cksum.h>
104 
105 #include <security/mac/mac_framework.h>
106 
107 VNET_DEFINE(int, path_mtu_discovery) = 1;
108 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_VNET | CTLFLAG_RW,
109 	&VNET_NAME(path_mtu_discovery), 1,
110 	"Enable Path MTU Discovery");
111 
112 VNET_DEFINE(int, tcp_do_tso) = 1;
113 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso, CTLFLAG_VNET | CTLFLAG_RW,
114 	&VNET_NAME(tcp_do_tso), 0,
115 	"Enable TCP Segmentation Offload");
116 
117 VNET_DEFINE(int, tcp_sendspace) = 1024*32;
118 #define	V_tcp_sendspace	VNET(tcp_sendspace)
119 SYSCTL_INT(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_VNET | CTLFLAG_RW,
120 	&VNET_NAME(tcp_sendspace), 0, "Initial send socket buffer size");
121 
122 VNET_DEFINE(int, tcp_do_autosndbuf) = 1;
123 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
124 	&VNET_NAME(tcp_do_autosndbuf), 0,
125 	"Enable automatic send buffer sizing");
126 
127 VNET_DEFINE(int, tcp_autosndbuf_inc) = 8*1024;
128 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
129 	&VNET_NAME(tcp_autosndbuf_inc), 0,
130 	"Incrementor step size of automatic send buffer");
131 
132 VNET_DEFINE(int, tcp_autosndbuf_max) = 2*1024*1024;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
134 	&VNET_NAME(tcp_autosndbuf_max), 0,
135 	"Max size of automatic send buffer");
136 
137 VNET_DEFINE(int, tcp_sendbuf_auto_lowat) = 0;
138 #define	V_tcp_sendbuf_auto_lowat	VNET(tcp_sendbuf_auto_lowat)
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto_lowat, CTLFLAG_VNET | CTLFLAG_RW,
140 	&VNET_NAME(tcp_sendbuf_auto_lowat), 0,
141 	"Modify threshold for auto send buffer growth to account for SO_SNDLOWAT");
142 
143 /*
144  * Make sure that either retransmit or persist timer is set for SYN, FIN and
145  * non-ACK.
146  */
147 #define TCP_XMIT_TIMER_ASSERT(tp, len, th_flags)			\
148 	KASSERT(((len) == 0 && ((th_flags) & (TH_SYN | TH_FIN)) == 0) ||\
149 	    tcp_timer_active((tp), TT_REXMT) ||				\
150 	    tcp_timer_active((tp), TT_PERSIST),				\
151 	    ("neither rexmt nor persist timer is set"))
152 
153 static void inline	cc_after_idle(struct tcpcb *tp);
154 
155 #ifdef TCP_HHOOK
156 /*
157  * Wrapper for the TCP established output helper hook.
158  */
159 void
160 hhook_run_tcp_est_out(struct tcpcb *tp, struct tcphdr *th,
161     struct tcpopt *to, uint32_t len, int tso)
162 {
163 	struct tcp_hhook_data hhook_data;
164 
165 	if (V_tcp_hhh[HHOOK_TCP_EST_OUT]->hhh_nhooks > 0) {
166 		hhook_data.tp = tp;
167 		hhook_data.th = th;
168 		hhook_data.to = to;
169 		hhook_data.len = len;
170 		hhook_data.tso = tso;
171 
172 		hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_OUT], &hhook_data,
173 		    tp->osd);
174 	}
175 }
176 #endif
177 
178 /*
179  * CC wrapper hook functions
180  */
181 static void inline
182 cc_after_idle(struct tcpcb *tp)
183 {
184 	INP_WLOCK_ASSERT(tp->t_inpcb);
185 
186 	if (CC_ALGO(tp)->after_idle != NULL)
187 		CC_ALGO(tp)->after_idle(tp->ccv);
188 }
189 
190 /*
191  * Tcp output routine: figure out what should be sent and send it.
192  */
193 int
194 tcp_output(struct tcpcb *tp)
195 {
196 	struct socket *so = tp->t_inpcb->inp_socket;
197 	int32_t len;
198 	uint32_t recwin, sendwin;
199 	int off, flags, error = 0;	/* Keep compiler happy */
200 	u_int if_hw_tsomaxsegcount = 0;
201 	u_int if_hw_tsomaxsegsize = 0;
202 	struct mbuf *m;
203 	struct ip *ip = NULL;
204 #ifdef TCPDEBUG
205 	struct ipovly *ipov = NULL;
206 #endif
207 	struct tcphdr *th;
208 	u_char opt[TCP_MAXOLEN];
209 	unsigned ipoptlen, optlen, hdrlen;
210 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
211 	unsigned ipsec_optlen = 0;
212 #endif
213 	int idle, sendalot, curticks;
214 	int sack_rxmit, sack_bytes_rxmt;
215 	struct sackhole *p;
216 	int tso, mtu;
217 	struct tcpopt to;
218 	unsigned int wanted_cookie = 0;
219 	unsigned int dont_sendalot = 0;
220 #if 0
221 	int maxburst = TCP_MAXBURST;
222 #endif
223 #ifdef INET6
224 	struct ip6_hdr *ip6 = NULL;
225 	int isipv6;
226 
227 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
228 #endif
229 #ifdef KERN_TLS
230 	const bool hw_tls = (so->so_snd.sb_flags & SB_TLS_IFNET) != 0;
231 #else
232 	const bool hw_tls = false;
233 #endif
234 
235 	INP_WLOCK_ASSERT(tp->t_inpcb);
236 
237 #ifdef TCP_OFFLOAD
238 	if (tp->t_flags & TF_TOE)
239 		return (tcp_offload_output(tp));
240 #endif
241 
242 	/*
243 	 * For TFO connections in SYN_SENT or SYN_RECEIVED,
244 	 * only allow the initial SYN or SYN|ACK and those sent
245 	 * by the retransmit timer.
246 	 */
247 	if (IS_FASTOPEN(tp->t_flags) &&
248 	    ((tp->t_state == TCPS_SYN_SENT) ||
249 	     (tp->t_state == TCPS_SYN_RECEIVED)) &&
250 	    SEQ_GT(tp->snd_max, tp->snd_una) && /* initial SYN or SYN|ACK sent */
251 	    (tp->snd_nxt != tp->snd_una))       /* not a retransmit */
252 		return (0);
253 
254 	/*
255 	 * Determine length of data that should be transmitted,
256 	 * and flags that will be used.
257 	 * If there is some data or critical controls (SYN, RST)
258 	 * to send, then transmit; otherwise, investigate further.
259 	 */
260 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
261 	if (idle && ticks - tp->t_rcvtime >= tp->t_rxtcur)
262 		cc_after_idle(tp);
263 	tp->t_flags &= ~TF_LASTIDLE;
264 	if (idle) {
265 		if (tp->t_flags & TF_MORETOCOME) {
266 			tp->t_flags |= TF_LASTIDLE;
267 			idle = 0;
268 		}
269 	}
270 again:
271 	/*
272 	 * If we've recently taken a timeout, snd_max will be greater than
273 	 * snd_nxt.  There may be SACK information that allows us to avoid
274 	 * resending already delivered data.  Adjust snd_nxt accordingly.
275 	 */
276 	if ((tp->t_flags & TF_SACK_PERMIT) &&
277 	    SEQ_LT(tp->snd_nxt, tp->snd_max))
278 		tcp_sack_adjust(tp);
279 	sendalot = 0;
280 	tso = 0;
281 	mtu = 0;
282 	off = tp->snd_nxt - tp->snd_una;
283 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
284 
285 	flags = tcp_outflags[tp->t_state];
286 	/*
287 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
288 	 * to send out new data (when sendalot is 1), bypass this function.
289 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
290 	 * we're replacing a (future) new transmission with a retransmission
291 	 * now, and we previously incremented snd_cwnd in tcp_input().
292 	 */
293 	/*
294 	 * Still in sack recovery , reset rxmit flag to zero.
295 	 */
296 	sack_rxmit = 0;
297 	sack_bytes_rxmt = 0;
298 	len = 0;
299 	p = NULL;
300 	if ((tp->t_flags & TF_SACK_PERMIT) && IN_FASTRECOVERY(tp->t_flags) &&
301 	    (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
302 		uint32_t cwin;
303 
304 		cwin =
305 		    imax(min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt, 0);
306 		/* Do not retransmit SACK segments beyond snd_recover */
307 		if (SEQ_GT(p->end, tp->snd_recover)) {
308 			/*
309 			 * (At least) part of sack hole extends beyond
310 			 * snd_recover. Check to see if we can rexmit data
311 			 * for this hole.
312 			 */
313 			if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
314 				/*
315 				 * Can't rexmit any more data for this hole.
316 				 * That data will be rexmitted in the next
317 				 * sack recovery episode, when snd_recover
318 				 * moves past p->rxmit.
319 				 */
320 				p = NULL;
321 				goto after_sack_rexmit;
322 			} else
323 				/* Can rexmit part of the current hole */
324 				len = ((int32_t)ulmin(cwin,
325 						   tp->snd_recover - p->rxmit));
326 		} else
327 			len = ((int32_t)ulmin(cwin, p->end - p->rxmit));
328 		off = p->rxmit - tp->snd_una;
329 		KASSERT(off >= 0,("%s: sack block to the left of una : %d",
330 		    __func__, off));
331 		if (len > 0) {
332 			sack_rxmit = 1;
333 			sendalot = 1;
334 			TCPSTAT_INC(tcps_sack_rexmits);
335 			TCPSTAT_ADD(tcps_sack_rexmit_bytes,
336 			    min(len, tp->t_maxseg));
337 		}
338 	}
339 after_sack_rexmit:
340 	/*
341 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
342 	 * state flags.
343 	 */
344 	if (tp->t_flags & TF_NEEDFIN)
345 		flags |= TH_FIN;
346 	if (tp->t_flags & TF_NEEDSYN)
347 		flags |= TH_SYN;
348 
349 	SOCKBUF_LOCK(&so->so_snd);
350 	/*
351 	 * If in persist timeout with window of 0, send 1 byte.
352 	 * Otherwise, if window is small but nonzero
353 	 * and timer expired, we will send what we can
354 	 * and go to transmit state.
355 	 */
356 	if (tp->t_flags & TF_FORCEDATA) {
357 		if (sendwin == 0) {
358 			/*
359 			 * If we still have some data to send, then
360 			 * clear the FIN bit.  Usually this would
361 			 * happen below when it realizes that we
362 			 * aren't sending all the data.  However,
363 			 * if we have exactly 1 byte of unsent data,
364 			 * then it won't clear the FIN bit below,
365 			 * and if we are in persist state, we wind
366 			 * up sending the packet without recording
367 			 * that we sent the FIN bit.
368 			 *
369 			 * We can't just blindly clear the FIN bit,
370 			 * because if we don't have any more data
371 			 * to send then the probe will be the FIN
372 			 * itself.
373 			 */
374 			if (off < sbused(&so->so_snd))
375 				flags &= ~TH_FIN;
376 			sendwin = 1;
377 		} else {
378 			tcp_timer_activate(tp, TT_PERSIST, 0);
379 			tp->t_rxtshift = 0;
380 		}
381 	}
382 
383 	/*
384 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
385 	 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
386 	 * a negative length.  This can also occur when TCP opens up
387 	 * its congestion window while receiving additional duplicate
388 	 * acks after fast-retransmit because TCP will reset snd_nxt
389 	 * to snd_max after the fast-retransmit.
390 	 *
391 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
392 	 * be set to snd_una, the offset will be 0, and the length may
393 	 * wind up 0.
394 	 *
395 	 * If sack_rxmit is true we are retransmitting from the scoreboard
396 	 * in which case len is already set.
397 	 */
398 	if (sack_rxmit == 0) {
399 		if (sack_bytes_rxmt == 0)
400 			len = ((int32_t)min(sbavail(&so->so_snd), sendwin) -
401 			    off);
402 		else {
403 			int32_t cwin;
404 
405                         /*
406 			 * We are inside of a SACK recovery episode and are
407 			 * sending new data, having retransmitted all the
408 			 * data possible in the scoreboard.
409 			 */
410 			len = ((int32_t)min(sbavail(&so->so_snd), tp->snd_wnd) -
411 			    off);
412 			/*
413 			 * Don't remove this (len > 0) check !
414 			 * We explicitly check for len > 0 here (although it
415 			 * isn't really necessary), to work around a gcc
416 			 * optimization issue - to force gcc to compute
417 			 * len above. Without this check, the computation
418 			 * of len is bungled by the optimizer.
419 			 */
420 			if (len > 0) {
421 				cwin = tp->snd_cwnd -
422 					(tp->snd_nxt - tp->sack_newdata) -
423 					sack_bytes_rxmt;
424 				if (cwin < 0)
425 					cwin = 0;
426 				len = imin(len, cwin);
427 			}
428 		}
429 	}
430 
431 	/*
432 	 * Lop off SYN bit if it has already been sent.  However, if this
433 	 * is SYN-SENT state and if segment contains data and if we don't
434 	 * know that foreign host supports TAO, suppress sending segment.
435 	 */
436 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
437 		if (tp->t_state != TCPS_SYN_RECEIVED)
438 			flags &= ~TH_SYN;
439 		/*
440 		 * When sending additional segments following a TFO SYN|ACK,
441 		 * do not include the SYN bit.
442 		 */
443 		if (IS_FASTOPEN(tp->t_flags) &&
444 		    (tp->t_state == TCPS_SYN_RECEIVED))
445 			flags &= ~TH_SYN;
446 		off--, len++;
447 	}
448 
449 	/*
450 	 * Be careful not to send data and/or FIN on SYN segments.
451 	 * This measure is needed to prevent interoperability problems
452 	 * with not fully conformant TCP implementations.
453 	 */
454 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
455 		len = 0;
456 		flags &= ~TH_FIN;
457 	}
458 
459 	/*
460 	 * On TFO sockets, ensure no data is sent in the following cases:
461 	 *
462 	 *  - When retransmitting SYN|ACK on a passively-created socket
463 	 *
464 	 *  - When retransmitting SYN on an actively created socket
465 	 *
466 	 *  - When sending a zero-length cookie (cookie request) on an
467 	 *    actively created socket
468 	 *
469 	 *  - When the socket is in the CLOSED state (RST is being sent)
470 	 */
471 	if (IS_FASTOPEN(tp->t_flags) &&
472 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
473 	     ((tp->t_state == TCPS_SYN_SENT) &&
474 	      (tp->t_tfo_client_cookie_len == 0)) ||
475 	     (flags & TH_RST)))
476 		len = 0;
477 	if (len <= 0) {
478 		/*
479 		 * If FIN has been sent but not acked,
480 		 * but we haven't been called to retransmit,
481 		 * len will be < 0.  Otherwise, window shrank
482 		 * after we sent into it.  If window shrank to 0,
483 		 * cancel pending retransmit, pull snd_nxt back
484 		 * to (closed) window, and set the persist timer
485 		 * if it isn't already going.  If the window didn't
486 		 * close completely, just wait for an ACK.
487 		 *
488 		 * We also do a general check here to ensure that
489 		 * we will set the persist timer when we have data
490 		 * to send, but a 0-byte window. This makes sure
491 		 * the persist timer is set even if the packet
492 		 * hits one of the "goto send" lines below.
493 		 */
494 		len = 0;
495 		if ((sendwin == 0) && (TCPS_HAVEESTABLISHED(tp->t_state)) &&
496 			(off < (int) sbavail(&so->so_snd))) {
497 			tcp_timer_activate(tp, TT_REXMT, 0);
498 			tp->t_rxtshift = 0;
499 			tp->snd_nxt = tp->snd_una;
500 			if (!tcp_timer_active(tp, TT_PERSIST))
501 				tcp_setpersist(tp);
502 		}
503 	}
504 
505 	/* len will be >= 0 after this point. */
506 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
507 
508 	tcp_sndbuf_autoscale(tp, so, sendwin);
509 
510 	/*
511 	 * Decide if we can use TCP Segmentation Offloading (if supported by
512 	 * hardware).
513 	 *
514 	 * TSO may only be used if we are in a pure bulk sending state.  The
515 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and
516 	 * IP options prevent using TSO.  With TSO the TCP header is the same
517 	 * (except for the sequence number) for all generated packets.  This
518 	 * makes it impossible to transmit any options which vary per generated
519 	 * segment or packet.
520 	 *
521 	 * IPv4 handling has a clear separation of ip options and ip header
522 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
523 	 * the right thing below to provide length of just ip options and thus
524 	 * checking for ipoptlen is enough to decide if ip options are present.
525 	 */
526 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
527 	/*
528 	 * Pre-calculate here as we save another lookup into the darknesses
529 	 * of IPsec that way and can actually decide if TSO is ok.
530 	 */
531 #ifdef INET6
532 	if (isipv6 && IPSEC_ENABLED(ipv6))
533 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, tp->t_inpcb);
534 #ifdef INET
535 	else
536 #endif
537 #endif /* INET6 */
538 #ifdef INET
539 	if (IPSEC_ENABLED(ipv4))
540 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, tp->t_inpcb);
541 #endif /* INET */
542 #endif /* IPSEC */
543 #ifdef INET6
544 	if (isipv6)
545 		ipoptlen = ip6_optlen(tp->t_inpcb);
546 	else
547 #endif
548 	if (tp->t_inpcb->inp_options)
549 		ipoptlen = tp->t_inpcb->inp_options->m_len -
550 				offsetof(struct ipoption, ipopt_list);
551 	else
552 		ipoptlen = 0;
553 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
554 	ipoptlen += ipsec_optlen;
555 #endif
556 
557 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > tp->t_maxseg &&
558 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
559 	    tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
560 	    ipoptlen == 0 && !(flags & TH_SYN))
561 		tso = 1;
562 
563 	if (sack_rxmit) {
564 		if (SEQ_LT(p->rxmit + len, tp->snd_una + sbused(&so->so_snd)))
565 			flags &= ~TH_FIN;
566 	} else {
567 		if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
568 		    sbused(&so->so_snd)))
569 			flags &= ~TH_FIN;
570 	}
571 
572 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
573 	    (long)TCP_MAXWIN << tp->rcv_scale);
574 
575 	/*
576 	 * Sender silly window avoidance.   We transmit under the following
577 	 * conditions when len is non-zero:
578 	 *
579 	 *	- We have a full segment (or more with TSO)
580 	 *	- This is the last buffer in a write()/send() and we are
581 	 *	  either idle or running NODELAY
582 	 *	- we've timed out (e.g. persist timer)
583 	 *	- we have more then 1/2 the maximum send window's worth of
584 	 *	  data (receiver may be limited the window size)
585 	 *	- we need to retransmit
586 	 */
587 	if (len) {
588 		if (len >= tp->t_maxseg)
589 			goto send;
590 		/*
591 		 * NOTE! on localhost connections an 'ack' from the remote
592 		 * end may occur synchronously with the output and cause
593 		 * us to flush a buffer queued with moretocome.  XXX
594 		 *
595 		 * note: the len + off check is almost certainly unnecessary.
596 		 */
597 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
598 		    (idle || (tp->t_flags & TF_NODELAY)) &&
599 		    (uint32_t)len + (uint32_t)off >= sbavail(&so->so_snd) &&
600 		    (tp->t_flags & TF_NOPUSH) == 0) {
601 			goto send;
602 		}
603 		if (tp->t_flags & TF_FORCEDATA)		/* typ. timeout case */
604 			goto send;
605 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
606 			goto send;
607 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
608 			goto send;
609 		if (sack_rxmit)
610 			goto send;
611 	}
612 
613 	/*
614 	 * Sending of standalone window updates.
615 	 *
616 	 * Window updates are important when we close our window due to a
617 	 * full socket buffer and are opening it again after the application
618 	 * reads data from it.  Once the window has opened again and the
619 	 * remote end starts to send again the ACK clock takes over and
620 	 * provides the most current window information.
621 	 *
622 	 * We must avoid the silly window syndrome whereas every read
623 	 * from the receive buffer, no matter how small, causes a window
624 	 * update to be sent.  We also should avoid sending a flurry of
625 	 * window updates when the socket buffer had queued a lot of data
626 	 * and the application is doing small reads.
627 	 *
628 	 * Prevent a flurry of pointless window updates by only sending
629 	 * an update when we can increase the advertized window by more
630 	 * than 1/4th of the socket buffer capacity.  When the buffer is
631 	 * getting full or is very small be more aggressive and send an
632 	 * update whenever we can increase by two mss sized segments.
633 	 * In all other situations the ACK's to new incoming data will
634 	 * carry further window increases.
635 	 *
636 	 * Don't send an independent window update if a delayed
637 	 * ACK is pending (it will get piggy-backed on it) or the
638 	 * remote side already has done a half-close and won't send
639 	 * more data.  Skip this if the connection is in T/TCP
640 	 * half-open state.
641 	 */
642 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
643 	    !(tp->t_flags & TF_DELACK) &&
644 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
645 		/*
646 		 * "adv" is the amount we could increase the window,
647 		 * taking into account that we are limited by
648 		 * TCP_MAXWIN << tp->rcv_scale.
649 		 */
650 		int32_t adv;
651 		int oldwin;
652 
653 		adv = recwin;
654 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
655 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
656 			adv -= oldwin;
657 		} else
658 			oldwin = 0;
659 
660 		/*
661 		 * If the new window size ends up being the same as or less
662 		 * than the old size when it is scaled, then don't force
663 		 * a window update.
664 		 */
665 		if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
666 			goto dontupdate;
667 
668 		if (adv >= (int32_t)(2 * tp->t_maxseg) &&
669 		    (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
670 		     recwin <= (so->so_rcv.sb_hiwat / 8) ||
671 		     so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg ||
672 		     adv >= TCP_MAXWIN << tp->rcv_scale))
673 			goto send;
674 		if (2 * adv >= (int32_t)so->so_rcv.sb_hiwat)
675 			goto send;
676 	}
677 dontupdate:
678 
679 	/*
680 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
681 	 * is also a catch-all for the retransmit timer timeout case.
682 	 */
683 	if (tp->t_flags & TF_ACKNOW)
684 		goto send;
685 	if ((flags & TH_RST) ||
686 	    ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
687 		goto send;
688 	if (SEQ_GT(tp->snd_up, tp->snd_una))
689 		goto send;
690 	/*
691 	 * If our state indicates that FIN should be sent
692 	 * and we have not yet done so, then we need to send.
693 	 */
694 	if (flags & TH_FIN &&
695 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
696 		goto send;
697 	/*
698 	 * In SACK, it is possible for tcp_output to fail to send a segment
699 	 * after the retransmission timer has been turned off.  Make sure
700 	 * that the retransmission timer is set.
701 	 */
702 	if ((tp->t_flags & TF_SACK_PERMIT) &&
703 	    SEQ_GT(tp->snd_max, tp->snd_una) &&
704 	    !tcp_timer_active(tp, TT_REXMT) &&
705 	    !tcp_timer_active(tp, TT_PERSIST)) {
706 		tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
707 		goto just_return;
708 	}
709 	/*
710 	 * TCP window updates are not reliable, rather a polling protocol
711 	 * using ``persist'' packets is used to insure receipt of window
712 	 * updates.  The three ``states'' for the output side are:
713 	 *	idle			not doing retransmits or persists
714 	 *	persisting		to move a small or zero window
715 	 *	(re)transmitting	and thereby not persisting
716 	 *
717 	 * tcp_timer_active(tp, TT_PERSIST)
718 	 *	is true when we are in persist state.
719 	 * (tp->t_flags & TF_FORCEDATA)
720 	 *	is set when we are called to send a persist packet.
721 	 * tcp_timer_active(tp, TT_REXMT)
722 	 *	is set when we are retransmitting
723 	 * The output side is idle when both timers are zero.
724 	 *
725 	 * If send window is too small, there is data to transmit, and no
726 	 * retransmit or persist is pending, then go to persist state.
727 	 * If nothing happens soon, send when timer expires:
728 	 * if window is nonzero, transmit what we can,
729 	 * otherwise force out a byte.
730 	 */
731 	if (sbavail(&so->so_snd) && !tcp_timer_active(tp, TT_REXMT) &&
732 	    !tcp_timer_active(tp, TT_PERSIST)) {
733 		tp->t_rxtshift = 0;
734 		tcp_setpersist(tp);
735 	}
736 
737 	/*
738 	 * No reason to send a segment, just return.
739 	 */
740 just_return:
741 	SOCKBUF_UNLOCK(&so->so_snd);
742 	return (0);
743 
744 send:
745 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
746 	if (len > 0) {
747 		if (len >= tp->t_maxseg)
748 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
749 		else
750 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
751 	}
752 	/*
753 	 * Before ESTABLISHED, force sending of initial options
754 	 * unless TCP set not to do any options.
755 	 * NOTE: we assume that the IP/TCP header plus TCP options
756 	 * always fit in a single mbuf, leaving room for a maximum
757 	 * link header, i.e.
758 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
759 	 */
760 	optlen = 0;
761 #ifdef INET6
762 	if (isipv6)
763 		hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
764 	else
765 #endif
766 		hdrlen = sizeof (struct tcpiphdr);
767 
768 	/*
769 	 * Compute options for segment.
770 	 * We only have to care about SYN and established connection
771 	 * segments.  Options for SYN-ACK segments are handled in TCP
772 	 * syncache.
773 	 */
774 	to.to_flags = 0;
775 	if ((tp->t_flags & TF_NOOPT) == 0) {
776 		/* Maximum segment size. */
777 		if (flags & TH_SYN) {
778 			tp->snd_nxt = tp->iss;
779 			to.to_mss = tcp_mssopt(&tp->t_inpcb->inp_inc);
780 			to.to_flags |= TOF_MSS;
781 
782 			/*
783 			 * On SYN or SYN|ACK transmits on TFO connections,
784 			 * only include the TFO option if it is not a
785 			 * retransmit, as the presence of the TFO option may
786 			 * have caused the original SYN or SYN|ACK to have
787 			 * been dropped by a middlebox.
788 			 */
789 			if (IS_FASTOPEN(tp->t_flags) &&
790 			    (tp->t_rxtshift == 0)) {
791 				if (tp->t_state == TCPS_SYN_RECEIVED) {
792 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
793 					to.to_tfo_cookie =
794 					    (u_int8_t *)&tp->t_tfo_cookie.server;
795 					to.to_flags |= TOF_FASTOPEN;
796 					wanted_cookie = 1;
797 				} else if (tp->t_state == TCPS_SYN_SENT) {
798 					to.to_tfo_len =
799 					    tp->t_tfo_client_cookie_len;
800 					to.to_tfo_cookie =
801 					    tp->t_tfo_cookie.client;
802 					to.to_flags |= TOF_FASTOPEN;
803 					wanted_cookie = 1;
804 					/*
805 					 * If we wind up having more data to
806 					 * send with the SYN than can fit in
807 					 * one segment, don't send any more
808 					 * until the SYN|ACK comes back from
809 					 * the other end.
810 					 */
811 					dont_sendalot = 1;
812 				}
813 			}
814 		}
815 		/* Window scaling. */
816 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
817 			to.to_wscale = tp->request_r_scale;
818 			to.to_flags |= TOF_SCALE;
819 		}
820 		/* Timestamps. */
821 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
822 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
823 			curticks = tcp_ts_getticks();
824 			to.to_tsval = curticks + tp->ts_offset;
825 			to.to_tsecr = tp->ts_recent;
826 			to.to_flags |= TOF_TS;
827 			if (tp->t_rxtshift == 1)
828 				tp->t_badrxtwin = curticks;
829 		}
830 
831 		/* Set receive buffer autosizing timestamp. */
832 		if (tp->rfbuf_ts == 0 &&
833 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
834 			tp->rfbuf_ts = tcp_ts_getticks();
835 
836 		/* Selective ACK's. */
837 		if (tp->t_flags & TF_SACK_PERMIT) {
838 			if (flags & TH_SYN)
839 				to.to_flags |= TOF_SACKPERM;
840 			else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
841 			    (tp->t_flags & TF_SACK_PERMIT) &&
842 			    tp->rcv_numsacks > 0) {
843 				to.to_flags |= TOF_SACK;
844 				to.to_nsacks = tp->rcv_numsacks;
845 				to.to_sacks = (u_char *)tp->sackblks;
846 			}
847 		}
848 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
849 		/* TCP-MD5 (RFC2385). */
850 		/*
851 		 * Check that TCP_MD5SIG is enabled in tcpcb to
852 		 * account the size needed to set this TCP option.
853 		 */
854 		if (tp->t_flags & TF_SIGNATURE)
855 			to.to_flags |= TOF_SIGNATURE;
856 #endif /* TCP_SIGNATURE */
857 
858 		/* Processing the options. */
859 		hdrlen += optlen = tcp_addoptions(&to, opt);
860 		/*
861 		 * If we wanted a TFO option to be added, but it was unable
862 		 * to fit, ensure no data is sent.
863 		 */
864 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
865 		    !(to.to_flags & TOF_FASTOPEN))
866 			len = 0;
867 	}
868 
869 	/*
870 	 * Adjust data length if insertion of options will
871 	 * bump the packet length beyond the t_maxseg length.
872 	 * Clear the FIN bit because we cut off the tail of
873 	 * the segment.
874 	 */
875 	if (len + optlen + ipoptlen > tp->t_maxseg) {
876 		flags &= ~TH_FIN;
877 
878 		if (tso) {
879 			u_int if_hw_tsomax;
880 			u_int moff;
881 			int max_len;
882 
883 			/* extract TSO information */
884 			if_hw_tsomax = tp->t_tsomax;
885 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
886 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
887 
888 			/*
889 			 * Limit a TSO burst to prevent it from
890 			 * overflowing or exceeding the maximum length
891 			 * allowed by the network interface:
892 			 */
893 			KASSERT(ipoptlen == 0,
894 			    ("%s: TSO can't do IP options", __func__));
895 
896 			/*
897 			 * Check if we should limit by maximum payload
898 			 * length:
899 			 */
900 			if (if_hw_tsomax != 0) {
901 				/* compute maximum TSO length */
902 				max_len = (if_hw_tsomax - hdrlen -
903 				    max_linkhdr);
904 				if (max_len <= 0) {
905 					len = 0;
906 				} else if (len > max_len) {
907 					sendalot = 1;
908 					len = max_len;
909 				}
910 			}
911 
912 			/*
913 			 * Prevent the last segment from being
914 			 * fractional unless the send sockbuf can be
915 			 * emptied:
916 			 */
917 			max_len = (tp->t_maxseg - optlen);
918 			if (((uint32_t)off + (uint32_t)len) <
919 			    sbavail(&so->so_snd)) {
920 				moff = len % max_len;
921 				if (moff != 0) {
922 					len -= moff;
923 					sendalot = 1;
924 				}
925 			}
926 
927 			/*
928 			 * In case there are too many small fragments
929 			 * don't use TSO:
930 			 */
931 			if (len <= max_len) {
932 				len = max_len;
933 				sendalot = 1;
934 				tso = 0;
935 			}
936 
937 			/*
938 			 * Send the FIN in a separate segment
939 			 * after the bulk sending is done.
940 			 * We don't trust the TSO implementations
941 			 * to clear the FIN flag on all but the
942 			 * last segment.
943 			 */
944 			if (tp->t_flags & TF_NEEDFIN)
945 				sendalot = 1;
946 		} else {
947 			if (optlen + ipoptlen >= tp->t_maxseg) {
948 				/*
949 				 * Since we don't have enough space to put
950 				 * the IP header chain and the TCP header in
951 				 * one packet as required by RFC 7112, don't
952 				 * send it. Also ensure that at least one
953 				 * byte of the payload can be put into the
954 				 * TCP segment.
955 				 */
956 				SOCKBUF_UNLOCK(&so->so_snd);
957 				error = EMSGSIZE;
958 				sack_rxmit = 0;
959 				goto out;
960 			}
961 			len = tp->t_maxseg - optlen - ipoptlen;
962 			sendalot = 1;
963 			if (dont_sendalot)
964 				sendalot = 0;
965 		}
966 	} else
967 		tso = 0;
968 
969 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
970 	    ("%s: len > IP_MAXPACKET", __func__));
971 
972 /*#ifdef DIAGNOSTIC*/
973 #ifdef INET6
974 	if (max_linkhdr + hdrlen > MCLBYTES)
975 #else
976 	if (max_linkhdr + hdrlen > MHLEN)
977 #endif
978 		panic("tcphdr too big");
979 /*#endif*/
980 
981 	/*
982 	 * This KASSERT is here to catch edge cases at a well defined place.
983 	 * Before, those had triggered (random) panic conditions further down.
984 	 */
985 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
986 
987 	/*
988 	 * Grab a header mbuf, attaching a copy of data to
989 	 * be transmitted, and initialize the header from
990 	 * the template for sends on this connection.
991 	 */
992 	if (len) {
993 		struct mbuf *mb;
994 		struct sockbuf *msb;
995 		u_int moff;
996 
997 		if ((tp->t_flags & TF_FORCEDATA) && len == 1) {
998 			TCPSTAT_INC(tcps_sndprobe);
999 #ifdef STATS
1000 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
1001 				stats_voi_update_abs_u32(tp->t_stats,
1002 				VOI_TCP_RETXPB, len);
1003 			else
1004 				stats_voi_update_abs_u64(tp->t_stats,
1005 				    VOI_TCP_TXPB, len);
1006 #endif /* STATS */
1007 		} else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
1008 			tp->t_sndrexmitpack++;
1009 			TCPSTAT_INC(tcps_sndrexmitpack);
1010 			TCPSTAT_ADD(tcps_sndrexmitbyte, len);
1011 #ifdef STATS
1012 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
1013 			    len);
1014 #endif /* STATS */
1015 		} else {
1016 			TCPSTAT_INC(tcps_sndpack);
1017 			TCPSTAT_ADD(tcps_sndbyte, len);
1018 #ifdef STATS
1019 			stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
1020 			    len);
1021 #endif /* STATS */
1022 		}
1023 #ifdef INET6
1024 		if (MHLEN < hdrlen + max_linkhdr)
1025 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1026 		else
1027 #endif
1028 			m = m_gethdr(M_NOWAIT, MT_DATA);
1029 
1030 		if (m == NULL) {
1031 			SOCKBUF_UNLOCK(&so->so_snd);
1032 			error = ENOBUFS;
1033 			sack_rxmit = 0;
1034 			goto out;
1035 		}
1036 
1037 		m->m_data += max_linkhdr;
1038 		m->m_len = hdrlen;
1039 
1040 		/*
1041 		 * Start the m_copy functions from the closest mbuf
1042 		 * to the offset in the socket buffer chain.
1043 		 */
1044 		mb = sbsndptr_noadv(&so->so_snd, off, &moff);
1045 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
1046 			m_copydata(mb, moff, len,
1047 			    mtod(m, caddr_t) + hdrlen);
1048 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
1049 				sbsndptr_adv(&so->so_snd, mb, len);
1050 			m->m_len += len;
1051 		} else {
1052 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
1053 				msb = NULL;
1054 			else
1055 				msb = &so->so_snd;
1056 			m->m_next = tcp_m_copym(mb, moff,
1057 			    &len, if_hw_tsomaxsegcount,
1058 			    if_hw_tsomaxsegsize, msb, hw_tls);
1059 			if (len <= (tp->t_maxseg - optlen)) {
1060 				/*
1061 				 * Must have ran out of mbufs for the copy
1062 				 * shorten it to no longer need tso. Lets
1063 				 * not put on sendalot since we are low on
1064 				 * mbufs.
1065 				 */
1066 				tso = 0;
1067 			}
1068 			if (m->m_next == NULL) {
1069 				SOCKBUF_UNLOCK(&so->so_snd);
1070 				(void) m_free(m);
1071 				error = ENOBUFS;
1072 				sack_rxmit = 0;
1073 				goto out;
1074 			}
1075 		}
1076 
1077 		/*
1078 		 * If we're sending everything we've got, set PUSH.
1079 		 * (This will keep happy those implementations which only
1080 		 * give data to the user when a buffer fills or
1081 		 * a PUSH comes in.)
1082 		 */
1083 		if (((uint32_t)off + (uint32_t)len == sbused(&so->so_snd)) &&
1084 		    !(flags & TH_SYN))
1085 			flags |= TH_PUSH;
1086 		SOCKBUF_UNLOCK(&so->so_snd);
1087 	} else {
1088 		SOCKBUF_UNLOCK(&so->so_snd);
1089 		if (tp->t_flags & TF_ACKNOW)
1090 			TCPSTAT_INC(tcps_sndacks);
1091 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
1092 			TCPSTAT_INC(tcps_sndctrl);
1093 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
1094 			TCPSTAT_INC(tcps_sndurg);
1095 		else
1096 			TCPSTAT_INC(tcps_sndwinup);
1097 
1098 		m = m_gethdr(M_NOWAIT, MT_DATA);
1099 		if (m == NULL) {
1100 			error = ENOBUFS;
1101 			sack_rxmit = 0;
1102 			goto out;
1103 		}
1104 #ifdef INET6
1105 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
1106 		    MHLEN >= hdrlen) {
1107 			M_ALIGN(m, hdrlen);
1108 		} else
1109 #endif
1110 		m->m_data += max_linkhdr;
1111 		m->m_len = hdrlen;
1112 	}
1113 	SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
1114 	m->m_pkthdr.rcvif = (struct ifnet *)0;
1115 #ifdef MAC
1116 	mac_inpcb_create_mbuf(tp->t_inpcb, m);
1117 #endif
1118 #ifdef INET6
1119 	if (isipv6) {
1120 		ip6 = mtod(m, struct ip6_hdr *);
1121 		th = (struct tcphdr *)(ip6 + 1);
1122 		tcpip_fillheaders(tp->t_inpcb, ip6, th);
1123 	} else
1124 #endif /* INET6 */
1125 	{
1126 		ip = mtod(m, struct ip *);
1127 #ifdef TCPDEBUG
1128 		ipov = (struct ipovly *)ip;
1129 #endif
1130 		th = (struct tcphdr *)(ip + 1);
1131 		tcpip_fillheaders(tp->t_inpcb, ip, th);
1132 	}
1133 
1134 	/*
1135 	 * Fill in fields, remembering maximum advertised
1136 	 * window for use in delaying messages about window sizes.
1137 	 * If resending a FIN, be sure not to use a new sequence number.
1138 	 */
1139 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
1140 	    tp->snd_nxt == tp->snd_max)
1141 		tp->snd_nxt--;
1142 	/*
1143 	 * If we are starting a connection, send ECN setup
1144 	 * SYN packet. If we are on a retransmit, we may
1145 	 * resend those bits a number of times as per
1146 	 * RFC 3168.
1147 	 */
1148 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
1149 		if (tp->t_rxtshift >= 1) {
1150 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
1151 				flags |= TH_ECE|TH_CWR;
1152 		} else
1153 			flags |= TH_ECE|TH_CWR;
1154 	}
1155 
1156 	if (tp->t_state == TCPS_ESTABLISHED &&
1157 	    (tp->t_flags2 & TF2_ECN_PERMIT)) {
1158 		/*
1159 		 * If the peer has ECN, mark data packets with
1160 		 * ECN capable transmission (ECT).
1161 		 * Ignore pure ack packets, retransmissions and window probes.
1162 		 */
1163 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
1164 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
1165 #ifdef INET6
1166 			if (isipv6)
1167 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
1168 			else
1169 #endif
1170 				ip->ip_tos |= IPTOS_ECN_ECT0;
1171 			TCPSTAT_INC(tcps_ecn_ect0);
1172 		}
1173 
1174 		/*
1175 		 * Reply with proper ECN notifications.
1176 		 */
1177 		if (tp->t_flags2 & TF2_ECN_SND_CWR) {
1178 			flags |= TH_CWR;
1179 			tp->t_flags2 &= ~TF2_ECN_SND_CWR;
1180 		}
1181 		if (tp->t_flags2 & TF2_ECN_SND_ECE)
1182 			flags |= TH_ECE;
1183 	}
1184 
1185 	/*
1186 	 * If we are doing retransmissions, then snd_nxt will
1187 	 * not reflect the first unsent octet.  For ACK only
1188 	 * packets, we do not want the sequence number of the
1189 	 * retransmitted packet, we want the sequence number
1190 	 * of the next unsent octet.  So, if there is no data
1191 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
1192 	 * when filling in ti_seq.  But if we are in persist
1193 	 * state, snd_max might reflect one byte beyond the
1194 	 * right edge of the window, so use snd_nxt in that
1195 	 * case, since we know we aren't doing a retransmission.
1196 	 * (retransmit and persist are mutually exclusive...)
1197 	 */
1198 	if (sack_rxmit == 0) {
1199 		if (len || (flags & (TH_SYN|TH_FIN)) ||
1200 		    tcp_timer_active(tp, TT_PERSIST))
1201 			th->th_seq = htonl(tp->snd_nxt);
1202 		else
1203 			th->th_seq = htonl(tp->snd_max);
1204 	} else {
1205 		th->th_seq = htonl(p->rxmit);
1206 		p->rxmit += len;
1207 		tp->sackhint.sack_bytes_rexmit += len;
1208 	}
1209 	th->th_ack = htonl(tp->rcv_nxt);
1210 	if (optlen) {
1211 		bcopy(opt, th + 1, optlen);
1212 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1213 	}
1214 	th->th_flags = flags;
1215 	/*
1216 	 * Calculate receive window.  Don't shrink window,
1217 	 * but avoid silly window syndrome.
1218 	 * If a RST segment is sent, advertise a window of zero.
1219 	 */
1220 	if (flags & TH_RST) {
1221 		recwin = 0;
1222 	} else {
1223 		if (recwin < (so->so_rcv.sb_hiwat / 4) &&
1224 		    recwin < tp->t_maxseg)
1225 			recwin = 0;
1226 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
1227 		    recwin < (tp->rcv_adv - tp->rcv_nxt))
1228 			recwin = (tp->rcv_adv - tp->rcv_nxt);
1229 	}
1230 	/*
1231 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1232 	 * or <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK>
1233 	 * case is handled in syncache.
1234 	 */
1235 	if (flags & TH_SYN)
1236 		th->th_win = htons((u_short)
1237 				(min(sbspace(&so->so_rcv), TCP_MAXWIN)));
1238 	else
1239 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
1240 
1241 	/*
1242 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
1243 	 * a 0 window.  This may cause the remote transmitter to stall.  This
1244 	 * flag tells soreceive() to disable delayed acknowledgements when
1245 	 * draining the buffer.  This can occur if the receiver is attempting
1246 	 * to read more data than can be buffered prior to transmitting on
1247 	 * the connection.
1248 	 */
1249 	if (th->th_win == 0) {
1250 		tp->t_sndzerowin++;
1251 		tp->t_flags |= TF_RXWIN0SENT;
1252 	} else
1253 		tp->t_flags &= ~TF_RXWIN0SENT;
1254 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1255 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
1256 		th->th_flags |= TH_URG;
1257 	} else
1258 		/*
1259 		 * If no urgent pointer to send, then we pull
1260 		 * the urgent pointer to the left edge of the send window
1261 		 * so that it doesn't drift into the send window on sequence
1262 		 * number wraparound.
1263 		 */
1264 		tp->snd_up = tp->snd_una;		/* drag it along */
1265 
1266 	/*
1267 	 * Put TCP length in extended header, and then
1268 	 * checksum extended header and data.
1269 	 */
1270 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
1271 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1272 
1273 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1274 	if (to.to_flags & TOF_SIGNATURE) {
1275 		/*
1276 		 * Calculate MD5 signature and put it into the place
1277 		 * determined before.
1278 		 * NOTE: since TCP options buffer doesn't point into
1279 		 * mbuf's data, calculate offset and use it.
1280 		 */
1281 		if (!TCPMD5_ENABLED() || (error = TCPMD5_OUTPUT(m, th,
1282 		    (u_char *)(th + 1) + (to.to_signature - opt))) != 0) {
1283 			/*
1284 			 * Do not send segment if the calculation of MD5
1285 			 * digest has failed.
1286 			 */
1287 			m_freem(m);
1288 			goto out;
1289 		}
1290 	}
1291 #endif
1292 #ifdef INET6
1293 	if (isipv6) {
1294 		/*
1295 		 * There is no need to fill in ip6_plen right now.
1296 		 * It will be filled later by ip6_output.
1297 		 */
1298 		m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
1299 		th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
1300 		    optlen + len, IPPROTO_TCP, 0);
1301 	}
1302 #endif
1303 #if defined(INET6) && defined(INET)
1304 	else
1305 #endif
1306 #ifdef INET
1307 	{
1308 		m->m_pkthdr.csum_flags = CSUM_TCP;
1309 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1310 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP + len + optlen));
1311 
1312 		/* IP version must be set here for ipv4/ipv6 checking later */
1313 		KASSERT(ip->ip_v == IPVERSION,
1314 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
1315 	}
1316 #endif
1317 
1318 	/*
1319 	 * Enable TSO and specify the size of the segments.
1320 	 * The TCP pseudo header checksum is always provided.
1321 	 */
1322 	if (tso) {
1323 		KASSERT(len > tp->t_maxseg - optlen,
1324 		    ("%s: len <= tso_segsz", __func__));
1325 		m->m_pkthdr.csum_flags |= CSUM_TSO;
1326 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
1327 	}
1328 
1329 	KASSERT(len + hdrlen == m_length(m, NULL),
1330 	    ("%s: mbuf chain shorter than expected: %d + %u != %u",
1331 	    __func__, len, hdrlen, m_length(m, NULL)));
1332 
1333 #ifdef TCP_HHOOK
1334 	/* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
1335 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
1336 #endif
1337 
1338 #ifdef TCPDEBUG
1339 	/*
1340 	 * Trace.
1341 	 */
1342 	if (so->so_options & SO_DEBUG) {
1343 		u_short save = 0;
1344 #ifdef INET6
1345 		if (!isipv6)
1346 #endif
1347 		{
1348 			save = ipov->ih_len;
1349 			ipov->ih_len = htons(m->m_pkthdr.len /* - hdrlen + (th->th_off << 2) */);
1350 		}
1351 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
1352 #ifdef INET6
1353 		if (!isipv6)
1354 #endif
1355 		ipov->ih_len = save;
1356 	}
1357 #endif /* TCPDEBUG */
1358 	TCP_PROBE3(debug__output, tp, th, m);
1359 
1360 	/* We're getting ready to send; log now. */
1361 	TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
1362 	    len, NULL, false);
1363 
1364 	/*
1365 	 * Fill in IP length and desired time to live and
1366 	 * send to IP level.  There should be a better way
1367 	 * to handle ttl and tos; we could keep them in
1368 	 * the template, but need a way to checksum without them.
1369 	 */
1370 	/*
1371 	 * m->m_pkthdr.len should have been set before checksum calculation,
1372 	 * because in6_cksum() need it.
1373 	 */
1374 #ifdef INET6
1375 	if (isipv6) {
1376 		/*
1377 		 * we separately set hoplimit for every segment, since the
1378 		 * user might want to change the value via setsockopt.
1379 		 * Also, desired default hop limit might be changed via
1380 		 * Neighbor Discovery.
1381 		 */
1382 		ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb, NULL);
1383 
1384 		/*
1385 		 * Set the packet size here for the benefit of DTrace probes.
1386 		 * ip6_output() will set it properly; it's supposed to include
1387 		 * the option header lengths as well.
1388 		 */
1389 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
1390 
1391 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
1392 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
1393 		else
1394 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
1395 
1396 		if (tp->t_state == TCPS_SYN_SENT)
1397 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
1398 
1399 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
1400 
1401 #ifdef TCPPCAP
1402 		/* Save packet, if requested. */
1403 		tcp_pcap_add(th, m, &(tp->t_outpkts));
1404 #endif
1405 
1406 		/* TODO: IPv6 IP6TOS_ECT bit on */
1407 		error = ip6_output(m, tp->t_inpcb->in6p_outputopts,
1408 		    &tp->t_inpcb->inp_route6,
1409 		    ((so->so_options & SO_DONTROUTE) ?  IP_ROUTETOIF : 0),
1410 		    NULL, NULL, tp->t_inpcb);
1411 
1412 		if (error == EMSGSIZE && tp->t_inpcb->inp_route6.ro_rt != NULL)
1413 			mtu = tp->t_inpcb->inp_route6.ro_rt->rt_mtu;
1414 	}
1415 #endif /* INET6 */
1416 #if defined(INET) && defined(INET6)
1417 	else
1418 #endif
1419 #ifdef INET
1420     {
1421 	ip->ip_len = htons(m->m_pkthdr.len);
1422 #ifdef INET6
1423 	if (tp->t_inpcb->inp_vflag & INP_IPV6PROTO)
1424 		ip->ip_ttl = in6_selecthlim(tp->t_inpcb, NULL);
1425 #endif /* INET6 */
1426 	/*
1427 	 * If we do path MTU discovery, then we set DF on every packet.
1428 	 * This might not be the best thing to do according to RFC3390
1429 	 * Section 2. However the tcp hostcache migitates the problem
1430 	 * so it affects only the first tcp connection with a host.
1431 	 *
1432 	 * NB: Don't set DF on small MTU/MSS to have a safe fallback.
1433 	 */
1434 	if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
1435 		ip->ip_off |= htons(IP_DF);
1436 		tp->t_flags2 |= TF2_PLPMTU_PMTUD;
1437 	} else {
1438 		tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
1439 	}
1440 
1441 	if (tp->t_state == TCPS_SYN_SENT)
1442 		TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
1443 
1444 	TCP_PROBE5(send, NULL, tp, ip, tp, th);
1445 
1446 #ifdef TCPPCAP
1447 	/* Save packet, if requested. */
1448 	tcp_pcap_add(th, m, &(tp->t_outpkts));
1449 #endif
1450 
1451 	error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
1452 	    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
1453 	    tp->t_inpcb);
1454 
1455 	if (error == EMSGSIZE && tp->t_inpcb->inp_route.ro_rt != NULL)
1456 		mtu = tp->t_inpcb->inp_route.ro_rt->rt_mtu;
1457     }
1458 #endif /* INET */
1459 
1460 out:
1461 	/*
1462 	 * In transmit state, time the transmission and arrange for
1463 	 * the retransmit.  In persist state, just set snd_max.
1464 	 */
1465 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
1466 	    !tcp_timer_active(tp, TT_PERSIST)) {
1467 		tcp_seq startseq = tp->snd_nxt;
1468 
1469 		/*
1470 		 * Advance snd_nxt over sequence space of this segment.
1471 		 */
1472 		if (flags & (TH_SYN|TH_FIN)) {
1473 			if (flags & TH_SYN)
1474 				tp->snd_nxt++;
1475 			if (flags & TH_FIN) {
1476 				tp->snd_nxt++;
1477 				tp->t_flags |= TF_SENTFIN;
1478 			}
1479 		}
1480 		if (sack_rxmit)
1481 			goto timer;
1482 		tp->snd_nxt += len;
1483 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1484 			tp->snd_max = tp->snd_nxt;
1485 			/*
1486 			 * Time this transmission if not a retransmission and
1487 			 * not currently timing anything.
1488 			 */
1489 			if (tp->t_rtttime == 0) {
1490 				tp->t_rtttime = ticks;
1491 				tp->t_rtseq = startseq;
1492 				TCPSTAT_INC(tcps_segstimed);
1493 			}
1494 #ifdef STATS
1495 			if (!(tp->t_flags & TF_GPUTINPROG) && len) {
1496 				tp->t_flags |= TF_GPUTINPROG;
1497 				tp->gput_seq = startseq;
1498 				tp->gput_ack = startseq +
1499 				    ulmin(sbavail(&so->so_snd) - off, sendwin);
1500 				tp->gput_ts = tcp_ts_getticks();
1501 			}
1502 #endif /* STATS */
1503 		}
1504 
1505 		/*
1506 		 * Set retransmit timer if not currently set,
1507 		 * and not doing a pure ack or a keep-alive probe.
1508 		 * Initial value for retransmit timer is smoothed
1509 		 * round-trip time + 2 * round-trip time variance.
1510 		 * Initialize shift counter which is used for backoff
1511 		 * of retransmit time.
1512 		 */
1513 timer:
1514 		if (!tcp_timer_active(tp, TT_REXMT) &&
1515 		    ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
1516 		     (tp->snd_nxt != tp->snd_una))) {
1517 			if (tcp_timer_active(tp, TT_PERSIST)) {
1518 				tcp_timer_activate(tp, TT_PERSIST, 0);
1519 				tp->t_rxtshift = 0;
1520 			}
1521 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1522 		} else if (len == 0 && sbavail(&so->so_snd) &&
1523 		    !tcp_timer_active(tp, TT_REXMT) &&
1524 		    !tcp_timer_active(tp, TT_PERSIST)) {
1525 			/*
1526 			 * Avoid a situation where we do not set persist timer
1527 			 * after a zero window condition. For example:
1528 			 * 1) A -> B: packet with enough data to fill the window
1529 			 * 2) B -> A: ACK for #1 + new data (0 window
1530 			 *    advertisement)
1531 			 * 3) A -> B: ACK for #2, 0 len packet
1532 			 *
1533 			 * In this case, A will not activate the persist timer,
1534 			 * because it chose to send a packet. Unless tcp_output
1535 			 * is called for some other reason (delayed ack timer,
1536 			 * another input packet from B, socket syscall), A will
1537 			 * not send zero window probes.
1538 			 *
1539 			 * So, if you send a 0-length packet, but there is data
1540 			 * in the socket buffer, and neither the rexmt or
1541 			 * persist timer is already set, then activate the
1542 			 * persist timer.
1543 			 */
1544 			tp->t_rxtshift = 0;
1545 			tcp_setpersist(tp);
1546 		}
1547 	} else {
1548 		/*
1549 		 * Persist case, update snd_max but since we are in
1550 		 * persist mode (no window) we do not update snd_nxt.
1551 		 */
1552 		int xlen = len;
1553 		if (flags & TH_SYN)
1554 			++xlen;
1555 		if (flags & TH_FIN) {
1556 			++xlen;
1557 			tp->t_flags |= TF_SENTFIN;
1558 		}
1559 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1560 			tp->snd_max = tp->snd_nxt + xlen;
1561 	}
1562 	if ((error == 0) &&
1563 	    (TCPS_HAVEESTABLISHED(tp->t_state) &&
1564 	     (tp->t_flags & TF_SACK_PERMIT) &&
1565 	     tp->rcv_numsacks > 0)) {
1566 		    /* Clean up any DSACK's sent */
1567 		    tcp_clean_dsack_blocks(tp);
1568 	}
1569 	if (error) {
1570 		/* Record the error. */
1571 		TCP_LOG_EVENT(tp, NULL, &so->so_rcv, &so->so_snd, TCP_LOG_OUT,
1572 		    error, 0, NULL, false);
1573 
1574 		/*
1575 		 * We know that the packet was lost, so back out the
1576 		 * sequence number advance, if any.
1577 		 *
1578 		 * If the error is EPERM the packet got blocked by the
1579 		 * local firewall.  Normally we should terminate the
1580 		 * connection but the blocking may have been spurious
1581 		 * due to a firewall reconfiguration cycle.  So we treat
1582 		 * it like a packet loss and let the retransmit timer and
1583 		 * timeouts do their work over time.
1584 		 * XXX: It is a POLA question whether calling tcp_drop right
1585 		 * away would be the really correct behavior instead.
1586 		 */
1587 		if (((tp->t_flags & TF_FORCEDATA) == 0 ||
1588 		    !tcp_timer_active(tp, TT_PERSIST)) &&
1589 		    ((flags & TH_SYN) == 0) &&
1590 		    (error != EPERM)) {
1591 			if (sack_rxmit) {
1592 				p->rxmit -= len;
1593 				tp->sackhint.sack_bytes_rexmit -= len;
1594 				KASSERT(tp->sackhint.sack_bytes_rexmit >= 0,
1595 				    ("sackhint bytes rtx >= 0"));
1596 			} else
1597 				tp->snd_nxt -= len;
1598 		}
1599 		SOCKBUF_UNLOCK_ASSERT(&so->so_snd);	/* Check gotos. */
1600 		switch (error) {
1601 		case EACCES:
1602 		case EPERM:
1603 			tp->t_softerror = error;
1604 			return (error);
1605 		case ENOBUFS:
1606 			TCP_XMIT_TIMER_ASSERT(tp, len, flags);
1607 			tp->snd_cwnd = tp->t_maxseg;
1608 			return (0);
1609 		case EMSGSIZE:
1610 			/*
1611 			 * For some reason the interface we used initially
1612 			 * to send segments changed to another or lowered
1613 			 * its MTU.
1614 			 * If TSO was active we either got an interface
1615 			 * without TSO capabilits or TSO was turned off.
1616 			 * If we obtained mtu from ip_output() then update
1617 			 * it and try again.
1618 			 */
1619 			if (tso)
1620 				tp->t_flags &= ~TF_TSO;
1621 			if (mtu != 0) {
1622 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
1623 				goto again;
1624 			}
1625 			return (error);
1626 		case EHOSTDOWN:
1627 		case EHOSTUNREACH:
1628 		case ENETDOWN:
1629 		case ENETUNREACH:
1630 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
1631 				tp->t_softerror = error;
1632 				return (0);
1633 			}
1634 			/* FALLTHROUGH */
1635 		default:
1636 			return (error);
1637 		}
1638 	}
1639 	TCPSTAT_INC(tcps_sndtotal);
1640 
1641 	/*
1642 	 * Data sent (as far as we can tell).
1643 	 * If this advertises a larger window than any other segment,
1644 	 * then remember the size of the advertised window.
1645 	 * Any pending ACK has now been sent.
1646 	 */
1647 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
1648 		tp->rcv_adv = tp->rcv_nxt + recwin;
1649 	tp->last_ack_sent = tp->rcv_nxt;
1650 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
1651 	if (tcp_timer_active(tp, TT_DELACK))
1652 		tcp_timer_activate(tp, TT_DELACK, 0);
1653 #if 0
1654 	/*
1655 	 * This completely breaks TCP if newreno is turned on.  What happens
1656 	 * is that if delayed-acks are turned on on the receiver, this code
1657 	 * on the transmitter effectively destroys the TCP window, forcing
1658 	 * it to four packets (1.5Kx4 = 6K window).
1659 	 */
1660 	if (sendalot && --maxburst)
1661 		goto again;
1662 #endif
1663 	if (sendalot)
1664 		goto again;
1665 	return (0);
1666 }
1667 
1668 void
1669 tcp_setpersist(struct tcpcb *tp)
1670 {
1671 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1672 	int tt;
1673 
1674 	tp->t_flags &= ~TF_PREVVALID;
1675 	if (tcp_timer_active(tp, TT_REXMT))
1676 		panic("tcp_setpersist: retransmit pending");
1677 	/*
1678 	 * Start/restart persistence timer.
1679 	 */
1680 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
1681 		      tcp_persmin, tcp_persmax);
1682 	tcp_timer_activate(tp, TT_PERSIST, tt);
1683 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1684 		tp->t_rxtshift++;
1685 }
1686 
1687 /*
1688  * Insert TCP options according to the supplied parameters to the place
1689  * optp in a consistent way.  Can handle unaligned destinations.
1690  *
1691  * The order of the option processing is crucial for optimal packing and
1692  * alignment for the scarce option space.
1693  *
1694  * The optimal order for a SYN/SYN-ACK segment is:
1695  *   MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) +
1696  *   Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40.
1697  *
1698  * The SACK options should be last.  SACK blocks consume 8*n+2 bytes.
1699  * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks).
1700  * At minimum we need 10 bytes (to generate 1 SACK block).  If both
1701  * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present,
1702  * we only have 10 bytes for SACK options (40 - (12 + 18)).
1703  */
1704 int
1705 tcp_addoptions(struct tcpopt *to, u_char *optp)
1706 {
1707 	u_int32_t mask, optlen = 0;
1708 
1709 	for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) {
1710 		if ((to->to_flags & mask) != mask)
1711 			continue;
1712 		if (optlen == TCP_MAXOLEN)
1713 			break;
1714 		switch (to->to_flags & mask) {
1715 		case TOF_MSS:
1716 			while (optlen % 4) {
1717 				optlen += TCPOLEN_NOP;
1718 				*optp++ = TCPOPT_NOP;
1719 			}
1720 			if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG)
1721 				continue;
1722 			optlen += TCPOLEN_MAXSEG;
1723 			*optp++ = TCPOPT_MAXSEG;
1724 			*optp++ = TCPOLEN_MAXSEG;
1725 			to->to_mss = htons(to->to_mss);
1726 			bcopy((u_char *)&to->to_mss, optp, sizeof(to->to_mss));
1727 			optp += sizeof(to->to_mss);
1728 			break;
1729 		case TOF_SCALE:
1730 			while (!optlen || optlen % 2 != 1) {
1731 				optlen += TCPOLEN_NOP;
1732 				*optp++ = TCPOPT_NOP;
1733 			}
1734 			if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW)
1735 				continue;
1736 			optlen += TCPOLEN_WINDOW;
1737 			*optp++ = TCPOPT_WINDOW;
1738 			*optp++ = TCPOLEN_WINDOW;
1739 			*optp++ = to->to_wscale;
1740 			break;
1741 		case TOF_SACKPERM:
1742 			while (optlen % 2) {
1743 				optlen += TCPOLEN_NOP;
1744 				*optp++ = TCPOPT_NOP;
1745 			}
1746 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED)
1747 				continue;
1748 			optlen += TCPOLEN_SACK_PERMITTED;
1749 			*optp++ = TCPOPT_SACK_PERMITTED;
1750 			*optp++ = TCPOLEN_SACK_PERMITTED;
1751 			break;
1752 		case TOF_TS:
1753 			while (!optlen || optlen % 4 != 2) {
1754 				optlen += TCPOLEN_NOP;
1755 				*optp++ = TCPOPT_NOP;
1756 			}
1757 			if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP)
1758 				continue;
1759 			optlen += TCPOLEN_TIMESTAMP;
1760 			*optp++ = TCPOPT_TIMESTAMP;
1761 			*optp++ = TCPOLEN_TIMESTAMP;
1762 			to->to_tsval = htonl(to->to_tsval);
1763 			to->to_tsecr = htonl(to->to_tsecr);
1764 			bcopy((u_char *)&to->to_tsval, optp, sizeof(to->to_tsval));
1765 			optp += sizeof(to->to_tsval);
1766 			bcopy((u_char *)&to->to_tsecr, optp, sizeof(to->to_tsecr));
1767 			optp += sizeof(to->to_tsecr);
1768 			break;
1769 		case TOF_SIGNATURE:
1770 			{
1771 			int siglen = TCPOLEN_SIGNATURE - 2;
1772 
1773 			while (!optlen || optlen % 4 != 2) {
1774 				optlen += TCPOLEN_NOP;
1775 				*optp++ = TCPOPT_NOP;
1776 			}
1777 			if (TCP_MAXOLEN - optlen < TCPOLEN_SIGNATURE) {
1778 				to->to_flags &= ~TOF_SIGNATURE;
1779 				continue;
1780 			}
1781 			optlen += TCPOLEN_SIGNATURE;
1782 			*optp++ = TCPOPT_SIGNATURE;
1783 			*optp++ = TCPOLEN_SIGNATURE;
1784 			to->to_signature = optp;
1785 			while (siglen--)
1786 				 *optp++ = 0;
1787 			break;
1788 			}
1789 		case TOF_SACK:
1790 			{
1791 			int sackblks = 0;
1792 			struct sackblk *sack = (struct sackblk *)to->to_sacks;
1793 			tcp_seq sack_seq;
1794 
1795 			while (!optlen || optlen % 4 != 2) {
1796 				optlen += TCPOLEN_NOP;
1797 				*optp++ = TCPOPT_NOP;
1798 			}
1799 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK)
1800 				continue;
1801 			optlen += TCPOLEN_SACKHDR;
1802 			*optp++ = TCPOPT_SACK;
1803 			sackblks = min(to->to_nsacks,
1804 					(TCP_MAXOLEN - optlen) / TCPOLEN_SACK);
1805 			*optp++ = TCPOLEN_SACKHDR + sackblks * TCPOLEN_SACK;
1806 			while (sackblks--) {
1807 				sack_seq = htonl(sack->start);
1808 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
1809 				optp += sizeof(sack_seq);
1810 				sack_seq = htonl(sack->end);
1811 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
1812 				optp += sizeof(sack_seq);
1813 				optlen += TCPOLEN_SACK;
1814 				sack++;
1815 			}
1816 			TCPSTAT_INC(tcps_sack_send_blocks);
1817 			break;
1818 			}
1819 		case TOF_FASTOPEN:
1820 			{
1821 			int total_len;
1822 
1823 			/* XXX is there any point to aligning this option? */
1824 			total_len = TCPOLEN_FAST_OPEN_EMPTY + to->to_tfo_len;
1825 			if (TCP_MAXOLEN - optlen < total_len) {
1826 				to->to_flags &= ~TOF_FASTOPEN;
1827 				continue;
1828 			}
1829 			*optp++ = TCPOPT_FAST_OPEN;
1830 			*optp++ = total_len;
1831 			if (to->to_tfo_len > 0) {
1832 				bcopy(to->to_tfo_cookie, optp, to->to_tfo_len);
1833 				optp += to->to_tfo_len;
1834 			}
1835 			optlen += total_len;
1836 			break;
1837 			}
1838 		default:
1839 			panic("%s: unknown TCP option type", __func__);
1840 			break;
1841 		}
1842 	}
1843 
1844 	/* Terminate and pad TCP options to a 4 byte boundary. */
1845 	if (optlen % 4) {
1846 		optlen += TCPOLEN_EOL;
1847 		*optp++ = TCPOPT_EOL;
1848 	}
1849 	/*
1850 	 * According to RFC 793 (STD0007):
1851 	 *   "The content of the header beyond the End-of-Option option
1852 	 *    must be header padding (i.e., zero)."
1853 	 *   and later: "The padding is composed of zeros."
1854 	 */
1855 	while (optlen % 4) {
1856 		optlen += TCPOLEN_PAD;
1857 		*optp++ = TCPOPT_PAD;
1858 	}
1859 
1860 	KASSERT(optlen <= TCP_MAXOLEN, ("%s: TCP options too long", __func__));
1861 	return (optlen);
1862 }
1863 
1864 /*
1865  * This is a copy of m_copym(), taking the TSO segment size/limit
1866  * constraints into account, and advancing the sndptr as it goes.
1867  */
1868 struct mbuf *
1869 tcp_m_copym(struct mbuf *m, int32_t off0, int32_t *plen,
1870     int32_t seglimit, int32_t segsize, struct sockbuf *sb, bool hw_tls)
1871 {
1872 #ifdef KERN_TLS
1873 	struct ktls_session *tls, *ntls;
1874 	struct mbuf *start;
1875 #endif
1876 	struct mbuf *n, **np;
1877 	struct mbuf *top;
1878 	int32_t off = off0;
1879 	int32_t len = *plen;
1880 	int32_t fragsize;
1881 	int32_t len_cp = 0;
1882 	int32_t *pkthdrlen;
1883 	uint32_t mlen, frags;
1884 	bool copyhdr;
1885 
1886 
1887 	KASSERT(off >= 0, ("tcp_m_copym, negative off %d", off));
1888 	KASSERT(len >= 0, ("tcp_m_copym, negative len %d", len));
1889 	if (off == 0 && m->m_flags & M_PKTHDR)
1890 		copyhdr = true;
1891 	else
1892 		copyhdr = false;
1893 	while (off > 0) {
1894 		KASSERT(m != NULL, ("tcp_m_copym, offset > size of mbuf chain"));
1895 		if (off < m->m_len)
1896 			break;
1897 		off -= m->m_len;
1898 		if ((sb) && (m == sb->sb_sndptr)) {
1899 			sb->sb_sndptroff += m->m_len;
1900 			sb->sb_sndptr = m->m_next;
1901 		}
1902 		m = m->m_next;
1903 	}
1904 	np = &top;
1905 	top = NULL;
1906 	pkthdrlen = NULL;
1907 #ifdef KERN_TLS
1908 	if (m->m_flags & M_NOMAP)
1909 		tls = m->m_ext.ext_pgs->tls;
1910 	else
1911 		tls = NULL;
1912 	start = m;
1913 #endif
1914 	while (len > 0) {
1915 		if (m == NULL) {
1916 			KASSERT(len == M_COPYALL,
1917 			    ("tcp_m_copym, length > size of mbuf chain"));
1918 			*plen = len_cp;
1919 			if (pkthdrlen != NULL)
1920 				*pkthdrlen = len_cp;
1921 			break;
1922 		}
1923 #ifdef KERN_TLS
1924 		if (hw_tls) {
1925 			if (m->m_flags & M_NOMAP)
1926 				ntls = m->m_ext.ext_pgs->tls;
1927 			else
1928 				ntls = NULL;
1929 
1930 			/*
1931 			 * Avoid mixing TLS records with handshake
1932 			 * data or TLS records from different
1933 			 * sessions.
1934 			 */
1935 			if (tls != ntls) {
1936 				MPASS(m != start);
1937 				*plen = len_cp;
1938 				if (pkthdrlen != NULL)
1939 					*pkthdrlen = len_cp;
1940 				break;
1941 			}
1942 
1943 			/*
1944 			 * Don't end a send in the middle of a TLS
1945 			 * record if it spans multiple TLS records.
1946 			 */
1947 			if (tls != NULL && (m != start) && len < m->m_len) {
1948 				*plen = len_cp;
1949 				if (pkthdrlen != NULL)
1950 					*pkthdrlen = len_cp;
1951 				break;
1952 			}
1953 		}
1954 #endif
1955 		mlen = min(len, m->m_len - off);
1956 		if (seglimit) {
1957 			/*
1958 			 * For M_NOMAP mbufs, add 3 segments
1959 			 * + 1 in case we are crossing page boundaries
1960 			 * + 2 in case the TLS hdr/trailer are used
1961 			 * It is cheaper to just add the segments
1962 			 * than it is to take the cache miss to look
1963 			 * at the mbuf ext_pgs state in detail.
1964 			 */
1965 			if (m->m_flags & M_NOMAP) {
1966 				fragsize = min(segsize, PAGE_SIZE);
1967 				frags = 3;
1968 			} else {
1969 				fragsize = segsize;
1970 				frags = 0;
1971 			}
1972 
1973 			/* Break if we really can't fit anymore. */
1974 			if ((frags + 1) >= seglimit) {
1975 				*plen =	len_cp;
1976 				if (pkthdrlen != NULL)
1977 					*pkthdrlen = len_cp;
1978 				break;
1979 			}
1980 
1981 			/*
1982 			 * Reduce size if you can't copy the whole
1983 			 * mbuf. If we can't copy the whole mbuf, also
1984 			 * adjust len so the loop will end after this
1985 			 * mbuf.
1986 			 */
1987 			if ((frags + howmany(mlen, fragsize)) >= seglimit) {
1988 				mlen = (seglimit - frags - 1) * fragsize;
1989 				len = mlen;
1990 				*plen = len_cp + len;
1991 				if (pkthdrlen != NULL)
1992 					*pkthdrlen = *plen;
1993 			}
1994 			frags += howmany(mlen, fragsize);
1995 			if (frags == 0)
1996 				frags++;
1997 			seglimit -= frags;
1998 			KASSERT(seglimit > 0,
1999 			    ("%s: seglimit went too low", __func__));
2000 		}
2001 		if (copyhdr)
2002 			n = m_gethdr(M_NOWAIT, m->m_type);
2003 		else
2004 			n = m_get(M_NOWAIT, m->m_type);
2005 		*np = n;
2006 		if (n == NULL)
2007 			goto nospace;
2008 		if (copyhdr) {
2009 			if (!m_dup_pkthdr(n, m, M_NOWAIT))
2010 				goto nospace;
2011 			if (len == M_COPYALL)
2012 				n->m_pkthdr.len -= off0;
2013 			else
2014 				n->m_pkthdr.len = len;
2015 			pkthdrlen = &n->m_pkthdr.len;
2016 			copyhdr = false;
2017 		}
2018 		n->m_len = mlen;
2019 		len_cp += n->m_len;
2020 		if (m->m_flags & M_EXT) {
2021 			n->m_data = m->m_data + off;
2022 			mb_dupcl(n, m);
2023 		} else
2024 			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
2025 			    (u_int)n->m_len);
2026 
2027 		if (sb && (sb->sb_sndptr == m) &&
2028 		    ((n->m_len + off) >= m->m_len) && m->m_next) {
2029 			sb->sb_sndptroff += m->m_len;
2030 			sb->sb_sndptr = m->m_next;
2031 		}
2032 		off = 0;
2033 		if (len != M_COPYALL) {
2034 			len -= n->m_len;
2035 		}
2036 		m = m->m_next;
2037 		np = &n->m_next;
2038 	}
2039 	return (top);
2040 nospace:
2041 	m_freem(top);
2042 	return (NULL);
2043 }
2044 
2045 void
2046 tcp_sndbuf_autoscale(struct tcpcb *tp, struct socket *so, uint32_t sendwin)
2047 {
2048 
2049 	/*
2050 	 * Automatic sizing of send socket buffer.  Often the send buffer
2051 	 * size is not optimally adjusted to the actual network conditions
2052 	 * at hand (delay bandwidth product).  Setting the buffer size too
2053 	 * small limits throughput on links with high bandwidth and high
2054 	 * delay (eg. trans-continental/oceanic links).  Setting the
2055 	 * buffer size too big consumes too much real kernel memory,
2056 	 * especially with many connections on busy servers.
2057 	 *
2058 	 * The criteria to step up the send buffer one notch are:
2059 	 *  1. receive window of remote host is larger than send buffer
2060 	 *     (with a fudge factor of 5/4th);
2061 	 *  2. send buffer is filled to 7/8th with data (so we actually
2062 	 *     have data to make use of it);
2063 	 *  3. send buffer fill has not hit maximal automatic size;
2064 	 *  4. our send window (slow start and cogestion controlled) is
2065 	 *     larger than sent but unacknowledged data in send buffer.
2066 	 *
2067 	 * The remote host receive window scaling factor may limit the
2068 	 * growing of the send buffer before it reaches its allowed
2069 	 * maximum.
2070 	 *
2071 	 * It scales directly with slow start or congestion window
2072 	 * and does at most one step per received ACK.  This fast
2073 	 * scaling has the drawback of growing the send buffer beyond
2074 	 * what is strictly necessary to make full use of a given
2075 	 * delay*bandwidth product.  However testing has shown this not
2076 	 * to be much of an problem.  At worst we are trading wasting
2077 	 * of available bandwidth (the non-use of it) for wasting some
2078 	 * socket buffer memory.
2079 	 *
2080 	 * TODO: Shrink send buffer during idle periods together
2081 	 * with congestion window.  Requires another timer.  Has to
2082 	 * wait for upcoming tcp timer rewrite.
2083 	 *
2084 	 * XXXGL: should there be used sbused() or sbavail()?
2085 	 */
2086 	if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
2087 		int lowat;
2088 
2089 		lowat = V_tcp_sendbuf_auto_lowat ? so->so_snd.sb_lowat : 0;
2090 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat - lowat &&
2091 		    sbused(&so->so_snd) >=
2092 		    (so->so_snd.sb_hiwat / 8 * 7) - lowat &&
2093 		    sbused(&so->so_snd) < V_tcp_autosndbuf_max &&
2094 		    sendwin >= (sbused(&so->so_snd) -
2095 		    (tp->snd_nxt - tp->snd_una))) {
2096 			if (!sbreserve_locked(&so->so_snd,
2097 			    min(so->so_snd.sb_hiwat + V_tcp_autosndbuf_inc,
2098 			     V_tcp_autosndbuf_max), so, curthread))
2099 				so->so_snd.sb_flags &= ~SB_AUTOSIZE;
2100 		}
2101 	}
2102 }
2103