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