xref: /freebsd/sys/netinet/tcp_output.c (revision 273c26a3c3bea87a241d6879abd4f991db180bf0)
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 			    long 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, long 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 	long len, recwin, sendwin;
189 	int off, flags, error = 0;	/* Keep compiler happy */
190 	struct mbuf *m;
191 	struct ip *ip = NULL;
192 	struct ipovly *ipov = NULL;
193 	struct tcphdr *th;
194 	u_char opt[TCP_MAXOLEN];
195 	unsigned ipoptlen, optlen, hdrlen;
196 #ifdef IPSEC
197 	unsigned ipsec_optlen = 0;
198 #endif
199 	int idle, sendalot;
200 	int sack_rxmit, sack_bytes_rxmt;
201 	struct sackhole *p;
202 	int tso, mtu;
203 	struct tcpopt to;
204 #if 0
205 	int maxburst = TCP_MAXBURST;
206 #endif
207 #ifdef INET6
208 	struct ip6_hdr *ip6 = NULL;
209 	int isipv6;
210 
211 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
212 #endif
213 
214 	INP_WLOCK_ASSERT(tp->t_inpcb);
215 
216 #ifdef TCP_OFFLOAD
217 	if (tp->t_flags & TF_TOE)
218 		return (tcp_offload_output(tp));
219 #endif
220 
221 #ifdef TCP_RFC7413
222 	/*
223 	 * For TFO connections in SYN_RECEIVED, only allow the initial
224 	 * SYN|ACK and those sent by the retransmit timer.
225 	 */
226 	if ((tp->t_flags & TF_FASTOPEN) &&
227 	    (tp->t_state == TCPS_SYN_RECEIVED) &&
228 	    SEQ_GT(tp->snd_max, tp->snd_una) &&    /* initial SYN|ACK sent */
229 	    (tp->snd_nxt != tp->snd_una))          /* not a retransmit */
230 		return (0);
231 #endif
232 	/*
233 	 * Determine length of data that should be transmitted,
234 	 * and flags that will be used.
235 	 * If there is some data or critical controls (SYN, RST)
236 	 * to send, then transmit; otherwise, investigate further.
237 	 */
238 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
239 	if (idle && ticks - tp->t_rcvtime >= tp->t_rxtcur)
240 		cc_after_idle(tp);
241 	tp->t_flags &= ~TF_LASTIDLE;
242 	if (idle) {
243 		if (tp->t_flags & TF_MORETOCOME) {
244 			tp->t_flags |= TF_LASTIDLE;
245 			idle = 0;
246 		}
247 	}
248 again:
249 	/*
250 	 * If we've recently taken a timeout, snd_max will be greater than
251 	 * snd_nxt.  There may be SACK information that allows us to avoid
252 	 * resending already delivered data.  Adjust snd_nxt accordingly.
253 	 */
254 	if ((tp->t_flags & TF_SACK_PERMIT) &&
255 	    SEQ_LT(tp->snd_nxt, tp->snd_max))
256 		tcp_sack_adjust(tp);
257 	sendalot = 0;
258 	tso = 0;
259 	mtu = 0;
260 	off = tp->snd_nxt - tp->snd_una;
261 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
262 
263 	flags = tcp_outflags[tp->t_state];
264 	/*
265 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
266 	 * to send out new data (when sendalot is 1), bypass this function.
267 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
268 	 * we're replacing a (future) new transmission with a retransmission
269 	 * now, and we previously incremented snd_cwnd in tcp_input().
270 	 */
271 	/*
272 	 * Still in sack recovery , reset rxmit flag to zero.
273 	 */
274 	sack_rxmit = 0;
275 	sack_bytes_rxmt = 0;
276 	len = 0;
277 	p = NULL;
278 	if ((tp->t_flags & TF_SACK_PERMIT) && IN_FASTRECOVERY(tp->t_flags) &&
279 	    (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
280 		long cwin;
281 
282 		cwin = min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
283 		if (cwin < 0)
284 			cwin = 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 = ((long)ulmin(cwin,
304 						   tp->snd_recover - p->rxmit));
305 		} else
306 			len = ((long)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 = ((long)ulmin(sbavail(&so->so_snd), sendwin) -
380 			    off);
381 		else {
382 			long 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 = ((long)ulmin(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 = lmin(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 = sbspace(&so->so_rcv);
570 
571 	/*
572 	 * Sender silly window avoidance.   We transmit under the following
573 	 * conditions when len is non-zero:
574 	 *
575 	 *	- We have a full segment (or more with TSO)
576 	 *	- This is the last buffer in a write()/send() and we are
577 	 *	  either idle or running NODELAY
578 	 *	- we've timed out (e.g. persist timer)
579 	 *	- we have more then 1/2 the maximum send window's worth of
580 	 *	  data (receiver may be limited the window size)
581 	 *	- we need to retransmit
582 	 */
583 	if (len) {
584 		if (len >= tp->t_maxseg)
585 			goto send;
586 		/*
587 		 * NOTE! on localhost connections an 'ack' from the remote
588 		 * end may occur synchronously with the output and cause
589 		 * us to flush a buffer queued with moretocome.  XXX
590 		 *
591 		 * note: the len + off check is almost certainly unnecessary.
592 		 */
593 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
594 		    (idle || (tp->t_flags & TF_NODELAY)) &&
595 		    len + off >= sbavail(&so->so_snd) &&
596 		    (tp->t_flags & TF_NOPUSH) == 0) {
597 			goto send;
598 		}
599 		if (tp->t_flags & TF_FORCEDATA)		/* typ. timeout case */
600 			goto send;
601 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
602 			goto send;
603 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
604 			goto send;
605 		if (sack_rxmit)
606 			goto send;
607 	}
608 
609 	/*
610 	 * Sending of standalone window updates.
611 	 *
612 	 * Window updates are important when we close our window due to a
613 	 * full socket buffer and are opening it again after the application
614 	 * reads data from it.  Once the window has opened again and the
615 	 * remote end starts to send again the ACK clock takes over and
616 	 * provides the most current window information.
617 	 *
618 	 * We must avoid the silly window syndrome whereas every read
619 	 * from the receive buffer, no matter how small, causes a window
620 	 * update to be sent.  We also should avoid sending a flurry of
621 	 * window updates when the socket buffer had queued a lot of data
622 	 * and the application is doing small reads.
623 	 *
624 	 * Prevent a flurry of pointless window updates by only sending
625 	 * an update when we can increase the advertized window by more
626 	 * than 1/4th of the socket buffer capacity.  When the buffer is
627 	 * getting full or is very small be more aggressive and send an
628 	 * update whenever we can increase by two mss sized segments.
629 	 * In all other situations the ACK's to new incoming data will
630 	 * carry further window increases.
631 	 *
632 	 * Don't send an independent window update if a delayed
633 	 * ACK is pending (it will get piggy-backed on it) or the
634 	 * remote side already has done a half-close and won't send
635 	 * more data.  Skip this if the connection is in T/TCP
636 	 * half-open state.
637 	 */
638 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
639 	    !(tp->t_flags & TF_DELACK) &&
640 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
641 		/*
642 		 * "adv" is the amount we could increase the window,
643 		 * taking into account that we are limited by
644 		 * TCP_MAXWIN << tp->rcv_scale.
645 		 */
646 		long adv;
647 		int oldwin;
648 
649 		adv = min(recwin, (long)TCP_MAXWIN << tp->rcv_scale);
650 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
651 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
652 			adv -= oldwin;
653 		} else
654 			oldwin = 0;
655 
656 		/*
657 		 * If the new window size ends up being the same as the old
658 		 * size when it is scaled, then don't force a window update.
659 		 */
660 		if (oldwin >> tp->rcv_scale == (adv + oldwin) >> tp->rcv_scale)
661 			goto dontupdate;
662 
663 		if (adv >= (long)(2 * tp->t_maxseg) &&
664 		    (adv >= (long)(so->so_rcv.sb_hiwat / 4) ||
665 		     recwin <= (long)(so->so_rcv.sb_hiwat / 8) ||
666 		     so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg))
667 			goto send;
668 	}
669 dontupdate:
670 
671 	/*
672 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
673 	 * is also a catch-all for the retransmit timer timeout case.
674 	 */
675 	if (tp->t_flags & TF_ACKNOW)
676 		goto send;
677 	if ((flags & TH_RST) ||
678 	    ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
679 		goto send;
680 	if (SEQ_GT(tp->snd_up, tp->snd_una))
681 		goto send;
682 	/*
683 	 * If our state indicates that FIN should be sent
684 	 * and we have not yet done so, then we need to send.
685 	 */
686 	if (flags & TH_FIN &&
687 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
688 		goto send;
689 	/*
690 	 * In SACK, it is possible for tcp_output to fail to send a segment
691 	 * after the retransmission timer has been turned off.  Make sure
692 	 * that the retransmission timer is set.
693 	 */
694 	if ((tp->t_flags & TF_SACK_PERMIT) &&
695 	    SEQ_GT(tp->snd_max, tp->snd_una) &&
696 	    !tcp_timer_active(tp, TT_REXMT) &&
697 	    !tcp_timer_active(tp, TT_PERSIST)) {
698 		tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
699 		goto just_return;
700 	}
701 	/*
702 	 * TCP window updates are not reliable, rather a polling protocol
703 	 * using ``persist'' packets is used to insure receipt of window
704 	 * updates.  The three ``states'' for the output side are:
705 	 *	idle			not doing retransmits or persists
706 	 *	persisting		to move a small or zero window
707 	 *	(re)transmitting	and thereby not persisting
708 	 *
709 	 * tcp_timer_active(tp, TT_PERSIST)
710 	 *	is true when we are in persist state.
711 	 * (tp->t_flags & TF_FORCEDATA)
712 	 *	is set when we are called to send a persist packet.
713 	 * tcp_timer_active(tp, TT_REXMT)
714 	 *	is set when we are retransmitting
715 	 * The output side is idle when both timers are zero.
716 	 *
717 	 * If send window is too small, there is data to transmit, and no
718 	 * retransmit or persist is pending, then go to persist state.
719 	 * If nothing happens soon, send when timer expires:
720 	 * if window is nonzero, transmit what we can,
721 	 * otherwise force out a byte.
722 	 */
723 	if (sbavail(&so->so_snd) && !tcp_timer_active(tp, TT_REXMT) &&
724 	    !tcp_timer_active(tp, TT_PERSIST)) {
725 		tp->t_rxtshift = 0;
726 		tcp_setpersist(tp);
727 	}
728 
729 	/*
730 	 * No reason to send a segment, just return.
731 	 */
732 just_return:
733 	SOCKBUF_UNLOCK(&so->so_snd);
734 	return (0);
735 
736 send:
737 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
738 	if (len > 0) {
739 		if (len >= tp->t_maxseg)
740 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
741 		else
742 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
743 	}
744 	/*
745 	 * Before ESTABLISHED, force sending of initial options
746 	 * unless TCP set not to do any options.
747 	 * NOTE: we assume that the IP/TCP header plus TCP options
748 	 * always fit in a single mbuf, leaving room for a maximum
749 	 * link header, i.e.
750 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
751 	 */
752 	optlen = 0;
753 #ifdef INET6
754 	if (isipv6)
755 		hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
756 	else
757 #endif
758 		hdrlen = sizeof (struct tcpiphdr);
759 
760 	/*
761 	 * Compute options for segment.
762 	 * We only have to care about SYN and established connection
763 	 * segments.  Options for SYN-ACK segments are handled in TCP
764 	 * syncache.
765 	 */
766 	to.to_flags = 0;
767 	if ((tp->t_flags & TF_NOOPT) == 0) {
768 		/* Maximum segment size. */
769 		if (flags & TH_SYN) {
770 			tp->snd_nxt = tp->iss;
771 			to.to_mss = tcp_mssopt(&tp->t_inpcb->inp_inc);
772 			to.to_flags |= TOF_MSS;
773 #ifdef TCP_RFC7413
774 			/*
775 			 * Only include the TFO option on the first
776 			 * transmission of the SYN|ACK on a
777 			 * passively-created TFO socket, as the presence of
778 			 * the TFO option may have caused the original
779 			 * SYN|ACK to have been dropped by a middlebox.
780 			 */
781 			if ((tp->t_flags & TF_FASTOPEN) &&
782 			    (tp->t_state == TCPS_SYN_RECEIVED) &&
783 			    (tp->t_rxtshift == 0)) {
784 				to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
785 				to.to_tfo_cookie = (u_char *)&tp->t_tfo_cookie;
786 				to.to_flags |= TOF_FASTOPEN;
787 			}
788 #endif
789 		}
790 		/* Window scaling. */
791 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
792 			to.to_wscale = tp->request_r_scale;
793 			to.to_flags |= TOF_SCALE;
794 		}
795 		/* Timestamps. */
796 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
797 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
798 			to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
799 			to.to_tsecr = tp->ts_recent;
800 			to.to_flags |= TOF_TS;
801 			/* Set receive buffer autosizing timestamp. */
802 			if (tp->rfbuf_ts == 0 &&
803 			    (so->so_rcv.sb_flags & SB_AUTOSIZE))
804 				tp->rfbuf_ts = tcp_ts_getticks();
805 		}
806 		/* Selective ACK's. */
807 		if (tp->t_flags & TF_SACK_PERMIT) {
808 			if (flags & TH_SYN)
809 				to.to_flags |= TOF_SACKPERM;
810 			else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
811 			    (tp->t_flags & TF_SACK_PERMIT) &&
812 			    tp->rcv_numsacks > 0) {
813 				to.to_flags |= TOF_SACK;
814 				to.to_nsacks = tp->rcv_numsacks;
815 				to.to_sacks = (u_char *)tp->sackblks;
816 			}
817 		}
818 #ifdef TCP_SIGNATURE
819 		/* TCP-MD5 (RFC2385). */
820 		if (tp->t_flags & TF_SIGNATURE)
821 			to.to_flags |= TOF_SIGNATURE;
822 #endif /* TCP_SIGNATURE */
823 
824 		/* Processing the options. */
825 		hdrlen += optlen = tcp_addoptions(&to, opt);
826 	}
827 
828 #ifdef INET6
829 	if (isipv6)
830 		ipoptlen = ip6_optlen(tp->t_inpcb);
831 	else
832 #endif
833 	if (tp->t_inpcb->inp_options)
834 		ipoptlen = tp->t_inpcb->inp_options->m_len -
835 				offsetof(struct ipoption, ipopt_list);
836 	else
837 		ipoptlen = 0;
838 #ifdef IPSEC
839 	ipoptlen += ipsec_optlen;
840 #endif
841 
842 	/*
843 	 * Adjust data length if insertion of options will
844 	 * bump the packet length beyond the t_maxseg length.
845 	 * Clear the FIN bit because we cut off the tail of
846 	 * the segment.
847 	 */
848 	if (len + optlen + ipoptlen > tp->t_maxseg) {
849 		flags &= ~TH_FIN;
850 
851 		if (tso) {
852 			u_int if_hw_tsomax;
853 			u_int if_hw_tsomaxsegcount;
854 			u_int if_hw_tsomaxsegsize;
855 			struct mbuf *mb;
856 			u_int moff;
857 			int max_len;
858 
859 			/* extract TSO information */
860 			if_hw_tsomax = tp->t_tsomax;
861 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
862 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
863 
864 			/*
865 			 * Limit a TSO burst to prevent it from
866 			 * overflowing or exceeding the maximum length
867 			 * allowed by the network interface:
868 			 */
869 			KASSERT(ipoptlen == 0,
870 			    ("%s: TSO can't do IP options", __func__));
871 
872 			/*
873 			 * Check if we should limit by maximum payload
874 			 * length:
875 			 */
876 			if (if_hw_tsomax != 0) {
877 				/* compute maximum TSO length */
878 				max_len = (if_hw_tsomax - hdrlen -
879 				    max_linkhdr);
880 				if (max_len <= 0) {
881 					len = 0;
882 				} else if (len > max_len) {
883 					sendalot = 1;
884 					len = max_len;
885 				}
886 			}
887 
888 			/*
889 			 * Check if we should limit by maximum segment
890 			 * size and count:
891 			 */
892 			if (if_hw_tsomaxsegcount != 0 &&
893 			    if_hw_tsomaxsegsize != 0) {
894 				/*
895 				 * Subtract one segment for the LINK
896 				 * and TCP/IP headers mbuf that will
897 				 * be prepended to this mbuf chain
898 				 * after the code in this section
899 				 * limits the number of mbufs in the
900 				 * chain to if_hw_tsomaxsegcount.
901 				 */
902 				if_hw_tsomaxsegcount -= 1;
903 				max_len = 0;
904 				mb = sbsndmbuf(&so->so_snd, off, &moff);
905 
906 				while (mb != NULL && max_len < len) {
907 					u_int mlen;
908 					u_int frags;
909 
910 					/*
911 					 * Get length of mbuf fragment
912 					 * and how many hardware frags,
913 					 * rounded up, it would use:
914 					 */
915 					mlen = (mb->m_len - moff);
916 					frags = howmany(mlen,
917 					    if_hw_tsomaxsegsize);
918 
919 					/* Handle special case: Zero Length Mbuf */
920 					if (frags == 0)
921 						frags = 1;
922 
923 					/*
924 					 * Check if the fragment limit
925 					 * will be reached or exceeded:
926 					 */
927 					if (frags >= if_hw_tsomaxsegcount) {
928 						max_len += min(mlen,
929 						    if_hw_tsomaxsegcount *
930 						    if_hw_tsomaxsegsize);
931 						break;
932 					}
933 					max_len += mlen;
934 					if_hw_tsomaxsegcount -= frags;
935 					moff = 0;
936 					mb = mb->m_next;
937 				}
938 				if (max_len <= 0) {
939 					len = 0;
940 				} else if (len > max_len) {
941 					sendalot = 1;
942 					len = max_len;
943 				}
944 			}
945 
946 			/*
947 			 * Prevent the last segment from being
948 			 * fractional unless the send sockbuf can be
949 			 * emptied:
950 			 */
951 			max_len = (tp->t_maxseg - optlen);
952 			if ((off + len) < sbavail(&so->so_snd)) {
953 				moff = len % max_len;
954 				if (moff != 0) {
955 					len -= moff;
956 					sendalot = 1;
957 				}
958 			}
959 
960 			/*
961 			 * In case there are too many small fragments
962 			 * don't use TSO:
963 			 */
964 			if (len <= max_len) {
965 				len = max_len;
966 				sendalot = 1;
967 				tso = 0;
968 			}
969 
970 			/*
971 			 * Send the FIN in a separate segment
972 			 * after the bulk sending is done.
973 			 * We don't trust the TSO implementations
974 			 * to clear the FIN flag on all but the
975 			 * last segment.
976 			 */
977 			if (tp->t_flags & TF_NEEDFIN)
978 				sendalot = 1;
979 
980 		} else {
981 			len = tp->t_maxseg - optlen - ipoptlen;
982 			sendalot = 1;
983 		}
984 	} else
985 		tso = 0;
986 
987 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
988 	    ("%s: len > IP_MAXPACKET", __func__));
989 
990 /*#ifdef DIAGNOSTIC*/
991 #ifdef INET6
992 	if (max_linkhdr + hdrlen > MCLBYTES)
993 #else
994 	if (max_linkhdr + hdrlen > MHLEN)
995 #endif
996 		panic("tcphdr too big");
997 /*#endif*/
998 
999 	/*
1000 	 * This KASSERT is here to catch edge cases at a well defined place.
1001 	 * Before, those had triggered (random) panic conditions further down.
1002 	 */
1003 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
1004 
1005 	/*
1006 	 * Grab a header mbuf, attaching a copy of data to
1007 	 * be transmitted, and initialize the header from
1008 	 * the template for sends on this connection.
1009 	 */
1010 	if (len) {
1011 		struct mbuf *mb;
1012 		u_int moff;
1013 
1014 		if ((tp->t_flags & TF_FORCEDATA) && len == 1)
1015 			TCPSTAT_INC(tcps_sndprobe);
1016 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
1017 			tp->t_sndrexmitpack++;
1018 			TCPSTAT_INC(tcps_sndrexmitpack);
1019 			TCPSTAT_ADD(tcps_sndrexmitbyte, len);
1020 		} else {
1021 			TCPSTAT_INC(tcps_sndpack);
1022 			TCPSTAT_ADD(tcps_sndbyte, len);
1023 		}
1024 #ifdef INET6
1025 		if (MHLEN < hdrlen + max_linkhdr)
1026 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1027 		else
1028 #endif
1029 			m = m_gethdr(M_NOWAIT, MT_DATA);
1030 
1031 		if (m == NULL) {
1032 			SOCKBUF_UNLOCK(&so->so_snd);
1033 			error = ENOBUFS;
1034 			sack_rxmit = 0;
1035 			goto out;
1036 		}
1037 
1038 		m->m_data += max_linkhdr;
1039 		m->m_len = hdrlen;
1040 
1041 		/*
1042 		 * Start the m_copy functions from the closest mbuf
1043 		 * to the offset in the socket buffer chain.
1044 		 */
1045 		mb = sbsndptr(&so->so_snd, off, len, &moff);
1046 
1047 		if (len <= MHLEN - hdrlen - max_linkhdr) {
1048 			m_copydata(mb, moff, (int)len,
1049 			    mtod(m, caddr_t) + hdrlen);
1050 			m->m_len += len;
1051 		} else {
1052 			m->m_next = m_copym(mb, moff, len, M_NOWAIT);
1053 			if (m->m_next == NULL) {
1054 				SOCKBUF_UNLOCK(&so->so_snd);
1055 				(void) m_free(m);
1056 				error = ENOBUFS;
1057 				sack_rxmit = 0;
1058 				goto out;
1059 			}
1060 		}
1061 
1062 		/*
1063 		 * If we're sending everything we've got, set PUSH.
1064 		 * (This will keep happy those implementations which only
1065 		 * give data to the user when a buffer fills or
1066 		 * a PUSH comes in.)
1067 		 */
1068 		if ((off + len == sbused(&so->so_snd)) && !(flags & TH_SYN))
1069 			flags |= TH_PUSH;
1070 		SOCKBUF_UNLOCK(&so->so_snd);
1071 	} else {
1072 		SOCKBUF_UNLOCK(&so->so_snd);
1073 		if (tp->t_flags & TF_ACKNOW)
1074 			TCPSTAT_INC(tcps_sndacks);
1075 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
1076 			TCPSTAT_INC(tcps_sndctrl);
1077 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
1078 			TCPSTAT_INC(tcps_sndurg);
1079 		else
1080 			TCPSTAT_INC(tcps_sndwinup);
1081 
1082 		m = m_gethdr(M_NOWAIT, MT_DATA);
1083 		if (m == NULL) {
1084 			error = ENOBUFS;
1085 			sack_rxmit = 0;
1086 			goto out;
1087 		}
1088 #ifdef INET6
1089 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
1090 		    MHLEN >= hdrlen) {
1091 			M_ALIGN(m, hdrlen);
1092 		} else
1093 #endif
1094 		m->m_data += max_linkhdr;
1095 		m->m_len = hdrlen;
1096 	}
1097 	SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
1098 	m->m_pkthdr.rcvif = (struct ifnet *)0;
1099 #ifdef MAC
1100 	mac_inpcb_create_mbuf(tp->t_inpcb, m);
1101 #endif
1102 #ifdef INET6
1103 	if (isipv6) {
1104 		ip6 = mtod(m, struct ip6_hdr *);
1105 		th = (struct tcphdr *)(ip6 + 1);
1106 		tcpip_fillheaders(tp->t_inpcb, ip6, th);
1107 	} else
1108 #endif /* INET6 */
1109 	{
1110 		ip = mtod(m, struct ip *);
1111 		ipov = (struct ipovly *)ip;
1112 		th = (struct tcphdr *)(ip + 1);
1113 		tcpip_fillheaders(tp->t_inpcb, ip, th);
1114 	}
1115 
1116 	/*
1117 	 * Fill in fields, remembering maximum advertised
1118 	 * window for use in delaying messages about window sizes.
1119 	 * If resending a FIN, be sure not to use a new sequence number.
1120 	 */
1121 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
1122 	    tp->snd_nxt == tp->snd_max)
1123 		tp->snd_nxt--;
1124 	/*
1125 	 * If we are starting a connection, send ECN setup
1126 	 * SYN packet. If we are on a retransmit, we may
1127 	 * resend those bits a number of times as per
1128 	 * RFC 3168.
1129 	 */
1130 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
1131 		if (tp->t_rxtshift >= 1) {
1132 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
1133 				flags |= TH_ECE|TH_CWR;
1134 		} else
1135 			flags |= TH_ECE|TH_CWR;
1136 	}
1137 
1138 	if (tp->t_state == TCPS_ESTABLISHED &&
1139 	    (tp->t_flags & TF_ECN_PERMIT)) {
1140 		/*
1141 		 * If the peer has ECN, mark data packets with
1142 		 * ECN capable transmission (ECT).
1143 		 * Ignore pure ack packets, retransmissions and window probes.
1144 		 */
1145 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
1146 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
1147 #ifdef INET6
1148 			if (isipv6)
1149 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
1150 			else
1151 #endif
1152 				ip->ip_tos |= IPTOS_ECN_ECT0;
1153 			TCPSTAT_INC(tcps_ecn_ect0);
1154 		}
1155 
1156 		/*
1157 		 * Reply with proper ECN notifications.
1158 		 */
1159 		if (tp->t_flags & TF_ECN_SND_CWR) {
1160 			flags |= TH_CWR;
1161 			tp->t_flags &= ~TF_ECN_SND_CWR;
1162 		}
1163 		if (tp->t_flags & TF_ECN_SND_ECE)
1164 			flags |= TH_ECE;
1165 	}
1166 
1167 	/*
1168 	 * If we are doing retransmissions, then snd_nxt will
1169 	 * not reflect the first unsent octet.  For ACK only
1170 	 * packets, we do not want the sequence number of the
1171 	 * retransmitted packet, we want the sequence number
1172 	 * of the next unsent octet.  So, if there is no data
1173 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
1174 	 * when filling in ti_seq.  But if we are in persist
1175 	 * state, snd_max might reflect one byte beyond the
1176 	 * right edge of the window, so use snd_nxt in that
1177 	 * case, since we know we aren't doing a retransmission.
1178 	 * (retransmit and persist are mutually exclusive...)
1179 	 */
1180 	if (sack_rxmit == 0) {
1181 		if (len || (flags & (TH_SYN|TH_FIN)) ||
1182 		    tcp_timer_active(tp, TT_PERSIST))
1183 			th->th_seq = htonl(tp->snd_nxt);
1184 		else
1185 			th->th_seq = htonl(tp->snd_max);
1186 	} else {
1187 		th->th_seq = htonl(p->rxmit);
1188 		p->rxmit += len;
1189 		tp->sackhint.sack_bytes_rexmit += len;
1190 	}
1191 	th->th_ack = htonl(tp->rcv_nxt);
1192 	if (optlen) {
1193 		bcopy(opt, th + 1, optlen);
1194 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1195 	}
1196 	th->th_flags = flags;
1197 	/*
1198 	 * Calculate receive window.  Don't shrink window,
1199 	 * but avoid silly window syndrome.
1200 	 */
1201 	if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
1202 	    recwin < (long)tp->t_maxseg)
1203 		recwin = 0;
1204 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
1205 	    recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
1206 		recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
1207 	if (recwin > (long)TCP_MAXWIN << tp->rcv_scale)
1208 		recwin = (long)TCP_MAXWIN << tp->rcv_scale;
1209 
1210 	/*
1211 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1212 	 * or <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK>
1213 	 * case is handled in syncache.
1214 	 */
1215 	if (flags & TH_SYN)
1216 		th->th_win = htons((u_short)
1217 				(min(sbspace(&so->so_rcv), TCP_MAXWIN)));
1218 	else
1219 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
1220 
1221 	/*
1222 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
1223 	 * a 0 window.  This may cause the remote transmitter to stall.  This
1224 	 * flag tells soreceive() to disable delayed acknowledgements when
1225 	 * draining the buffer.  This can occur if the receiver is attempting
1226 	 * to read more data than can be buffered prior to transmitting on
1227 	 * the connection.
1228 	 */
1229 	if (th->th_win == 0) {
1230 		tp->t_sndzerowin++;
1231 		tp->t_flags |= TF_RXWIN0SENT;
1232 	} else
1233 		tp->t_flags &= ~TF_RXWIN0SENT;
1234 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1235 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
1236 		th->th_flags |= TH_URG;
1237 	} else
1238 		/*
1239 		 * If no urgent pointer to send, then we pull
1240 		 * the urgent pointer to the left edge of the send window
1241 		 * so that it doesn't drift into the send window on sequence
1242 		 * number wraparound.
1243 		 */
1244 		tp->snd_up = tp->snd_una;		/* drag it along */
1245 
1246 #ifdef TCP_SIGNATURE
1247 	if (to.to_flags & TOF_SIGNATURE) {
1248 		int sigoff = to.to_signature - opt;
1249 		tcp_signature_compute(m, 0, len, optlen,
1250 		    (u_char *)(th + 1) + sigoff, IPSEC_DIR_OUTBOUND);
1251 	}
1252 #endif
1253 
1254 	/*
1255 	 * Put TCP length in extended header, and then
1256 	 * checksum extended header and data.
1257 	 */
1258 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
1259 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1260 #ifdef INET6
1261 	if (isipv6) {
1262 		/*
1263 		 * ip6_plen is not need to be filled now, and will be filled
1264 		 * in ip6_output.
1265 		 */
1266 		m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
1267 		th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
1268 		    optlen + len, IPPROTO_TCP, 0);
1269 	}
1270 #endif
1271 #if defined(INET6) && defined(INET)
1272 	else
1273 #endif
1274 #ifdef INET
1275 	{
1276 		m->m_pkthdr.csum_flags = CSUM_TCP;
1277 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1278 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP + len + optlen));
1279 
1280 		/* IP version must be set here for ipv4/ipv6 checking later */
1281 		KASSERT(ip->ip_v == IPVERSION,
1282 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
1283 	}
1284 #endif
1285 
1286 	/*
1287 	 * Enable TSO and specify the size of the segments.
1288 	 * The TCP pseudo header checksum is always provided.
1289 	 */
1290 	if (tso) {
1291 		KASSERT(len > tp->t_maxseg - optlen,
1292 		    ("%s: len <= tso_segsz", __func__));
1293 		m->m_pkthdr.csum_flags |= CSUM_TSO;
1294 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
1295 	}
1296 
1297 #ifdef IPSEC
1298 	KASSERT(len + hdrlen + ipoptlen - ipsec_optlen == m_length(m, NULL),
1299 	    ("%s: mbuf chain shorter than expected: %ld + %u + %u - %u != %u",
1300 	    __func__, len, hdrlen, ipoptlen, ipsec_optlen, m_length(m, NULL)));
1301 #else
1302 	KASSERT(len + hdrlen + ipoptlen == m_length(m, NULL),
1303 	    ("%s: mbuf chain shorter than expected: %ld + %u + %u != %u",
1304 	    __func__, len, hdrlen, ipoptlen, m_length(m, NULL)));
1305 #endif
1306 
1307 	/* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
1308 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
1309 
1310 #ifdef TCPDEBUG
1311 	/*
1312 	 * Trace.
1313 	 */
1314 	if (so->so_options & SO_DEBUG) {
1315 		u_short save = 0;
1316 #ifdef INET6
1317 		if (!isipv6)
1318 #endif
1319 		{
1320 			save = ipov->ih_len;
1321 			ipov->ih_len = htons(m->m_pkthdr.len /* - hdrlen + (th->th_off << 2) */);
1322 		}
1323 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
1324 #ifdef INET6
1325 		if (!isipv6)
1326 #endif
1327 		ipov->ih_len = save;
1328 	}
1329 #endif /* TCPDEBUG */
1330 	TCP_PROBE3(debug__output, tp, th, mtod(m, const char *));
1331 
1332 	/*
1333 	 * Fill in IP length and desired time to live and
1334 	 * send to IP level.  There should be a better way
1335 	 * to handle ttl and tos; we could keep them in
1336 	 * the template, but need a way to checksum without them.
1337 	 */
1338 	/*
1339 	 * m->m_pkthdr.len should have been set before checksum calculation,
1340 	 * because in6_cksum() need it.
1341 	 */
1342 #ifdef INET6
1343 	if (isipv6) {
1344 		struct route_in6 ro;
1345 
1346 		bzero(&ro, sizeof(ro));
1347 		/*
1348 		 * we separately set hoplimit for every segment, since the
1349 		 * user might want to change the value via setsockopt.
1350 		 * Also, desired default hop limit might be changed via
1351 		 * Neighbor Discovery.
1352 		 */
1353 		ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb, NULL);
1354 
1355 		/*
1356 		 * Set the packet size here for the benefit of DTrace probes.
1357 		 * ip6_output() will set it properly; it's supposed to include
1358 		 * the option header lengths as well.
1359 		 */
1360 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
1361 
1362 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
1363 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
1364 		else
1365 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
1366 
1367 		if (tp->t_state == TCPS_SYN_SENT)
1368 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
1369 
1370 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
1371 
1372 #ifdef TCPPCAP
1373 		/* Save packet, if requested. */
1374 		tcp_pcap_add(th, m, &(tp->t_outpkts));
1375 #endif
1376 
1377 		/* TODO: IPv6 IP6TOS_ECT bit on */
1378 		error = ip6_output(m, tp->t_inpcb->in6p_outputopts, &ro,
1379 		    ((so->so_options & SO_DONTROUTE) ?  IP_ROUTETOIF : 0),
1380 		    NULL, NULL, tp->t_inpcb);
1381 
1382 		if (error == EMSGSIZE && ro.ro_rt != NULL)
1383 			mtu = ro.ro_rt->rt_mtu;
1384 		RO_RTFREE(&ro);
1385 	}
1386 #endif /* INET6 */
1387 #if defined(INET) && defined(INET6)
1388 	else
1389 #endif
1390 #ifdef INET
1391     {
1392 	ip->ip_len = htons(m->m_pkthdr.len);
1393 #ifdef INET6
1394 	if (tp->t_inpcb->inp_vflag & INP_IPV6PROTO)
1395 		ip->ip_ttl = in6_selecthlim(tp->t_inpcb, NULL);
1396 #endif /* INET6 */
1397 	/*
1398 	 * If we do path MTU discovery, then we set DF on every packet.
1399 	 * This might not be the best thing to do according to RFC3390
1400 	 * Section 2. However the tcp hostcache migitates the problem
1401 	 * so it affects only the first tcp connection with a host.
1402 	 *
1403 	 * NB: Don't set DF on small MTU/MSS to have a safe fallback.
1404 	 */
1405 	if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
1406 		ip->ip_off |= htons(IP_DF);
1407 		tp->t_flags2 |= TF2_PLPMTU_PMTUD;
1408 	} else {
1409 		tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
1410 	}
1411 
1412 	if (tp->t_state == TCPS_SYN_SENT)
1413 		TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
1414 
1415 	TCP_PROBE5(send, NULL, tp, ip, tp, th);
1416 
1417 #ifdef TCPPCAP
1418 	/* Save packet, if requested. */
1419 	tcp_pcap_add(th, m, &(tp->t_outpkts));
1420 #endif
1421 
1422 	error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
1423 	    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
1424 	    tp->t_inpcb);
1425 
1426 	if (error == EMSGSIZE && tp->t_inpcb->inp_route.ro_rt != NULL)
1427 		mtu = tp->t_inpcb->inp_route.ro_rt->rt_mtu;
1428     }
1429 #endif /* INET */
1430 
1431 out:
1432 	/*
1433 	 * In transmit state, time the transmission and arrange for
1434 	 * the retransmit.  In persist state, just set snd_max.
1435 	 */
1436 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
1437 	    !tcp_timer_active(tp, TT_PERSIST)) {
1438 		tcp_seq startseq = tp->snd_nxt;
1439 
1440 		/*
1441 		 * Advance snd_nxt over sequence space of this segment.
1442 		 */
1443 		if (flags & (TH_SYN|TH_FIN)) {
1444 			if (flags & TH_SYN)
1445 				tp->snd_nxt++;
1446 			if (flags & TH_FIN) {
1447 				tp->snd_nxt++;
1448 				tp->t_flags |= TF_SENTFIN;
1449 			}
1450 		}
1451 		if (sack_rxmit)
1452 			goto timer;
1453 		tp->snd_nxt += len;
1454 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1455 			tp->snd_max = tp->snd_nxt;
1456 			/*
1457 			 * Time this transmission if not a retransmission and
1458 			 * not currently timing anything.
1459 			 */
1460 			if (tp->t_rtttime == 0) {
1461 				tp->t_rtttime = ticks;
1462 				tp->t_rtseq = startseq;
1463 				TCPSTAT_INC(tcps_segstimed);
1464 			}
1465 		}
1466 
1467 		/*
1468 		 * Set retransmit timer if not currently set,
1469 		 * and not doing a pure ack or a keep-alive probe.
1470 		 * Initial value for retransmit timer is smoothed
1471 		 * round-trip time + 2 * round-trip time variance.
1472 		 * Initialize shift counter which is used for backoff
1473 		 * of retransmit time.
1474 		 */
1475 timer:
1476 		if (!tcp_timer_active(tp, TT_REXMT) &&
1477 		    ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
1478 		     (tp->snd_nxt != tp->snd_una))) {
1479 			if (tcp_timer_active(tp, TT_PERSIST)) {
1480 				tcp_timer_activate(tp, TT_PERSIST, 0);
1481 				tp->t_rxtshift = 0;
1482 			}
1483 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1484 		} else if (len == 0 && sbavail(&so->so_snd) &&
1485 		    !tcp_timer_active(tp, TT_REXMT) &&
1486 		    !tcp_timer_active(tp, TT_PERSIST)) {
1487 			/*
1488 			 * Avoid a situation where we do not set persist timer
1489 			 * after a zero window condition. For example:
1490 			 * 1) A -> B: packet with enough data to fill the window
1491 			 * 2) B -> A: ACK for #1 + new data (0 window
1492 			 *    advertisement)
1493 			 * 3) A -> B: ACK for #2, 0 len packet
1494 			 *
1495 			 * In this case, A will not activate the persist timer,
1496 			 * because it chose to send a packet. Unless tcp_output
1497 			 * is called for some other reason (delayed ack timer,
1498 			 * another input packet from B, socket syscall), A will
1499 			 * not send zero window probes.
1500 			 *
1501 			 * So, if you send a 0-length packet, but there is data
1502 			 * in the socket buffer, and neither the rexmt or
1503 			 * persist timer is already set, then activate the
1504 			 * persist timer.
1505 			 */
1506 			tp->t_rxtshift = 0;
1507 			tcp_setpersist(tp);
1508 		}
1509 	} else {
1510 		/*
1511 		 * Persist case, update snd_max but since we are in
1512 		 * persist mode (no window) we do not update snd_nxt.
1513 		 */
1514 		int xlen = len;
1515 		if (flags & TH_SYN)
1516 			++xlen;
1517 		if (flags & TH_FIN) {
1518 			++xlen;
1519 			tp->t_flags |= TF_SENTFIN;
1520 		}
1521 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1522 			tp->snd_max = tp->snd_nxt + len;
1523 	}
1524 
1525 	if (error) {
1526 
1527 		/*
1528 		 * We know that the packet was lost, so back out the
1529 		 * sequence number advance, if any.
1530 		 *
1531 		 * If the error is EPERM the packet got blocked by the
1532 		 * local firewall.  Normally we should terminate the
1533 		 * connection but the blocking may have been spurious
1534 		 * due to a firewall reconfiguration cycle.  So we treat
1535 		 * it like a packet loss and let the retransmit timer and
1536 		 * timeouts do their work over time.
1537 		 * XXX: It is a POLA question whether calling tcp_drop right
1538 		 * away would be the really correct behavior instead.
1539 		 */
1540 		if (((tp->t_flags & TF_FORCEDATA) == 0 ||
1541 		    !tcp_timer_active(tp, TT_PERSIST)) &&
1542 		    ((flags & TH_SYN) == 0) &&
1543 		    (error != EPERM)) {
1544 			if (sack_rxmit) {
1545 				p->rxmit -= len;
1546 				tp->sackhint.sack_bytes_rexmit -= len;
1547 				KASSERT(tp->sackhint.sack_bytes_rexmit >= 0,
1548 				    ("sackhint bytes rtx >= 0"));
1549 			} else
1550 				tp->snd_nxt -= len;
1551 		}
1552 		SOCKBUF_UNLOCK_ASSERT(&so->so_snd);	/* Check gotos. */
1553 		switch (error) {
1554 		case EPERM:
1555 			tp->t_softerror = error;
1556 			return (error);
1557 		case ENOBUFS:
1558 			TCP_XMIT_TIMER_ASSERT(tp, len, flags);
1559 			tp->snd_cwnd = tp->t_maxseg;
1560 			return (0);
1561 		case EMSGSIZE:
1562 			/*
1563 			 * For some reason the interface we used initially
1564 			 * to send segments changed to another or lowered
1565 			 * its MTU.
1566 			 * If TSO was active we either got an interface
1567 			 * without TSO capabilits or TSO was turned off.
1568 			 * If we obtained mtu from ip_output() then update
1569 			 * it and try again.
1570 			 */
1571 			if (tso)
1572 				tp->t_flags &= ~TF_TSO;
1573 			if (mtu != 0) {
1574 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
1575 				goto again;
1576 			}
1577 			return (error);
1578 		case EHOSTDOWN:
1579 		case EHOSTUNREACH:
1580 		case ENETDOWN:
1581 		case ENETUNREACH:
1582 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
1583 				tp->t_softerror = error;
1584 				return (0);
1585 			}
1586 			/* FALLTHROUGH */
1587 		default:
1588 			return (error);
1589 		}
1590 	}
1591 	TCPSTAT_INC(tcps_sndtotal);
1592 
1593 	/*
1594 	 * Data sent (as far as we can tell).
1595 	 * If this advertises a larger window than any other segment,
1596 	 * then remember the size of the advertised window.
1597 	 * Any pending ACK has now been sent.
1598 	 */
1599 	if (recwin >= 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
1600 		tp->rcv_adv = tp->rcv_nxt + recwin;
1601 	tp->last_ack_sent = tp->rcv_nxt;
1602 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
1603 	if (tcp_timer_active(tp, TT_DELACK))
1604 		tcp_timer_activate(tp, TT_DELACK, 0);
1605 #if 0
1606 	/*
1607 	 * This completely breaks TCP if newreno is turned on.  What happens
1608 	 * is that if delayed-acks are turned on on the receiver, this code
1609 	 * on the transmitter effectively destroys the TCP window, forcing
1610 	 * it to four packets (1.5Kx4 = 6K window).
1611 	 */
1612 	if (sendalot && --maxburst)
1613 		goto again;
1614 #endif
1615 	if (sendalot)
1616 		goto again;
1617 	return (0);
1618 }
1619 
1620 void
1621 tcp_setpersist(struct tcpcb *tp)
1622 {
1623 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1624 	int tt;
1625 
1626 	tp->t_flags &= ~TF_PREVVALID;
1627 	if (tcp_timer_active(tp, TT_REXMT))
1628 		panic("tcp_setpersist: retransmit pending");
1629 	/*
1630 	 * Start/restart persistence timer.
1631 	 */
1632 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
1633 		      tcp_persmin, tcp_persmax);
1634 	tcp_timer_activate(tp, TT_PERSIST, tt);
1635 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1636 		tp->t_rxtshift++;
1637 }
1638 
1639 /*
1640  * Insert TCP options according to the supplied parameters to the place
1641  * optp in a consistent way.  Can handle unaligned destinations.
1642  *
1643  * The order of the option processing is crucial for optimal packing and
1644  * alignment for the scarce option space.
1645  *
1646  * The optimal order for a SYN/SYN-ACK segment is:
1647  *   MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) +
1648  *   Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40.
1649  *
1650  * The SACK options should be last.  SACK blocks consume 8*n+2 bytes.
1651  * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks).
1652  * At minimum we need 10 bytes (to generate 1 SACK block).  If both
1653  * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present,
1654  * we only have 10 bytes for SACK options (40 - (12 + 18)).
1655  */
1656 int
1657 tcp_addoptions(struct tcpopt *to, u_char *optp)
1658 {
1659 	u_int32_t mask, optlen = 0;
1660 
1661 	for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) {
1662 		if ((to->to_flags & mask) != mask)
1663 			continue;
1664 		if (optlen == TCP_MAXOLEN)
1665 			break;
1666 		switch (to->to_flags & mask) {
1667 		case TOF_MSS:
1668 			while (optlen % 4) {
1669 				optlen += TCPOLEN_NOP;
1670 				*optp++ = TCPOPT_NOP;
1671 			}
1672 			if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG)
1673 				continue;
1674 			optlen += TCPOLEN_MAXSEG;
1675 			*optp++ = TCPOPT_MAXSEG;
1676 			*optp++ = TCPOLEN_MAXSEG;
1677 			to->to_mss = htons(to->to_mss);
1678 			bcopy((u_char *)&to->to_mss, optp, sizeof(to->to_mss));
1679 			optp += sizeof(to->to_mss);
1680 			break;
1681 		case TOF_SCALE:
1682 			while (!optlen || optlen % 2 != 1) {
1683 				optlen += TCPOLEN_NOP;
1684 				*optp++ = TCPOPT_NOP;
1685 			}
1686 			if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW)
1687 				continue;
1688 			optlen += TCPOLEN_WINDOW;
1689 			*optp++ = TCPOPT_WINDOW;
1690 			*optp++ = TCPOLEN_WINDOW;
1691 			*optp++ = to->to_wscale;
1692 			break;
1693 		case TOF_SACKPERM:
1694 			while (optlen % 2) {
1695 				optlen += TCPOLEN_NOP;
1696 				*optp++ = TCPOPT_NOP;
1697 			}
1698 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED)
1699 				continue;
1700 			optlen += TCPOLEN_SACK_PERMITTED;
1701 			*optp++ = TCPOPT_SACK_PERMITTED;
1702 			*optp++ = TCPOLEN_SACK_PERMITTED;
1703 			break;
1704 		case TOF_TS:
1705 			while (!optlen || optlen % 4 != 2) {
1706 				optlen += TCPOLEN_NOP;
1707 				*optp++ = TCPOPT_NOP;
1708 			}
1709 			if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP)
1710 				continue;
1711 			optlen += TCPOLEN_TIMESTAMP;
1712 			*optp++ = TCPOPT_TIMESTAMP;
1713 			*optp++ = TCPOLEN_TIMESTAMP;
1714 			to->to_tsval = htonl(to->to_tsval);
1715 			to->to_tsecr = htonl(to->to_tsecr);
1716 			bcopy((u_char *)&to->to_tsval, optp, sizeof(to->to_tsval));
1717 			optp += sizeof(to->to_tsval);
1718 			bcopy((u_char *)&to->to_tsecr, optp, sizeof(to->to_tsecr));
1719 			optp += sizeof(to->to_tsecr);
1720 			break;
1721 #ifdef TCP_SIGNATURE
1722 		case TOF_SIGNATURE:
1723 			{
1724 			int siglen = TCPOLEN_SIGNATURE - 2;
1725 
1726 			while (!optlen || optlen % 4 != 2) {
1727 				optlen += TCPOLEN_NOP;
1728 				*optp++ = TCPOPT_NOP;
1729 			}
1730 			if (TCP_MAXOLEN - optlen < TCPOLEN_SIGNATURE)
1731 				continue;
1732 			optlen += TCPOLEN_SIGNATURE;
1733 			*optp++ = TCPOPT_SIGNATURE;
1734 			*optp++ = TCPOLEN_SIGNATURE;
1735 			to->to_signature = optp;
1736 			while (siglen--)
1737 				 *optp++ = 0;
1738 			break;
1739 			}
1740 #endif
1741 		case TOF_SACK:
1742 			{
1743 			int sackblks = 0;
1744 			struct sackblk *sack = (struct sackblk *)to->to_sacks;
1745 			tcp_seq sack_seq;
1746 
1747 			while (!optlen || optlen % 4 != 2) {
1748 				optlen += TCPOLEN_NOP;
1749 				*optp++ = TCPOPT_NOP;
1750 			}
1751 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK)
1752 				continue;
1753 			optlen += TCPOLEN_SACKHDR;
1754 			*optp++ = TCPOPT_SACK;
1755 			sackblks = min(to->to_nsacks,
1756 					(TCP_MAXOLEN - optlen) / TCPOLEN_SACK);
1757 			*optp++ = TCPOLEN_SACKHDR + sackblks * TCPOLEN_SACK;
1758 			while (sackblks--) {
1759 				sack_seq = htonl(sack->start);
1760 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
1761 				optp += sizeof(sack_seq);
1762 				sack_seq = htonl(sack->end);
1763 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
1764 				optp += sizeof(sack_seq);
1765 				optlen += TCPOLEN_SACK;
1766 				sack++;
1767 			}
1768 			TCPSTAT_INC(tcps_sack_send_blocks);
1769 			break;
1770 			}
1771 #ifdef TCP_RFC7413
1772 		case TOF_FASTOPEN:
1773 			{
1774 			int total_len;
1775 
1776 			/* XXX is there any point to aligning this option? */
1777 			total_len = TCPOLEN_FAST_OPEN_EMPTY + to->to_tfo_len;
1778 			if (TCP_MAXOLEN - optlen < total_len)
1779 				continue;
1780 			*optp++ = TCPOPT_FAST_OPEN;
1781 			*optp++ = total_len;
1782 			if (to->to_tfo_len > 0) {
1783 				bcopy(to->to_tfo_cookie, optp, to->to_tfo_len);
1784 				optp += to->to_tfo_len;
1785 			}
1786 			optlen += total_len;
1787 			break;
1788 			}
1789 #endif
1790 		default:
1791 			panic("%s: unknown TCP option type", __func__);
1792 			break;
1793 		}
1794 	}
1795 
1796 	/* Terminate and pad TCP options to a 4 byte boundary. */
1797 	if (optlen % 4) {
1798 		optlen += TCPOLEN_EOL;
1799 		*optp++ = TCPOPT_EOL;
1800 	}
1801 	/*
1802 	 * According to RFC 793 (STD0007):
1803 	 *   "The content of the header beyond the End-of-Option option
1804 	 *    must be header padding (i.e., zero)."
1805 	 *   and later: "The padding is composed of zeros."
1806 	 */
1807 	while (optlen % 4) {
1808 		optlen += TCPOLEN_PAD;
1809 		*optp++ = TCPOPT_PAD;
1810 	}
1811 
1812 	KASSERT(optlen <= TCP_MAXOLEN, ("%s: TCP options too long", __func__));
1813 	return (optlen);
1814 }
1815