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