xref: /freebsd/sys/netinet/tcp_output.c (revision 5861f9665471e98e544f6fa3ce73c4912229ff82)
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/kernel.h>
44 #include <sys/lock.h>
45 #include <sys/mbuf.h>
46 #include <sys/mutex.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/vimage.h>
52 
53 #include <net/if.h>
54 #include <net/route.h>
55 
56 #include <netinet/in.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/ip.h>
59 #include <netinet/in_pcb.h>
60 #include <netinet/ip_var.h>
61 #include <netinet/ip_options.h>
62 #ifdef INET6
63 #include <netinet6/in6_pcb.h>
64 #include <netinet/ip6.h>
65 #include <netinet6/ip6_var.h>
66 #endif
67 #include <netinet/tcp.h>
68 #define	TCPOUTFLAGS
69 #include <netinet/tcp_fsm.h>
70 #include <netinet/tcp_seq.h>
71 #include <netinet/tcp_timer.h>
72 #include <netinet/tcp_var.h>
73 #include <netinet/tcpip.h>
74 #ifdef TCPDEBUG
75 #include <netinet/tcp_debug.h>
76 #endif
77 #include <netinet/vinet.h>
78 
79 #ifdef IPSEC
80 #include <netipsec/ipsec.h>
81 #endif /*IPSEC*/
82 
83 #include <machine/in_cksum.h>
84 
85 #include <security/mac/mac_framework.h>
86 
87 #ifdef notyet
88 extern struct mbuf *m_copypack();
89 #endif
90 
91 #ifdef VIMAGE_GLOBALS
92 int path_mtu_discovery;
93 int ss_fltsz;
94 int ss_fltsz_local;
95 int tcp_do_newreno;
96 int tcp_do_tso;
97 int tcp_do_autosndbuf;
98 int tcp_autosndbuf_inc;
99 int tcp_autosndbuf_max;
100 #endif
101 
102 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, path_mtu_discovery,
103 	CTLFLAG_RW, path_mtu_discovery, 1, "Enable Path MTU Discovery");
104 
105 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO,
106 	slowstart_flightsize, CTLFLAG_RW,
107 	ss_fltsz, 1, "Slow start flight size");
108 
109 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO,
110 	local_slowstart_flightsize, CTLFLAG_RW,
111 	ss_fltsz_local, 1, "Slow start flight size for local networks");
112 
113 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, newreno, CTLFLAG_RW,
114 	tcp_do_newreno, 0, "Enable NewReno Algorithms");
115 
116 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, tso, CTLFLAG_RW,
117 	tcp_do_tso, 0, "Enable TCP Segmentation Offload");
118 
119 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, sendbuf_auto,
120 	CTLFLAG_RW,
121 	tcp_do_autosndbuf, 0, "Enable automatic send buffer sizing");
122 
123 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, sendbuf_inc,
124 	CTLFLAG_RW, tcp_autosndbuf_inc, 0,
125 	"Incrementor step size of automatic send buffer");
126 
127 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, sendbuf_max,
128 	CTLFLAG_RW, tcp_autosndbuf_max, 0,
129 	"Max size of automatic send buffer");
130 
131 
132 /*
133  * Tcp output routine: figure out what should be sent and send it.
134  */
135 int
136 tcp_output(struct tcpcb *tp)
137 {
138 	INIT_VNET_INET(tp->t_inpcb->inp_vnet);
139 	struct socket *so = tp->t_inpcb->inp_socket;
140 	long len, recwin, sendwin;
141 	int off, flags, error;
142 	struct mbuf *m;
143 	struct ip *ip = NULL;
144 	struct ipovly *ipov = NULL;
145 	struct tcphdr *th;
146 	u_char opt[TCP_MAXOLEN];
147 	unsigned ipoptlen, optlen, hdrlen;
148 #ifdef IPSEC
149 	unsigned ipsec_optlen = 0;
150 #endif
151 	int idle, sendalot;
152 	int sack_rxmit, sack_bytes_rxmt;
153 	struct sackhole *p;
154 	int tso = 0;
155 	struct tcpopt to;
156 #if 0
157 	int maxburst = TCP_MAXBURST;
158 #endif
159 #ifdef INET6
160 	struct ip6_hdr *ip6 = NULL;
161 	int isipv6;
162 
163 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
164 #endif
165 
166 	INP_WLOCK_ASSERT(tp->t_inpcb);
167 
168 	/*
169 	 * Determine length of data that should be transmitted,
170 	 * and flags that will be used.
171 	 * If there is some data or critical controls (SYN, RST)
172 	 * to send, then transmit; otherwise, investigate further.
173 	 */
174 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
175 	if (idle && ticks - tp->t_rcvtime >= tp->t_rxtcur) {
176 		/*
177 		 * We have been idle for "a while" and no acks are
178 		 * expected to clock out any data we send --
179 		 * slow start to get ack "clock" running again.
180 		 *
181 		 * Set the slow-start flight size depending on whether
182 		 * this is a local network or not.
183 		 */
184 		int ss = V_ss_fltsz;
185 #ifdef INET6
186 		if (isipv6) {
187 			if (in6_localaddr(&tp->t_inpcb->in6p_faddr))
188 				ss = V_ss_fltsz_local;
189 		} else
190 #endif /* INET6 */
191 		if (in_localaddr(tp->t_inpcb->inp_faddr))
192 			ss = V_ss_fltsz_local;
193 		tp->snd_cwnd = tp->t_maxseg * ss;
194 	}
195 	tp->t_flags &= ~TF_LASTIDLE;
196 	if (idle) {
197 		if (tp->t_flags & TF_MORETOCOME) {
198 			tp->t_flags |= TF_LASTIDLE;
199 			idle = 0;
200 		}
201 	}
202 again:
203 	/*
204 	 * If we've recently taken a timeout, snd_max will be greater than
205 	 * snd_nxt.  There may be SACK information that allows us to avoid
206 	 * resending already delivered data.  Adjust snd_nxt accordingly.
207 	 */
208 	if ((tp->t_flags & TF_SACK_PERMIT) &&
209 	    SEQ_LT(tp->snd_nxt, tp->snd_max))
210 		tcp_sack_adjust(tp);
211 	sendalot = 0;
212 	off = tp->snd_nxt - tp->snd_una;
213 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
214 	sendwin = min(sendwin, tp->snd_bwnd);
215 
216 	flags = tcp_outflags[tp->t_state];
217 	/*
218 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
219 	 * to send out new data (when sendalot is 1), bypass this function.
220 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
221 	 * we're replacing a (future) new transmission with a retransmission
222 	 * now, and we previously incremented snd_cwnd in tcp_input().
223 	 */
224 	/*
225 	 * Still in sack recovery , reset rxmit flag to zero.
226 	 */
227 	sack_rxmit = 0;
228 	sack_bytes_rxmt = 0;
229 	len = 0;
230 	p = NULL;
231 	if ((tp->t_flags & TF_SACK_PERMIT) && IN_FASTRECOVERY(tp) &&
232 	    (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
233 		long cwin;
234 
235 		cwin = min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
236 		if (cwin < 0)
237 			cwin = 0;
238 		/* Do not retransmit SACK segments beyond snd_recover */
239 		if (SEQ_GT(p->end, tp->snd_recover)) {
240 			/*
241 			 * (At least) part of sack hole extends beyond
242 			 * snd_recover. Check to see if we can rexmit data
243 			 * for this hole.
244 			 */
245 			if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
246 				/*
247 				 * Can't rexmit any more data for this hole.
248 				 * That data will be rexmitted in the next
249 				 * sack recovery episode, when snd_recover
250 				 * moves past p->rxmit.
251 				 */
252 				p = NULL;
253 				goto after_sack_rexmit;
254 			} else
255 				/* Can rexmit part of the current hole */
256 				len = ((long)ulmin(cwin,
257 						   tp->snd_recover - p->rxmit));
258 		} else
259 			len = ((long)ulmin(cwin, p->end - p->rxmit));
260 		off = p->rxmit - tp->snd_una;
261 		KASSERT(off >= 0,("%s: sack block to the left of una : %d",
262 		    __func__, off));
263 		if (len > 0) {
264 			sack_rxmit = 1;
265 			sendalot = 1;
266 			TCPSTAT_INC(tcps_sack_rexmits);
267 			TCPSTAT_ADD(tcps_sack_rexmit_bytes,
268 			    min(len, tp->t_maxseg));
269 		}
270 	}
271 after_sack_rexmit:
272 	/*
273 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
274 	 * state flags.
275 	 */
276 	if (tp->t_flags & TF_NEEDFIN)
277 		flags |= TH_FIN;
278 	if (tp->t_flags & TF_NEEDSYN)
279 		flags |= TH_SYN;
280 
281 	SOCKBUF_LOCK(&so->so_snd);
282 	/*
283 	 * If in persist timeout with window of 0, send 1 byte.
284 	 * Otherwise, if window is small but nonzero
285 	 * and timer expired, we will send what we can
286 	 * and go to transmit state.
287 	 */
288 	if (tp->t_flags & TF_FORCEDATA) {
289 		if (sendwin == 0) {
290 			/*
291 			 * If we still have some data to send, then
292 			 * clear the FIN bit.  Usually this would
293 			 * happen below when it realizes that we
294 			 * aren't sending all the data.  However,
295 			 * if we have exactly 1 byte of unsent data,
296 			 * then it won't clear the FIN bit below,
297 			 * and if we are in persist state, we wind
298 			 * up sending the packet without recording
299 			 * that we sent the FIN bit.
300 			 *
301 			 * We can't just blindly clear the FIN bit,
302 			 * because if we don't have any more data
303 			 * to send then the probe will be the FIN
304 			 * itself.
305 			 */
306 			if (off < so->so_snd.sb_cc)
307 				flags &= ~TH_FIN;
308 			sendwin = 1;
309 		} else {
310 			tcp_timer_activate(tp, TT_PERSIST, 0);
311 			tp->t_rxtshift = 0;
312 		}
313 	}
314 
315 	/*
316 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
317 	 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
318 	 * a negative length.  This can also occur when TCP opens up
319 	 * its congestion window while receiving additional duplicate
320 	 * acks after fast-retransmit because TCP will reset snd_nxt
321 	 * to snd_max after the fast-retransmit.
322 	 *
323 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
324 	 * be set to snd_una, the offset will be 0, and the length may
325 	 * wind up 0.
326 	 *
327 	 * If sack_rxmit is true we are retransmitting from the scoreboard
328 	 * in which case len is already set.
329 	 */
330 	if (sack_rxmit == 0) {
331 		if (sack_bytes_rxmt == 0)
332 			len = ((long)ulmin(so->so_snd.sb_cc, sendwin) - off);
333 		else {
334 			long cwin;
335 
336                         /*
337 			 * We are inside of a SACK recovery episode and are
338 			 * sending new data, having retransmitted all the
339 			 * data possible in the scoreboard.
340 			 */
341 			len = ((long)ulmin(so->so_snd.sb_cc, tp->snd_wnd)
342 			       - off);
343 			/*
344 			 * Don't remove this (len > 0) check !
345 			 * We explicitly check for len > 0 here (although it
346 			 * isn't really necessary), to work around a gcc
347 			 * optimization issue - to force gcc to compute
348 			 * len above. Without this check, the computation
349 			 * of len is bungled by the optimizer.
350 			 */
351 			if (len > 0) {
352 				cwin = tp->snd_cwnd -
353 					(tp->snd_nxt - tp->sack_newdata) -
354 					sack_bytes_rxmt;
355 				if (cwin < 0)
356 					cwin = 0;
357 				len = lmin(len, cwin);
358 			}
359 		}
360 	}
361 
362 	/*
363 	 * Lop off SYN bit if it has already been sent.  However, if this
364 	 * is SYN-SENT state and if segment contains data and if we don't
365 	 * know that foreign host supports TAO, suppress sending segment.
366 	 */
367 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
368 		if (tp->t_state != TCPS_SYN_RECEIVED)
369 			flags &= ~TH_SYN;
370 		off--, len++;
371 	}
372 
373 	/*
374 	 * Be careful not to send data and/or FIN on SYN segments.
375 	 * This measure is needed to prevent interoperability problems
376 	 * with not fully conformant TCP implementations.
377 	 */
378 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
379 		len = 0;
380 		flags &= ~TH_FIN;
381 	}
382 
383 	if (len < 0) {
384 		/*
385 		 * If FIN has been sent but not acked,
386 		 * but we haven't been called to retransmit,
387 		 * len will be < 0.  Otherwise, window shrank
388 		 * after we sent into it.  If window shrank to 0,
389 		 * cancel pending retransmit, pull snd_nxt back
390 		 * to (closed) window, and set the persist timer
391 		 * if it isn't already going.  If the window didn't
392 		 * close completely, just wait for an ACK.
393 		 */
394 		len = 0;
395 		if (sendwin == 0) {
396 			tcp_timer_activate(tp, TT_REXMT, 0);
397 			tp->t_rxtshift = 0;
398 			tp->snd_nxt = tp->snd_una;
399 			if (!tcp_timer_active(tp, TT_PERSIST))
400 				tcp_setpersist(tp);
401 		}
402 	}
403 
404 	/* len will be >= 0 after this point. */
405 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
406 
407 	/*
408 	 * Automatic sizing of send socket buffer.  Often the send buffer
409 	 * size is not optimally adjusted to the actual network conditions
410 	 * at hand (delay bandwidth product).  Setting the buffer size too
411 	 * small limits throughput on links with high bandwidth and high
412 	 * delay (eg. trans-continental/oceanic links).  Setting the
413 	 * buffer size too big consumes too much real kernel memory,
414 	 * especially with many connections on busy servers.
415 	 *
416 	 * The criteria to step up the send buffer one notch are:
417 	 *  1. receive window of remote host is larger than send buffer
418 	 *     (with a fudge factor of 5/4th);
419 	 *  2. send buffer is filled to 7/8th with data (so we actually
420 	 *     have data to make use of it);
421 	 *  3. send buffer fill has not hit maximal automatic size;
422 	 *  4. our send window (slow start and cogestion controlled) is
423 	 *     larger than sent but unacknowledged data in send buffer.
424 	 *
425 	 * The remote host receive window scaling factor may limit the
426 	 * growing of the send buffer before it reaches its allowed
427 	 * maximum.
428 	 *
429 	 * It scales directly with slow start or congestion window
430 	 * and does at most one step per received ACK.  This fast
431 	 * scaling has the drawback of growing the send buffer beyond
432 	 * what is strictly necessary to make full use of a given
433 	 * delay*bandwith product.  However testing has shown this not
434 	 * to be much of an problem.  At worst we are trading wasting
435 	 * of available bandwith (the non-use of it) for wasting some
436 	 * socket buffer memory.
437 	 *
438 	 * TODO: Shrink send buffer during idle periods together
439 	 * with congestion window.  Requires another timer.  Has to
440 	 * wait for upcoming tcp timer rewrite.
441 	 */
442 	if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
443 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
444 		    so->so_snd.sb_cc >= (so->so_snd.sb_hiwat / 8 * 7) &&
445 		    so->so_snd.sb_cc < V_tcp_autosndbuf_max &&
446 		    sendwin >= (so->so_snd.sb_cc - (tp->snd_nxt - tp->snd_una))) {
447 			if (!sbreserve_locked(&so->so_snd,
448 			    min(so->so_snd.sb_hiwat + V_tcp_autosndbuf_inc,
449 			     V_tcp_autosndbuf_max), so, curthread))
450 				so->so_snd.sb_flags &= ~SB_AUTOSIZE;
451 		}
452 	}
453 
454 	/*
455 	 * Truncate to the maximum segment length or enable TCP Segmentation
456 	 * Offloading (if supported by hardware) and ensure that FIN is removed
457 	 * if the length no longer contains the last data byte.
458 	 *
459 	 * TSO may only be used if we are in a pure bulk sending state.  The
460 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and
461 	 * IP options prevent using TSO.  With TSO the TCP header is the same
462 	 * (except for the sequence number) for all generated packets.  This
463 	 * makes it impossible to transmit any options which vary per generated
464 	 * segment or packet.
465 	 *
466 	 * The length of TSO bursts is limited to TCP_MAXWIN.  That limit and
467 	 * removal of FIN (if not already catched here) are handled later after
468 	 * the exact length of the TCP options are known.
469 	 */
470 #ifdef IPSEC
471 	/*
472 	 * Pre-calculate here as we save another lookup into the darknesses
473 	 * of IPsec that way and can actually decide if TSO is ok.
474 	 */
475 	ipsec_optlen = ipsec_hdrsiz_tcp(tp);
476 #endif
477 	if (len > tp->t_maxseg) {
478 		if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
479 		    ((tp->t_flags & TF_SIGNATURE) == 0) &&
480 		    tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
481 		    tp->t_inpcb->inp_options == NULL &&
482 		    tp->t_inpcb->in6p_options == NULL
483 #ifdef IPSEC
484 		    && ipsec_optlen == 0
485 #endif
486 		    ) {
487 			tso = 1;
488 		} else {
489 			len = tp->t_maxseg;
490 			sendalot = 1;
491 			tso = 0;
492 		}
493 	}
494 	if (sack_rxmit) {
495 		if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc))
496 			flags &= ~TH_FIN;
497 	} else {
498 		if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))
499 			flags &= ~TH_FIN;
500 	}
501 
502 	recwin = sbspace(&so->so_rcv);
503 
504 	/*
505 	 * Sender silly window avoidance.   We transmit under the following
506 	 * conditions when len is non-zero:
507 	 *
508 	 *	- We have a full segment (or more with TSO)
509 	 *	- This is the last buffer in a write()/send() and we are
510 	 *	  either idle or running NODELAY
511 	 *	- we've timed out (e.g. persist timer)
512 	 *	- we have more then 1/2 the maximum send window's worth of
513 	 *	  data (receiver may be limited the window size)
514 	 *	- we need to retransmit
515 	 */
516 	if (len) {
517 		if (len >= tp->t_maxseg)
518 			goto send;
519 		/*
520 		 * NOTE! on localhost connections an 'ack' from the remote
521 		 * end may occur synchronously with the output and cause
522 		 * us to flush a buffer queued with moretocome.  XXX
523 		 *
524 		 * note: the len + off check is almost certainly unnecessary.
525 		 */
526 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
527 		    (idle || (tp->t_flags & TF_NODELAY)) &&
528 		    len + off >= so->so_snd.sb_cc &&
529 		    (tp->t_flags & TF_NOPUSH) == 0) {
530 			goto send;
531 		}
532 		if (tp->t_flags & TF_FORCEDATA)		/* typ. timeout case */
533 			goto send;
534 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
535 			goto send;
536 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
537 			goto send;
538 		if (sack_rxmit)
539 			goto send;
540 	}
541 
542 	/*
543 	 * Compare available window to amount of window
544 	 * known to peer (as advertised window less
545 	 * next expected input).  If the difference is at least two
546 	 * max size segments, or at least 50% of the maximum possible
547 	 * window, then want to send a window update to peer.
548 	 * Skip this if the connection is in T/TCP half-open state.
549 	 * Don't send pure window updates when the peer has closed
550 	 * the connection and won't ever send more data.
551 	 */
552 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
553 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
554 		/*
555 		 * "adv" is the amount we can increase the window,
556 		 * taking into account that we are limited by
557 		 * TCP_MAXWIN << tp->rcv_scale.
558 		 */
559 		long adv = min(recwin, (long)TCP_MAXWIN << tp->rcv_scale) -
560 			(tp->rcv_adv - tp->rcv_nxt);
561 
562 		if (adv >= (long) (2 * tp->t_maxseg))
563 			goto send;
564 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
565 			goto send;
566 	}
567 
568 	/*
569 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
570 	 * is also a catch-all for the retransmit timer timeout case.
571 	 */
572 	if (tp->t_flags & TF_ACKNOW)
573 		goto send;
574 	if ((flags & TH_RST) ||
575 	    ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
576 		goto send;
577 	if (SEQ_GT(tp->snd_up, tp->snd_una))
578 		goto send;
579 	/*
580 	 * If our state indicates that FIN should be sent
581 	 * and we have not yet done so, then we need to send.
582 	 */
583 	if (flags & TH_FIN &&
584 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
585 		goto send;
586 	/*
587 	 * In SACK, it is possible for tcp_output to fail to send a segment
588 	 * after the retransmission timer has been turned off.  Make sure
589 	 * that the retransmission timer is set.
590 	 */
591 	if ((tp->t_flags & TF_SACK_PERMIT) &&
592 	    SEQ_GT(tp->snd_max, tp->snd_una) &&
593 	    !tcp_timer_active(tp, TT_REXMT) &&
594 	    !tcp_timer_active(tp, TT_PERSIST)) {
595 		tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
596 		goto just_return;
597 	}
598 	/*
599 	 * TCP window updates are not reliable, rather a polling protocol
600 	 * using ``persist'' packets is used to insure receipt of window
601 	 * updates.  The three ``states'' for the output side are:
602 	 *	idle			not doing retransmits or persists
603 	 *	persisting		to move a small or zero window
604 	 *	(re)transmitting	and thereby not persisting
605 	 *
606 	 * tcp_timer_active(tp, TT_PERSIST)
607 	 *	is true when we are in persist state.
608 	 * (tp->t_flags & TF_FORCEDATA)
609 	 *	is set when we are called to send a persist packet.
610 	 * tcp_timer_active(tp, TT_REXMT)
611 	 *	is set when we are retransmitting
612 	 * The output side is idle when both timers are zero.
613 	 *
614 	 * If send window is too small, there is data to transmit, and no
615 	 * retransmit or persist is pending, then go to persist state.
616 	 * If nothing happens soon, send when timer expires:
617 	 * if window is nonzero, transmit what we can,
618 	 * otherwise force out a byte.
619 	 */
620 	if (so->so_snd.sb_cc && !tcp_timer_active(tp, TT_REXMT) &&
621 	    !tcp_timer_active(tp, TT_PERSIST)) {
622 		tp->t_rxtshift = 0;
623 		tcp_setpersist(tp);
624 	}
625 
626 	/*
627 	 * No reason to send a segment, just return.
628 	 */
629 just_return:
630 	SOCKBUF_UNLOCK(&so->so_snd);
631 	return (0);
632 
633 send:
634 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
635 	/*
636 	 * Before ESTABLISHED, force sending of initial options
637 	 * unless TCP set not to do any options.
638 	 * NOTE: we assume that the IP/TCP header plus TCP options
639 	 * always fit in a single mbuf, leaving room for a maximum
640 	 * link header, i.e.
641 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
642 	 */
643 	optlen = 0;
644 #ifdef INET6
645 	if (isipv6)
646 		hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
647 	else
648 #endif
649 	hdrlen = sizeof (struct tcpiphdr);
650 
651 	/*
652 	 * Compute options for segment.
653 	 * We only have to care about SYN and established connection
654 	 * segments.  Options for SYN-ACK segments are handled in TCP
655 	 * syncache.
656 	 */
657 	if ((tp->t_flags & TF_NOOPT) == 0) {
658 		to.to_flags = 0;
659 		/* Maximum segment size. */
660 		if (flags & TH_SYN) {
661 			tp->snd_nxt = tp->iss;
662 			to.to_mss = tcp_mssopt(&tp->t_inpcb->inp_inc);
663 			to.to_flags |= TOF_MSS;
664 		}
665 		/* Window scaling. */
666 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
667 			to.to_wscale = tp->request_r_scale;
668 			to.to_flags |= TOF_SCALE;
669 		}
670 		/* Timestamps. */
671 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
672 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
673 			to.to_tsval = ticks + tp->ts_offset;
674 			to.to_tsecr = tp->ts_recent;
675 			to.to_flags |= TOF_TS;
676 			/* Set receive buffer autosizing timestamp. */
677 			if (tp->rfbuf_ts == 0 &&
678 			    (so->so_rcv.sb_flags & SB_AUTOSIZE))
679 				tp->rfbuf_ts = ticks;
680 		}
681 		/* Selective ACK's. */
682 		if (tp->t_flags & TF_SACK_PERMIT) {
683 			if (flags & TH_SYN)
684 				to.to_flags |= TOF_SACKPERM;
685 			else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
686 			    (tp->t_flags & TF_SACK_PERMIT) &&
687 			    tp->rcv_numsacks > 0) {
688 				to.to_flags |= TOF_SACK;
689 				to.to_nsacks = tp->rcv_numsacks;
690 				to.to_sacks = (u_char *)tp->sackblks;
691 			}
692 		}
693 #ifdef TCP_SIGNATURE
694 		/* TCP-MD5 (RFC2385). */
695 		if (tp->t_flags & TF_SIGNATURE)
696 			to.to_flags |= TOF_SIGNATURE;
697 #endif /* TCP_SIGNATURE */
698 
699 		/* Processing the options. */
700 		hdrlen += optlen = tcp_addoptions(&to, opt);
701 	}
702 
703 #ifdef INET6
704 	if (isipv6)
705 		ipoptlen = ip6_optlen(tp->t_inpcb);
706 	else
707 #endif
708 	if (tp->t_inpcb->inp_options)
709 		ipoptlen = tp->t_inpcb->inp_options->m_len -
710 				offsetof(struct ipoption, ipopt_list);
711 	else
712 		ipoptlen = 0;
713 #ifdef IPSEC
714 	ipoptlen += ipsec_optlen;
715 #endif
716 
717 	/*
718 	 * Adjust data length if insertion of options will
719 	 * bump the packet length beyond the t_maxopd length.
720 	 * Clear the FIN bit because we cut off the tail of
721 	 * the segment.
722 	 *
723 	 * When doing TSO limit a burst to TCP_MAXWIN minus the
724 	 * IP, TCP and Options length to keep ip->ip_len from
725 	 * overflowing.  Prevent the last segment from being
726 	 * fractional thus making them all equal sized and set
727 	 * the flag to continue sending.  TSO is disabled when
728 	 * IP options or IPSEC are present.
729 	 */
730 	if (len + optlen + ipoptlen > tp->t_maxopd) {
731 		flags &= ~TH_FIN;
732 		if (tso) {
733 			if (len > TCP_MAXWIN - hdrlen - optlen) {
734 				len = TCP_MAXWIN - hdrlen - optlen;
735 				len = len - (len % (tp->t_maxopd - optlen));
736 				sendalot = 1;
737 			} else if (tp->t_flags & TF_NEEDFIN)
738 				sendalot = 1;
739 		} else {
740 			len = tp->t_maxopd - optlen - ipoptlen;
741 			sendalot = 1;
742 		}
743 	}
744 
745 /*#ifdef DIAGNOSTIC*/
746 #ifdef INET6
747 	if (max_linkhdr + hdrlen > MCLBYTES)
748 #else
749 	if (max_linkhdr + hdrlen > MHLEN)
750 #endif
751 		panic("tcphdr too big");
752 /*#endif*/
753 
754 	/*
755 	 * This KASSERT is here to catch edge cases at a well defined place.
756 	 * Before, those had triggered (random) panic conditions further down.
757 	 */
758 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
759 
760 	/*
761 	 * Grab a header mbuf, attaching a copy of data to
762 	 * be transmitted, and initialize the header from
763 	 * the template for sends on this connection.
764 	 */
765 	if (len) {
766 		struct mbuf *mb;
767 		u_int moff;
768 
769 		if ((tp->t_flags & TF_FORCEDATA) && len == 1)
770 			TCPSTAT_INC(tcps_sndprobe);
771 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
772 			TCPSTAT_INC(tcps_sndrexmitpack);
773 			TCPSTAT_ADD(tcps_sndrexmitbyte, len);
774 		} else {
775 			TCPSTAT_INC(tcps_sndpack);
776 			TCPSTAT_ADD(tcps_sndbyte, len);
777 		}
778 #ifdef notyet
779 		if ((m = m_copypack(so->so_snd.sb_mb, off,
780 		    (int)len, max_linkhdr + hdrlen)) == 0) {
781 			SOCKBUF_UNLOCK(&so->so_snd);
782 			error = ENOBUFS;
783 			goto out;
784 		}
785 		/*
786 		 * m_copypack left space for our hdr; use it.
787 		 */
788 		m->m_len += hdrlen;
789 		m->m_data -= hdrlen;
790 #else
791 		MGETHDR(m, M_DONTWAIT, MT_DATA);
792 		if (m == NULL) {
793 			SOCKBUF_UNLOCK(&so->so_snd);
794 			error = ENOBUFS;
795 			goto out;
796 		}
797 #ifdef INET6
798 		if (MHLEN < hdrlen + max_linkhdr) {
799 			MCLGET(m, M_DONTWAIT);
800 			if ((m->m_flags & M_EXT) == 0) {
801 				SOCKBUF_UNLOCK(&so->so_snd);
802 				m_freem(m);
803 				error = ENOBUFS;
804 				goto out;
805 			}
806 		}
807 #endif
808 		m->m_data += max_linkhdr;
809 		m->m_len = hdrlen;
810 
811 		/*
812 		 * Start the m_copy functions from the closest mbuf
813 		 * to the offset in the socket buffer chain.
814 		 */
815 		mb = sbsndptr(&so->so_snd, off, len, &moff);
816 
817 		if (len <= MHLEN - hdrlen - max_linkhdr) {
818 			m_copydata(mb, moff, (int)len,
819 			    mtod(m, caddr_t) + hdrlen);
820 			m->m_len += len;
821 		} else {
822 			m->m_next = m_copy(mb, moff, (int)len);
823 			if (m->m_next == NULL) {
824 				SOCKBUF_UNLOCK(&so->so_snd);
825 				(void) m_free(m);
826 				error = ENOBUFS;
827 				goto out;
828 			}
829 		}
830 #endif
831 		/*
832 		 * If we're sending everything we've got, set PUSH.
833 		 * (This will keep happy those implementations which only
834 		 * give data to the user when a buffer fills or
835 		 * a PUSH comes in.)
836 		 */
837 		if (off + len == so->so_snd.sb_cc)
838 			flags |= TH_PUSH;
839 		SOCKBUF_UNLOCK(&so->so_snd);
840 	} else {
841 		SOCKBUF_UNLOCK(&so->so_snd);
842 		if (tp->t_flags & TF_ACKNOW)
843 			TCPSTAT_INC(tcps_sndacks);
844 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
845 			TCPSTAT_INC(tcps_sndctrl);
846 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
847 			TCPSTAT_INC(tcps_sndurg);
848 		else
849 			TCPSTAT_INC(tcps_sndwinup);
850 
851 		MGETHDR(m, M_DONTWAIT, MT_DATA);
852 		if (m == NULL) {
853 			error = ENOBUFS;
854 			goto out;
855 		}
856 #ifdef INET6
857 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
858 		    MHLEN >= hdrlen) {
859 			MH_ALIGN(m, hdrlen);
860 		} else
861 #endif
862 		m->m_data += max_linkhdr;
863 		m->m_len = hdrlen;
864 	}
865 	SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
866 	m->m_pkthdr.rcvif = (struct ifnet *)0;
867 #ifdef MAC
868 	mac_inpcb_create_mbuf(tp->t_inpcb, m);
869 #endif
870 #ifdef INET6
871 	if (isipv6) {
872 		ip6 = mtod(m, struct ip6_hdr *);
873 		th = (struct tcphdr *)(ip6 + 1);
874 		tcpip_fillheaders(tp->t_inpcb, ip6, th);
875 	} else
876 #endif /* INET6 */
877 	{
878 		ip = mtod(m, struct ip *);
879 		ipov = (struct ipovly *)ip;
880 		th = (struct tcphdr *)(ip + 1);
881 		tcpip_fillheaders(tp->t_inpcb, ip, th);
882 	}
883 
884 	/*
885 	 * Fill in fields, remembering maximum advertised
886 	 * window for use in delaying messages about window sizes.
887 	 * If resending a FIN, be sure not to use a new sequence number.
888 	 */
889 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
890 	    tp->snd_nxt == tp->snd_max)
891 		tp->snd_nxt--;
892 	/*
893 	 * If we are starting a connection, send ECN setup
894 	 * SYN packet. If we are on a retransmit, we may
895 	 * resend those bits a number of times as per
896 	 * RFC 3168.
897 	 */
898 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn) {
899 		if (tp->t_rxtshift >= 1) {
900 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
901 				flags |= TH_ECE|TH_CWR;
902 		} else
903 			flags |= TH_ECE|TH_CWR;
904 	}
905 
906 	if (tp->t_state == TCPS_ESTABLISHED &&
907 	    (tp->t_flags & TF_ECN_PERMIT)) {
908 		/*
909 		 * If the peer has ECN, mark data packets with
910 		 * ECN capable transmission (ECT).
911 		 * Ignore pure ack packets, retransmissions and window probes.
912 		 */
913 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
914 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
915 #ifdef INET6
916 			if (isipv6)
917 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
918 			else
919 #endif
920 				ip->ip_tos |= IPTOS_ECN_ECT0;
921 			TCPSTAT_INC(tcps_ecn_ect0);
922 		}
923 
924 		/*
925 		 * Reply with proper ECN notifications.
926 		 */
927 		if (tp->t_flags & TF_ECN_SND_CWR) {
928 			flags |= TH_CWR;
929 			tp->t_flags &= ~TF_ECN_SND_CWR;
930 		}
931 		if (tp->t_flags & TF_ECN_SND_ECE)
932 			flags |= TH_ECE;
933 	}
934 
935 	/*
936 	 * If we are doing retransmissions, then snd_nxt will
937 	 * not reflect the first unsent octet.  For ACK only
938 	 * packets, we do not want the sequence number of the
939 	 * retransmitted packet, we want the sequence number
940 	 * of the next unsent octet.  So, if there is no data
941 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
942 	 * when filling in ti_seq.  But if we are in persist
943 	 * state, snd_max might reflect one byte beyond the
944 	 * right edge of the window, so use snd_nxt in that
945 	 * case, since we know we aren't doing a retransmission.
946 	 * (retransmit and persist are mutually exclusive...)
947 	 */
948 	if (sack_rxmit == 0) {
949 		if (len || (flags & (TH_SYN|TH_FIN)) ||
950 		    tcp_timer_active(tp, TT_PERSIST))
951 			th->th_seq = htonl(tp->snd_nxt);
952 		else
953 			th->th_seq = htonl(tp->snd_max);
954 	} else {
955 		th->th_seq = htonl(p->rxmit);
956 		p->rxmit += len;
957 		tp->sackhint.sack_bytes_rexmit += len;
958 	}
959 	th->th_ack = htonl(tp->rcv_nxt);
960 	if (optlen) {
961 		bcopy(opt, th + 1, optlen);
962 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
963 	}
964 	th->th_flags = flags;
965 	/*
966 	 * Calculate receive window.  Don't shrink window,
967 	 * but avoid silly window syndrome.
968 	 */
969 	if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
970 	    recwin < (long)tp->t_maxseg)
971 		recwin = 0;
972 	if (recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
973 		recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
974 	if (recwin > (long)TCP_MAXWIN << tp->rcv_scale)
975 		recwin = (long)TCP_MAXWIN << tp->rcv_scale;
976 
977 	/*
978 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
979 	 * or <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK>
980 	 * case is handled in syncache.
981 	 */
982 	if (flags & TH_SYN)
983 		th->th_win = htons((u_short)
984 				(min(sbspace(&so->so_rcv), TCP_MAXWIN)));
985 	else
986 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
987 
988 	/*
989 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
990 	 * a 0 window.  This may cause the remote transmitter to stall.  This
991 	 * flag tells soreceive() to disable delayed acknowledgements when
992 	 * draining the buffer.  This can occur if the receiver is attempting
993 	 * to read more data than can be buffered prior to transmitting on
994 	 * the connection.
995 	 */
996 	if (recwin == 0)
997 		tp->t_flags |= TF_RXWIN0SENT;
998 	else
999 		tp->t_flags &= ~TF_RXWIN0SENT;
1000 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1001 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
1002 		th->th_flags |= TH_URG;
1003 	} else
1004 		/*
1005 		 * If no urgent pointer to send, then we pull
1006 		 * the urgent pointer to the left edge of the send window
1007 		 * so that it doesn't drift into the send window on sequence
1008 		 * number wraparound.
1009 		 */
1010 		tp->snd_up = tp->snd_una;		/* drag it along */
1011 
1012 #ifdef TCP_SIGNATURE
1013 	if (tp->t_flags & TF_SIGNATURE) {
1014 		int sigoff = to.to_signature - opt;
1015 		tcp_signature_compute(m, 0, len, optlen,
1016 		    (u_char *)(th + 1) + sigoff, IPSEC_DIR_OUTBOUND);
1017 	}
1018 #endif
1019 
1020 	/*
1021 	 * Put TCP length in extended header, and then
1022 	 * checksum extended header and data.
1023 	 */
1024 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
1025 #ifdef INET6
1026 	if (isipv6)
1027 		/*
1028 		 * ip6_plen is not need to be filled now, and will be filled
1029 		 * in ip6_output.
1030 		 */
1031 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
1032 				       sizeof(struct tcphdr) + optlen + len);
1033 	else
1034 #endif /* INET6 */
1035 	{
1036 		m->m_pkthdr.csum_flags = CSUM_TCP;
1037 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1038 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1039 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP + len + optlen));
1040 
1041 		/* IP version must be set here for ipv4/ipv6 checking later */
1042 		KASSERT(ip->ip_v == IPVERSION,
1043 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
1044 	}
1045 
1046 	/*
1047 	 * Enable TSO and specify the size of the segments.
1048 	 * The TCP pseudo header checksum is always provided.
1049 	 * XXX: Fixme: This is currently not the case for IPv6.
1050 	 */
1051 	if (tso) {
1052 		m->m_pkthdr.csum_flags = CSUM_TSO;
1053 		m->m_pkthdr.tso_segsz = tp->t_maxopd - optlen;
1054 	}
1055 
1056 	/*
1057 	 * In transmit state, time the transmission and arrange for
1058 	 * the retransmit.  In persist state, just set snd_max.
1059 	 */
1060 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
1061 	    !tcp_timer_active(tp, TT_PERSIST)) {
1062 		tcp_seq startseq = tp->snd_nxt;
1063 
1064 		/*
1065 		 * Advance snd_nxt over sequence space of this segment.
1066 		 */
1067 		if (flags & (TH_SYN|TH_FIN)) {
1068 			if (flags & TH_SYN)
1069 				tp->snd_nxt++;
1070 			if (flags & TH_FIN) {
1071 				tp->snd_nxt++;
1072 				tp->t_flags |= TF_SENTFIN;
1073 			}
1074 		}
1075 		if (sack_rxmit)
1076 			goto timer;
1077 		tp->snd_nxt += len;
1078 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1079 			tp->snd_max = tp->snd_nxt;
1080 			/*
1081 			 * Time this transmission if not a retransmission and
1082 			 * not currently timing anything.
1083 			 */
1084 			if (tp->t_rtttime == 0) {
1085 				tp->t_rtttime = ticks;
1086 				tp->t_rtseq = startseq;
1087 				TCPSTAT_INC(tcps_segstimed);
1088 			}
1089 		}
1090 
1091 		/*
1092 		 * Set retransmit timer if not currently set,
1093 		 * and not doing a pure ack or a keep-alive probe.
1094 		 * Initial value for retransmit timer is smoothed
1095 		 * round-trip time + 2 * round-trip time variance.
1096 		 * Initialize shift counter which is used for backoff
1097 		 * of retransmit time.
1098 		 */
1099 timer:
1100 		if (!tcp_timer_active(tp, TT_REXMT) &&
1101 		    ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
1102 		     (tp->snd_nxt != tp->snd_una))) {
1103 			if (tcp_timer_active(tp, TT_PERSIST)) {
1104 				tcp_timer_activate(tp, TT_PERSIST, 0);
1105 				tp->t_rxtshift = 0;
1106 			}
1107 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1108 		}
1109 	} else {
1110 		/*
1111 		 * Persist case, update snd_max but since we are in
1112 		 * persist mode (no window) we do not update snd_nxt.
1113 		 */
1114 		int xlen = len;
1115 		if (flags & TH_SYN)
1116 			++xlen;
1117 		if (flags & TH_FIN) {
1118 			++xlen;
1119 			tp->t_flags |= TF_SENTFIN;
1120 		}
1121 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1122 			tp->snd_max = tp->snd_nxt + len;
1123 	}
1124 
1125 #ifdef TCPDEBUG
1126 	/*
1127 	 * Trace.
1128 	 */
1129 	if (so->so_options & SO_DEBUG) {
1130 		u_short save = 0;
1131 #ifdef INET6
1132 		if (!isipv6)
1133 #endif
1134 		{
1135 			save = ipov->ih_len;
1136 			ipov->ih_len = htons(m->m_pkthdr.len /* - hdrlen + (th->th_off << 2) */);
1137 		}
1138 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
1139 #ifdef INET6
1140 		if (!isipv6)
1141 #endif
1142 		ipov->ih_len = save;
1143 	}
1144 #endif
1145 
1146 	/*
1147 	 * Fill in IP length and desired time to live and
1148 	 * send to IP level.  There should be a better way
1149 	 * to handle ttl and tos; we could keep them in
1150 	 * the template, but need a way to checksum without them.
1151 	 */
1152 	/*
1153 	 * m->m_pkthdr.len should have been set before cksum calcuration,
1154 	 * because in6_cksum() need it.
1155 	 */
1156 #ifdef INET6
1157 	if (isipv6) {
1158 		/*
1159 		 * we separately set hoplimit for every segment, since the
1160 		 * user might want to change the value via setsockopt.
1161 		 * Also, desired default hop limit might be changed via
1162 		 * Neighbor Discovery.
1163 		 */
1164 		ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb, NULL);
1165 
1166 		/* TODO: IPv6 IP6TOS_ECT bit on */
1167 		error = ip6_output(m,
1168 			    tp->t_inpcb->in6p_outputopts, NULL,
1169 			    ((so->so_options & SO_DONTROUTE) ?
1170 			    IP_ROUTETOIF : 0), NULL, NULL, tp->t_inpcb);
1171 	} else
1172 #endif /* INET6 */
1173     {
1174 	ip->ip_len = m->m_pkthdr.len;
1175 #ifdef INET6
1176 	if (tp->t_inpcb->inp_vflag & INP_IPV6PROTO)
1177 		ip->ip_ttl = in6_selecthlim(tp->t_inpcb, NULL);
1178 #endif /* INET6 */
1179 	/*
1180 	 * If we do path MTU discovery, then we set DF on every packet.
1181 	 * This might not be the best thing to do according to RFC3390
1182 	 * Section 2. However the tcp hostcache migitates the problem
1183 	 * so it affects only the first tcp connection with a host.
1184 	 */
1185 	if (V_path_mtu_discovery)
1186 		ip->ip_off |= IP_DF;
1187 
1188 	error = ip_output(m, tp->t_inpcb->inp_options, NULL,
1189 	    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
1190 	    tp->t_inpcb);
1191     }
1192 	if (error) {
1193 
1194 		/*
1195 		 * We know that the packet was lost, so back out the
1196 		 * sequence number advance, if any.
1197 		 *
1198 		 * If the error is EPERM the packet got blocked by the
1199 		 * local firewall.  Normally we should terminate the
1200 		 * connection but the blocking may have been spurious
1201 		 * due to a firewall reconfiguration cycle.  So we treat
1202 		 * it like a packet loss and let the retransmit timer and
1203 		 * timeouts do their work over time.
1204 		 * XXX: It is a POLA question whether calling tcp_drop right
1205 		 * away would be the really correct behavior instead.
1206 		 */
1207 		if (((tp->t_flags & TF_FORCEDATA) == 0 ||
1208 		    !tcp_timer_active(tp, TT_PERSIST)) &&
1209 		    ((flags & TH_SYN) == 0) &&
1210 		    (error != EPERM)) {
1211 			if (sack_rxmit) {
1212 				p->rxmit -= len;
1213 				tp->sackhint.sack_bytes_rexmit -= len;
1214 				KASSERT(tp->sackhint.sack_bytes_rexmit >= 0,
1215 				    ("sackhint bytes rtx >= 0"));
1216 			} else
1217 				tp->snd_nxt -= len;
1218 		}
1219 out:
1220 		SOCKBUF_UNLOCK_ASSERT(&so->so_snd);	/* Check gotos. */
1221 		switch (error) {
1222 		case EPERM:
1223 			tp->t_softerror = error;
1224 			return (error);
1225 		case ENOBUFS:
1226 	                if (!tcp_timer_active(tp, TT_REXMT) &&
1227 			    !tcp_timer_active(tp, TT_PERSIST))
1228 	                        tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1229 			tp->snd_cwnd = tp->t_maxseg;
1230 			return (0);
1231 		case EMSGSIZE:
1232 			/*
1233 			 * For some reason the interface we used initially
1234 			 * to send segments changed to another or lowered
1235 			 * its MTU.
1236 			 *
1237 			 * tcp_mtudisc() will find out the new MTU and as
1238 			 * its last action, initiate retransmission, so it
1239 			 * is important to not do so here.
1240 			 *
1241 			 * If TSO was active we either got an interface
1242 			 * without TSO capabilits or TSO was turned off.
1243 			 * Disable it for this connection as too and
1244 			 * immediatly retry with MSS sized segments generated
1245 			 * by this function.
1246 			 */
1247 			if (tso)
1248 				tp->t_flags &= ~TF_TSO;
1249 			tcp_mtudisc(tp->t_inpcb, 0);
1250 			return (0);
1251 		case EHOSTDOWN:
1252 		case EHOSTUNREACH:
1253 		case ENETDOWN:
1254 		case ENETUNREACH:
1255 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
1256 				tp->t_softerror = error;
1257 				return (0);
1258 			}
1259 			/* FALLTHROUGH */
1260 		default:
1261 			return (error);
1262 		}
1263 	}
1264 	TCPSTAT_INC(tcps_sndtotal);
1265 
1266 	/*
1267 	 * Data sent (as far as we can tell).
1268 	 * If this advertises a larger window than any other segment,
1269 	 * then remember the size of the advertised window.
1270 	 * Any pending ACK has now been sent.
1271 	 */
1272 	if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
1273 		tp->rcv_adv = tp->rcv_nxt + recwin;
1274 	tp->last_ack_sent = tp->rcv_nxt;
1275 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
1276 	if (tcp_timer_active(tp, TT_DELACK))
1277 		tcp_timer_activate(tp, TT_DELACK, 0);
1278 #if 0
1279 	/*
1280 	 * This completely breaks TCP if newreno is turned on.  What happens
1281 	 * is that if delayed-acks are turned on on the receiver, this code
1282 	 * on the transmitter effectively destroys the TCP window, forcing
1283 	 * it to four packets (1.5Kx4 = 6K window).
1284 	 */
1285 	if (sendalot && (!V_tcp_do_newreno || --maxburst))
1286 		goto again;
1287 #endif
1288 	if (sendalot)
1289 		goto again;
1290 	return (0);
1291 }
1292 
1293 void
1294 tcp_setpersist(struct tcpcb *tp)
1295 {
1296 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1297 	int tt;
1298 
1299 	if (tcp_timer_active(tp, TT_REXMT))
1300 		panic("tcp_setpersist: retransmit pending");
1301 	/*
1302 	 * Start/restart persistance timer.
1303 	 */
1304 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
1305 		      TCPTV_PERSMIN, TCPTV_PERSMAX);
1306 	tcp_timer_activate(tp, TT_PERSIST, tt);
1307 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1308 		tp->t_rxtshift++;
1309 }
1310 
1311 /*
1312  * Insert TCP options according to the supplied parameters to the place
1313  * optp in a consistent way.  Can handle unaligned destinations.
1314  *
1315  * The order of the option processing is crucial for optimal packing and
1316  * alignment for the scarce option space.
1317  *
1318  * The optimal order for a SYN/SYN-ACK segment is:
1319  *   MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) +
1320  *   Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40.
1321  *
1322  * The SACK options should be last.  SACK blocks consume 8*n+2 bytes.
1323  * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks).
1324  * At minimum we need 10 bytes (to generate 1 SACK block).  If both
1325  * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present,
1326  * we only have 10 bytes for SACK options (40 - (12 + 18)).
1327  */
1328 int
1329 tcp_addoptions(struct tcpopt *to, u_char *optp)
1330 {
1331 	INIT_VNET_INET(curvnet);
1332 	u_int mask, optlen = 0;
1333 
1334 	for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) {
1335 		if ((to->to_flags & mask) != mask)
1336 			continue;
1337 		if (optlen == TCP_MAXOLEN)
1338 			break;
1339 		switch (to->to_flags & mask) {
1340 		case TOF_MSS:
1341 			while (optlen % 4) {
1342 				optlen += TCPOLEN_NOP;
1343 				*optp++ = TCPOPT_NOP;
1344 			}
1345 			if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG)
1346 				continue;
1347 			optlen += TCPOLEN_MAXSEG;
1348 			*optp++ = TCPOPT_MAXSEG;
1349 			*optp++ = TCPOLEN_MAXSEG;
1350 			to->to_mss = htons(to->to_mss);
1351 			bcopy((u_char *)&to->to_mss, optp, sizeof(to->to_mss));
1352 			optp += sizeof(to->to_mss);
1353 			break;
1354 		case TOF_SCALE:
1355 			while (!optlen || optlen % 2 != 1) {
1356 				optlen += TCPOLEN_NOP;
1357 				*optp++ = TCPOPT_NOP;
1358 			}
1359 			if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW)
1360 				continue;
1361 			optlen += TCPOLEN_WINDOW;
1362 			*optp++ = TCPOPT_WINDOW;
1363 			*optp++ = TCPOLEN_WINDOW;
1364 			*optp++ = to->to_wscale;
1365 			break;
1366 		case TOF_SACKPERM:
1367 			while (optlen % 2) {
1368 				optlen += TCPOLEN_NOP;
1369 				*optp++ = TCPOPT_NOP;
1370 			}
1371 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED)
1372 				continue;
1373 			optlen += TCPOLEN_SACK_PERMITTED;
1374 			*optp++ = TCPOPT_SACK_PERMITTED;
1375 			*optp++ = TCPOLEN_SACK_PERMITTED;
1376 			break;
1377 		case TOF_TS:
1378 			while (!optlen || optlen % 4 != 2) {
1379 				optlen += TCPOLEN_NOP;
1380 				*optp++ = TCPOPT_NOP;
1381 			}
1382 			if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP)
1383 				continue;
1384 			optlen += TCPOLEN_TIMESTAMP;
1385 			*optp++ = TCPOPT_TIMESTAMP;
1386 			*optp++ = TCPOLEN_TIMESTAMP;
1387 			to->to_tsval = htonl(to->to_tsval);
1388 			to->to_tsecr = htonl(to->to_tsecr);
1389 			bcopy((u_char *)&to->to_tsval, optp, sizeof(to->to_tsval));
1390 			optp += sizeof(to->to_tsval);
1391 			bcopy((u_char *)&to->to_tsecr, optp, sizeof(to->to_tsecr));
1392 			optp += sizeof(to->to_tsecr);
1393 			break;
1394 		case TOF_SIGNATURE:
1395 			{
1396 			int siglen = TCPOLEN_SIGNATURE - 2;
1397 
1398 			while (!optlen || optlen % 4 != 2) {
1399 				optlen += TCPOLEN_NOP;
1400 				*optp++ = TCPOPT_NOP;
1401 			}
1402 			if (TCP_MAXOLEN - optlen < TCPOLEN_SIGNATURE)
1403 				continue;
1404 			optlen += TCPOLEN_SIGNATURE;
1405 			*optp++ = TCPOPT_SIGNATURE;
1406 			*optp++ = TCPOLEN_SIGNATURE;
1407 			to->to_signature = optp;
1408 			while (siglen--)
1409 				 *optp++ = 0;
1410 			break;
1411 			}
1412 		case TOF_SACK:
1413 			{
1414 			int sackblks = 0;
1415 			struct sackblk *sack = (struct sackblk *)to->to_sacks;
1416 			tcp_seq sack_seq;
1417 
1418 			while (!optlen || optlen % 4 != 2) {
1419 				optlen += TCPOLEN_NOP;
1420 				*optp++ = TCPOPT_NOP;
1421 			}
1422 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK)
1423 				continue;
1424 			optlen += TCPOLEN_SACKHDR;
1425 			*optp++ = TCPOPT_SACK;
1426 			sackblks = min(to->to_nsacks,
1427 					(TCP_MAXOLEN - optlen) / TCPOLEN_SACK);
1428 			*optp++ = TCPOLEN_SACKHDR + sackblks * TCPOLEN_SACK;
1429 			while (sackblks--) {
1430 				sack_seq = htonl(sack->start);
1431 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
1432 				optp += sizeof(sack_seq);
1433 				sack_seq = htonl(sack->end);
1434 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
1435 				optp += sizeof(sack_seq);
1436 				optlen += TCPOLEN_SACK;
1437 				sack++;
1438 			}
1439 			TCPSTAT_INC(tcps_sack_send_blocks);
1440 			break;
1441 			}
1442 		default:
1443 			panic("%s: unknown TCP option type", __func__);
1444 			break;
1445 		}
1446 	}
1447 
1448 	/* Terminate and pad TCP options to a 4 byte boundary. */
1449 	if (optlen % 4) {
1450 		optlen += TCPOLEN_EOL;
1451 		*optp++ = TCPOPT_EOL;
1452 	}
1453 	/*
1454 	 * According to RFC 793 (STD0007):
1455 	 *   "The content of the header beyond the End-of-Option option
1456 	 *    must be header padding (i.e., zero)."
1457 	 *   and later: "The padding is composed of zeros."
1458 	 */
1459 	while (optlen % 4) {
1460 		optlen += TCPOLEN_PAD;
1461 		*optp++ = TCPOPT_PAD;
1462 	}
1463 
1464 	KASSERT(optlen <= TCP_MAXOLEN, ("%s: TCP options too long", __func__));
1465 	return (optlen);
1466 }
1467