xref: /dflybsd-src/sys/netinet/tcp_output.c (revision 14343ad3b815bafa1bcec3656de2d614fcc75bec)
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
67  * $FreeBSD: src/sys/netinet/tcp_output.c,v 1.39.2.20 2003/01/29 22:45:36 hsu Exp $
68  * $DragonFly: src/sys/netinet/tcp_output.c,v 1.34 2007/04/22 01:13:14 dillon Exp $
69  */
70 
71 #include "opt_inet.h"
72 #include "opt_inet6.h"
73 #include "opt_ipsec.h"
74 #include "opt_tcpdebug.h"
75 
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/kernel.h>
79 #include <sys/sysctl.h>
80 #include <sys/mbuf.h>
81 #include <sys/domain.h>
82 #include <sys/protosw.h>
83 #include <sys/socket.h>
84 #include <sys/socketvar.h>
85 #include <sys/in_cksum.h>
86 #include <sys/thread.h>
87 #include <sys/globaldata.h>
88 
89 #include <net/route.h>
90 
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet/ip_var.h>
96 #include <netinet6/in6_pcb.h>
97 #include <netinet/ip6.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet/tcp.h>
100 #define	TCPOUTFLAGS
101 #include <netinet/tcp_fsm.h>
102 #include <netinet/tcp_seq.h>
103 #include <netinet/tcp_timer.h>
104 #include <netinet/tcp_timer2.h>
105 #include <netinet/tcp_var.h>
106 #include <netinet/tcpip.h>
107 #ifdef TCPDEBUG
108 #include <netinet/tcp_debug.h>
109 #endif
110 
111 #ifdef IPSEC
112 #include <netinet6/ipsec.h>
113 #endif /*IPSEC*/
114 
115 #ifdef FAST_IPSEC
116 #include <netproto/ipsec/ipsec.h>
117 #define	IPSEC
118 #endif /*FAST_IPSEC*/
119 
120 #ifdef notyet
121 extern struct mbuf *m_copypack();
122 #endif
123 
124 int path_mtu_discovery = 0;
125 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_RW,
126 	&path_mtu_discovery, 1, "Enable Path MTU Discovery");
127 
128 static int avoid_pure_win_update = 1;
129 SYSCTL_INT(_net_inet_tcp, OID_AUTO, avoid_pure_win_update, CTLFLAG_RW,
130 	&avoid_pure_win_update, 1, "Avoid pure window updates when possible");
131 
132 int tcp_do_autosndbuf = 1;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto, CTLFLAG_RW,
134     &tcp_do_autosndbuf, 0, "Enable automatic send buffer sizing");
135 
136 int tcp_autosndbuf_inc = 8*1024;
137 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_inc, CTLFLAG_RW,
138     &tcp_autosndbuf_inc, 0, "Incrementor step size of automatic send buffer");
139 
140 int tcp_autosndbuf_max = 2*1024*1024;
141 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_max, CTLFLAG_RW,
142     &tcp_autosndbuf_max, 0, "Max size of automatic send buffer");
143 
144 /*
145  * Tcp output routine: figure out what should be sent and send it.
146  */
147 int
148 tcp_output(struct tcpcb *tp)
149 {
150 	struct inpcb * const inp = tp->t_inpcb;
151 	struct socket *so = inp->inp_socket;
152 	long len, recvwin, sendwin;
153 	int nsacked = 0;
154 	int off, flags, error;
155 #ifdef TCP_SIGNATURE
156 	int sigoff = 0;
157 #endif
158 	struct mbuf *m;
159 	struct ip *ip = NULL;
160 	struct ipovly *ipov = NULL;
161 	struct tcphdr *th;
162 	u_char opt[TCP_MAXOLEN];
163 	unsigned int ipoptlen, optlen, hdrlen;
164 	int idle;
165 	boolean_t sendalot;
166 	struct ip6_hdr *ip6 = NULL;
167 #ifdef INET6
168 	const boolean_t isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
169 #else
170 	const boolean_t isipv6 = FALSE;
171 #endif
172 
173 	/*
174 	 * Determine length of data that should be transmitted,
175 	 * and flags that will be used.
176 	 * If there is some data or critical controls (SYN, RST)
177 	 * to send, then transmit; otherwise, investigate further.
178 	 */
179 
180 	/*
181 	 * If we have been idle for a while, the send congestion window
182 	 * could be no longer representative of the current state of the link.
183 	 * So unless we are expecting more acks to come in, slow-start from
184 	 * scratch to re-determine the send congestion window.
185 	 */
186 	if (tp->snd_max == tp->snd_una &&
187 	    (ticks - tp->t_rcvtime) >= tp->t_rxtcur) {
188 		if (tcp_do_rfc3390) {
189 			int initial_cwnd =
190 			    min(4 * tp->t_maxseg, max(2 * tp->t_maxseg, 4380));
191 
192 			tp->snd_cwnd = min(tp->snd_cwnd, initial_cwnd);
193 		} else {
194 			tp->snd_cwnd = tp->t_maxseg;
195 		}
196 		tp->snd_wacked = 0;
197 	}
198 
199 	/*
200 	 * Calculate whether the transmit stream was previously idle
201 	 * and adjust TF_LASTIDLE for the next time.
202 	 */
203 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
204 	if (idle && (tp->t_flags & TF_MORETOCOME))
205 		tp->t_flags |= TF_LASTIDLE;
206 	else
207 		tp->t_flags &= ~TF_LASTIDLE;
208 
209 	if (TCP_DO_SACK(tp) && tp->snd_nxt != tp->snd_max &&
210 	    !IN_FASTRECOVERY(tp))
211 		nsacked = tcp_sack_bytes_below(&tp->scb, tp->snd_nxt);
212 
213 again:
214 	/* Make use of SACK information when slow-starting after a RTO. */
215 	if (TCP_DO_SACK(tp) && tp->snd_nxt != tp->snd_max &&
216 	    !IN_FASTRECOVERY(tp)) {
217 		tcp_seq old_snd_nxt = tp->snd_nxt;
218 
219 		tcp_sack_skip_sacked(&tp->scb, &tp->snd_nxt);
220 		nsacked += tp->snd_nxt - old_snd_nxt;
221 	}
222 
223 	sendalot = FALSE;
224 	off = tp->snd_nxt - tp->snd_una;
225 	sendwin = min(tp->snd_wnd, tp->snd_cwnd + nsacked);
226 	sendwin = min(sendwin, tp->snd_bwnd);
227 
228 	flags = tcp_outflags[tp->t_state];
229 	/*
230 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
231 	 * state flags.
232 	 */
233 	if (tp->t_flags & TF_NEEDFIN)
234 		flags |= TH_FIN;
235 	if (tp->t_flags & TF_NEEDSYN)
236 		flags |= TH_SYN;
237 
238 	/*
239 	 * If in persist timeout with window of 0, send 1 byte.
240 	 * Otherwise, if window is small but nonzero
241 	 * and timer expired, we will send what we can
242 	 * and go to transmit state.
243 	 */
244 	if (tp->t_flags & TF_FORCE) {
245 		if (sendwin == 0) {
246 			/*
247 			 * If we still have some data to send, then
248 			 * clear the FIN bit.  Usually this would
249 			 * happen below when it realizes that we
250 			 * aren't sending all the data.  However,
251 			 * if we have exactly 1 byte of unsent data,
252 			 * then it won't clear the FIN bit below,
253 			 * and if we are in persist state, we wind
254 			 * up sending the packet without recording
255 			 * that we sent the FIN bit.
256 			 *
257 			 * We can't just blindly clear the FIN bit,
258 			 * because if we don't have any more data
259 			 * to send then the probe will be the FIN
260 			 * itself.
261 			 */
262 			if (off < so->so_snd.ssb_cc)
263 				flags &= ~TH_FIN;
264 			sendwin = 1;
265 		} else {
266 			tcp_callout_stop(tp, tp->tt_persist);
267 			tp->t_rxtshift = 0;
268 		}
269 	}
270 
271 	/*
272 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
273 	 * offset will be > 0 even if so_snd.ssb_cc is 0, resulting in
274 	 * a negative length.  This can also occur when TCP opens up
275 	 * its congestion window while receiving additional duplicate
276 	 * acks after fast-retransmit because TCP will reset snd_nxt
277 	 * to snd_max after the fast-retransmit.
278 	 *
279 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
280 	 * be set to snd_una, the offset will be 0, and the length may
281 	 * wind up 0.
282 	 */
283 	len = (long)ulmin(so->so_snd.ssb_cc, sendwin) - off;
284 
285 	/*
286 	 * Lop off SYN bit if it has already been sent.  However, if this
287 	 * is SYN-SENT state and if segment contains data, suppress sending
288 	 * segment (sending the segment would be an option if we still
289 	 * did TAO and the remote host supported it).
290 	 */
291 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
292 		flags &= ~TH_SYN;
293 		off--, len++;
294 		if (len > 0 && tp->t_state == TCPS_SYN_SENT)
295 			return 0;
296 	}
297 
298 	/*
299 	 * Be careful not to send data and/or FIN on SYN segments.
300 	 * This measure is needed to prevent interoperability problems
301 	 * with not fully conformant TCP implementations.
302 	 */
303 	if (flags & TH_SYN) {
304 		len = 0;
305 		flags &= ~TH_FIN;
306 	}
307 
308 	if (len < 0) {
309 		/*
310 		 * If FIN has been sent but not acked,
311 		 * but we haven't been called to retransmit,
312 		 * len will be < 0.  Otherwise, window shrank
313 		 * after we sent into it.  If window shrank to 0,
314 		 * cancel pending retransmit, pull snd_nxt back
315 		 * to (closed) window, and set the persist timer
316 		 * if it isn't already going.  If the window didn't
317 		 * close completely, just wait for an ACK.
318 		 */
319 		len = 0;
320 		if (sendwin == 0) {
321 			tcp_callout_stop(tp, tp->tt_rexmt);
322 			tp->t_rxtshift = 0;
323 			tp->snd_nxt = tp->snd_una;
324 			if (!tcp_callout_active(tp, tp->tt_persist))
325 				tcp_setpersist(tp);
326 		}
327 	}
328 
329 	KASSERT(len >= 0, ("%s: len < 0", __func__));
330 	/*
331 	 * Automatic sizing of send socket buffer.  Often the send buffer
332 	 * size is not optimally adjusted to the actual network conditions
333 	 * at hand (delay bandwidth product).  Setting the buffer size too
334 	 * small limits throughput on links with high bandwidth and high
335 	 * delay (eg. trans-continental/oceanic links).  Setting the
336 	 * buffer size too big consumes too much real kernel memory,
337 	 * especially with many connections on busy servers.
338 	 *
339 	 * The criteria to step up the send buffer one notch are:
340 	 *  1. receive window of remote host is larger than send buffer
341 	 *     (with a fudge factor of 5/4th);
342 	 *  2. send buffer is filled to 7/8th with data (so we actually
343 	 *     have data to make use of it);
344 	 *  3. send buffer fill has not hit maximal automatic size;
345 	 *  4. our send window (slow start and cogestion controlled) is
346 	 *     larger than sent but unacknowledged data in send buffer.
347 	 *
348 	 * The remote host receive window scaling factor may limit the
349 	 * growing of the send buffer before it reaches its allowed
350 	 * maximum.
351 	 *
352 	 * It scales directly with slow start or congestion window
353 	 * and does at most one step per received ACK.  This fast
354 	 * scaling has the drawback of growing the send buffer beyond
355 	 * what is strictly necessary to make full use of a given
356 	 * delay*bandwith product.  However testing has shown this not
357 	 * to be much of an problem.  At worst we are trading wasting
358 	 * of available bandwith (the non-use of it) for wasting some
359 	 * socket buffer memory.
360 	 *
361 	 * TODO: Shrink send buffer during idle periods together
362 	 * with congestion window.  Requires another timer.  Has to
363 	 * wait for upcoming tcp timer rewrite.
364 	 */
365 	if (tcp_do_autosndbuf && so->so_snd.ssb_flags & SSB_AUTOSIZE) {
366 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.ssb_hiwat &&
367 		    so->so_snd.ssb_cc >= (so->so_snd.ssb_hiwat / 8 * 7) &&
368 		    so->so_snd.ssb_cc < tcp_autosndbuf_max &&
369 		    sendwin >= (so->so_snd.ssb_cc - (tp->snd_nxt - tp->snd_una))) {
370 			u_long newsize;
371 
372 			newsize = ulmin(so->so_snd.ssb_hiwat +
373 					 tcp_autosndbuf_inc,
374 					tcp_autosndbuf_max);
375 			if (!ssb_reserve(&so->so_snd, newsize, so, NULL))
376 				atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
377 			if (newsize >= (TCP_MAXWIN << tp->snd_scale))
378 				atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
379 		}
380 	}
381 
382 	/*
383 	 * Truncate to the maximum segment length and ensure that FIN is
384 	 * removed if the length no longer contains the last data byte.
385 	 */
386 	if (len > tp->t_maxseg) {
387 		len = tp->t_maxseg;
388 		sendalot = TRUE;
389 	}
390 	if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.ssb_cc))
391 		flags &= ~TH_FIN;
392 
393 	recvwin = ssb_space(&so->so_rcv);
394 
395 	/*
396 	 * Sender silly window avoidance.   We transmit under the following
397 	 * conditions when len is non-zero:
398 	 *
399 	 *	- We have a full segment
400 	 *	- This is the last buffer in a write()/send() and we are
401 	 *	  either idle or running NODELAY
402 	 *	- we've timed out (e.g. persist timer)
403 	 *	- we have more then 1/2 the maximum send window's worth of
404 	 *	  data (receiver may be limiting the window size)
405 	 *	- we need to retransmit
406 	 */
407 	if (len) {
408 		if (len == tp->t_maxseg)
409 			goto send;
410 		/*
411 		 * NOTE! on localhost connections an 'ack' from the remote
412 		 * end may occur synchronously with the output and cause
413 		 * us to flush a buffer queued with moretocome.  XXX
414 		 *
415 		 * note: the len + off check is almost certainly unnecessary.
416 		 */
417 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
418 		    (idle || (tp->t_flags & TF_NODELAY)) &&
419 		    len + off >= so->so_snd.ssb_cc &&
420 		    !(tp->t_flags & TF_NOPUSH)) {
421 			goto send;
422 		}
423 		if (tp->t_flags & TF_FORCE)		/* typ. timeout case */
424 			goto send;
425 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
426 			goto send;
427 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
428 			goto send;
429 	}
430 
431 	/*
432 	 * Compare available window to amount of window
433 	 * known to peer (as advertised window less
434 	 * next expected input).  If the difference is at least two
435 	 * max size segments, or at least 50% of the maximum possible
436 	 * window, then want to send a window update to peer.
437 	 */
438 	if (recvwin > 0) {
439 		/*
440 		 * "adv" is the amount we can increase the window,
441 		 * taking into account that we are limited by
442 		 * TCP_MAXWIN << tp->rcv_scale.
443 		 */
444 		long adv = min(recvwin, (long)TCP_MAXWIN << tp->rcv_scale) -
445 			(tp->rcv_adv - tp->rcv_nxt);
446 		long hiwat;
447 
448 		/*
449 		 * This ack case typically occurs when the user has drained
450 		 * the TCP socket buffer sufficiently to warrent an ack
451 		 * containing a 'pure window update'... that is, an ack that
452 		 * ONLY updates the tcp window.
453 		 *
454 		 * It is unclear why we would need to do a pure window update
455 		 * past 2 segments if we are going to do one at 1/2 the high
456 		 * water mark anyway, especially since under normal conditions
457 		 * the user program will drain the socket buffer quickly.
458 		 * The 2-segment pure window update will often add a large
459 		 * number of extra, unnecessary acks to the stream.
460 		 *
461 		 * avoid_pure_win_update now defaults to 1.
462 		 */
463 		if (avoid_pure_win_update == 0 ||
464 		    (tp->t_flags & TF_RXRESIZED)) {
465 			if (adv >= (long) (2 * tp->t_maxseg)) {
466 				goto send;
467 			}
468 		}
469 		hiwat = (long)(TCP_MAXWIN << tp->rcv_scale);
470 		if (hiwat > (long)so->so_rcv.ssb_hiwat)
471 			hiwat = (long)so->so_rcv.ssb_hiwat;
472 		if (adv >= hiwat / 2)
473 			goto send;
474 	}
475 
476 	/*
477 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
478 	 * is also a catch-all for the retransmit timer timeout case.
479 	 */
480 	if (tp->t_flags & TF_ACKNOW)
481 		goto send;
482 	if ((flags & TH_RST) ||
483 	    ((flags & TH_SYN) && !(tp->t_flags & TF_NEEDSYN)))
484 		goto send;
485 	if (SEQ_GT(tp->snd_up, tp->snd_una))
486 		goto send;
487 	/*
488 	 * If our state indicates that FIN should be sent
489 	 * and we have not yet done so, then we need to send.
490 	 */
491 	if (flags & TH_FIN &&
492 	    (!(tp->t_flags & TF_SENTFIN) || tp->snd_nxt == tp->snd_una))
493 		goto send;
494 
495 	/*
496 	 * TCP window updates are not reliable, rather a polling protocol
497 	 * using ``persist'' packets is used to insure receipt of window
498 	 * updates.  The three ``states'' for the output side are:
499 	 *	idle			not doing retransmits or persists
500 	 *	persisting		to move a small or zero window
501 	 *	(re)transmitting	and thereby not persisting
502 	 *
503 	 * tcp_callout_active(tp, tp->tt_persist)
504 	 *	is true when we are in persist state.
505 	 * The TF_FORCE flag in tp->t_flags
506 	 *	is set when we are called to send a persist packet.
507 	 * tcp_callout_active(tp, tp->tt_rexmt)
508 	 *	is set when we are retransmitting
509 	 * The output side is idle when both timers are zero.
510 	 *
511 	 * If send window is too small, there is data to transmit, and no
512 	 * retransmit or persist is pending, then go to persist state.
513 	 * If nothing happens soon, send when timer expires:
514 	 * if window is nonzero, transmit what we can,
515 	 * otherwise force out a byte.
516 	 */
517 	if (so->so_snd.ssb_cc > 0 &&
518 	    !tcp_callout_active(tp, tp->tt_rexmt) &&
519 	    !tcp_callout_active(tp, tp->tt_persist)) {
520 		tp->t_rxtshift = 0;
521 		tcp_setpersist(tp);
522 	}
523 
524 	/*
525 	 * No reason to send a segment, just return.
526 	 */
527 	return (0);
528 
529 send:
530 	/*
531 	 * Before ESTABLISHED, force sending of initial options
532 	 * unless TCP set not to do any options.
533 	 * NOTE: we assume that the IP/TCP header plus TCP options
534 	 * always fit in a single mbuf, leaving room for a maximum
535 	 * link header, i.e.
536 	 *	max_linkhdr + sizeof(struct tcpiphdr) + optlen <= MCLBYTES
537 	 */
538 	optlen = 0;
539 	if (isipv6)
540 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
541 	else
542 		hdrlen = sizeof(struct tcpiphdr);
543 	if (flags & TH_SYN) {
544 		tp->snd_nxt = tp->iss;
545 		if (!(tp->t_flags & TF_NOOPT)) {
546 			u_short mss;
547 
548 			opt[0] = TCPOPT_MAXSEG;
549 			opt[1] = TCPOLEN_MAXSEG;
550 			mss = htons((u_short) tcp_mssopt(tp));
551 			memcpy(opt + 2, &mss, sizeof mss);
552 			optlen = TCPOLEN_MAXSEG;
553 
554 			if ((tp->t_flags & TF_REQ_SCALE) &&
555 			    (!(flags & TH_ACK) ||
556 			     (tp->t_flags & TF_RCVD_SCALE))) {
557 				*((u_int32_t *)(opt + optlen)) = htonl(
558 					TCPOPT_NOP << 24 |
559 					TCPOPT_WINDOW << 16 |
560 					TCPOLEN_WINDOW << 8 |
561 					tp->request_r_scale);
562 				optlen += 4;
563 			}
564 
565 			if ((tcp_do_sack && !(flags & TH_ACK)) ||
566 			    tp->t_flags & TF_SACK_PERMITTED) {
567 				uint32_t *lp = (uint32_t *)(opt + optlen);
568 
569 				*lp = htonl(TCPOPT_SACK_PERMITTED_ALIGNED);
570 				optlen += TCPOLEN_SACK_PERMITTED_ALIGNED;
571 			}
572 		}
573 	}
574 
575 	/*
576 	 * Send a timestamp and echo-reply if this is a SYN and our side
577 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
578 	 * and our peer have sent timestamps in our SYN's.
579 	 */
580 	if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
581 	    !(flags & TH_RST) &&
582 	    (!(flags & TH_ACK) || (tp->t_flags & TF_RCVD_TSTMP))) {
583 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
584 
585 		/* Form timestamp option as shown in appendix A of RFC 1323. */
586 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
587 		*lp++ = htonl(ticks);
588 		*lp   = htonl(tp->ts_recent);
589 		optlen += TCPOLEN_TSTAMP_APPA;
590 	}
591 
592 	/* Set receive buffer autosizing timestamp. */
593 	if (tp->rfbuf_ts == 0 && (so->so_rcv.ssb_flags & SSB_AUTOSIZE))
594 		tp->rfbuf_ts = ticks;
595 
596 	/*
597 	 * If this is a SACK connection and we have a block to report,
598 	 * fill in the SACK blocks in the TCP options.
599 	 */
600 	if ((tp->t_flags & (TF_SACK_PERMITTED | TF_NOOPT)) ==
601 		TF_SACK_PERMITTED &&
602 	    (!LIST_EMPTY(&tp->t_segq) ||
603 	     tp->reportblk.rblk_start != tp->reportblk.rblk_end))
604 		tcp_sack_fill_report(tp, opt, &optlen);
605 
606 #ifdef TCP_SIGNATURE
607 	if (tp->t_flags & TF_SIGNATURE) {
608 		int i;
609 		u_char *bp;
610 		/*
611 		 * Initialize TCP-MD5 option (RFC2385)
612 		 */
613 		bp = (u_char *)opt + optlen;
614 		*bp++ = TCPOPT_SIGNATURE;
615 		*bp++ = TCPOLEN_SIGNATURE;
616 		sigoff = optlen + 2;
617 		for (i = 0; i < TCP_SIGLEN; i++)
618 			*bp++ = 0;
619 		optlen += TCPOLEN_SIGNATURE;
620 		/*
621 		 * Terminate options list and maintain 32-bit alignment.
622 		 */
623 		*bp++ = TCPOPT_NOP;
624 		*bp++ = TCPOPT_EOL;
625 		optlen += 2;
626 	}
627 #endif /* TCP_SIGNATURE */
628 	KASSERT(optlen <= TCP_MAXOLEN, ("too many TCP options"));
629 	hdrlen += optlen;
630 
631 	if (isipv6) {
632 		ipoptlen = ip6_optlen(inp);
633 	} else {
634 		if (inp->inp_options) {
635 			ipoptlen = inp->inp_options->m_len -
636 			    offsetof(struct ipoption, ipopt_list);
637 		} else {
638 			ipoptlen = 0;
639 		}
640 	}
641 #ifdef IPSEC
642 	ipoptlen += ipsec_hdrsiz_tcp(tp);
643 #endif
644 
645 	/*
646 	 * Adjust data length if insertion of options will bump the packet
647 	 * length beyond the t_maxopd length.  Clear FIN to prevent premature
648 	 * closure since there is still more data to send after this (now
649 	 * truncated) packet.
650 	 *
651 	 * If just the options do not fit we are in a no-win situation and
652 	 * we treat it as an unreachable host.
653 	 */
654 	if (len + optlen + ipoptlen > tp->t_maxopd) {
655 		if (tp->t_maxopd <= optlen + ipoptlen) {
656 			static time_t last_optlen_report;
657 
658 			if (last_optlen_report != time_second) {
659 				last_optlen_report = time_second;
660 				kprintf("tcpcb %p: MSS (%d) too small to hold options!\n", tp, tp->t_maxopd);
661 			}
662 			error = EHOSTUNREACH;
663 			goto out;
664 		} else {
665 			flags &= ~TH_FIN;
666 			len = tp->t_maxopd - optlen - ipoptlen;
667 			sendalot = TRUE;
668 		}
669 	}
670 
671 #ifdef INET6
672 	KASSERT(max_linkhdr + hdrlen <= MCLBYTES, ("tcphdr too big"));
673 #else
674 	KASSERT(max_linkhdr + hdrlen <= MHLEN, ("tcphdr too big"));
675 #endif
676 
677 	/*
678 	 * Grab a header mbuf, attaching a copy of data to
679 	 * be transmitted, and initialize the header from
680 	 * the template for sends on this connection.
681 	 */
682 	if (len) {
683 		if ((tp->t_flags & TF_FORCE) && len == 1)
684 			tcpstat.tcps_sndprobe++;
685 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
686 			if (tp->snd_nxt == tp->snd_una)
687 				tp->snd_max_rexmt = tp->snd_max;
688 			tcpstat.tcps_sndrexmitpack++;
689 			tcpstat.tcps_sndrexmitbyte += len;
690 		} else {
691 			tcpstat.tcps_sndpack++;
692 			tcpstat.tcps_sndbyte += len;
693 		}
694 #ifdef notyet
695 		if ((m = m_copypack(so->so_snd.ssb_mb, off, (int)len,
696 		    max_linkhdr + hdrlen)) == NULL) {
697 			error = ENOBUFS;
698 			goto out;
699 		}
700 		/*
701 		 * m_copypack left space for our hdr; use it.
702 		 */
703 		m->m_len += hdrlen;
704 		m->m_data -= hdrlen;
705 #else
706 #ifndef INET6
707 		m = m_gethdr(MB_DONTWAIT, MT_HEADER);
708 #else
709 		m = m_getl(hdrlen + max_linkhdr, MB_DONTWAIT, MT_HEADER,
710 			   M_PKTHDR, NULL);
711 #endif
712 		if (m == NULL) {
713 			error = ENOBUFS;
714 			goto out;
715 		}
716 		m->m_data += max_linkhdr;
717 		m->m_len = hdrlen;
718 		if (len <= MHLEN - hdrlen - max_linkhdr) {
719 			m_copydata(so->so_snd.ssb_mb, off, (int) len,
720 			    mtod(m, caddr_t) + hdrlen);
721 			m->m_len += len;
722 		} else {
723 			m->m_next = m_copy(so->so_snd.ssb_mb, off, (int) len);
724 			if (m->m_next == NULL) {
725 				m_free(m);
726 				error = ENOBUFS;
727 				goto out;
728 			}
729 		}
730 #endif
731 		/*
732 		 * If we're sending everything we've got, set PUSH.
733 		 * (This will keep happy those implementations which only
734 		 * give data to the user when a buffer fills or
735 		 * a PUSH comes in.)
736 		 */
737 		if (off + len == so->so_snd.ssb_cc)
738 			flags |= TH_PUSH;
739 	} else {
740 		if (tp->t_flags & TF_ACKNOW)
741 			tcpstat.tcps_sndacks++;
742 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
743 			tcpstat.tcps_sndctrl++;
744 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
745 			tcpstat.tcps_sndurg++;
746 		else
747 			tcpstat.tcps_sndwinup++;
748 
749 		MGETHDR(m, MB_DONTWAIT, MT_HEADER);
750 		if (m == NULL) {
751 			error = ENOBUFS;
752 			goto out;
753 		}
754 		if (isipv6 &&
755 		    (hdrlen + max_linkhdr > MHLEN) && hdrlen <= MHLEN)
756 			MH_ALIGN(m, hdrlen);
757 		else
758 			m->m_data += max_linkhdr;
759 		m->m_len = hdrlen;
760 	}
761 	m->m_pkthdr.rcvif = NULL;
762 	if (isipv6) {
763 		ip6 = mtod(m, struct ip6_hdr *);
764 		th = (struct tcphdr *)(ip6 + 1);
765 		tcp_fillheaders(tp, ip6, th);
766 	} else {
767 		ip = mtod(m, struct ip *);
768 		ipov = (struct ipovly *)ip;
769 		th = (struct tcphdr *)(ip + 1);
770 		/* this picks up the pseudo header (w/o the length) */
771 		tcp_fillheaders(tp, ip, th);
772 	}
773 
774 	/*
775 	 * Fill in fields, remembering maximum advertised
776 	 * window for use in delaying messages about window sizes.
777 	 * If resending a FIN, be sure not to use a new sequence number.
778 	 */
779 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
780 	    tp->snd_nxt == tp->snd_max)
781 		tp->snd_nxt--;
782 	/*
783 	 * If we are doing retransmissions, then snd_nxt will
784 	 * not reflect the first unsent octet.  For ACK only
785 	 * packets, we do not want the sequence number of the
786 	 * retransmitted packet, we want the sequence number
787 	 * of the next unsent octet.  So, if there is no data
788 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
789 	 * when filling in ti_seq.  But if we are in persist
790 	 * state, snd_max might reflect one byte beyond the
791 	 * right edge of the window, so use snd_nxt in that
792 	 * case, since we know we aren't doing a retransmission.
793 	 * (retransmit and persist are mutually exclusive...)
794 	 */
795 	if (len || (flags & (TH_SYN|TH_FIN)) ||
796 	    tcp_callout_active(tp, tp->tt_persist))
797 		th->th_seq = htonl(tp->snd_nxt);
798 	else
799 		th->th_seq = htonl(tp->snd_max);
800 	th->th_ack = htonl(tp->rcv_nxt);
801 	if (optlen) {
802 		bcopy(opt, th + 1, optlen);
803 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
804 	}
805 	th->th_flags = flags;
806 
807 	/*
808 	 * Calculate receive window.  Don't shrink window, but avoid
809 	 * silly window syndrome by sending a 0 window if the actual
810 	 * window is less then one segment.
811 	 */
812 	if (recvwin < (long)(so->so_rcv.ssb_hiwat / 4) &&
813 	    recvwin < (long)tp->t_maxseg)
814 		recvwin = 0;
815 	if (recvwin < (tcp_seq_diff_t)(tp->rcv_adv - tp->rcv_nxt))
816 		recvwin = (tcp_seq_diff_t)(tp->rcv_adv - tp->rcv_nxt);
817 	if (recvwin > (long)TCP_MAXWIN << tp->rcv_scale)
818 		recvwin = (long)TCP_MAXWIN << tp->rcv_scale;
819 	th->th_win = htons((u_short) (recvwin>>tp->rcv_scale));
820 
821 	/*
822 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
823 	 * a 0 window.  This may cause the remote transmitter to stall.  This
824 	 * flag tells soreceive() to disable delayed acknowledgements when
825 	 * draining the buffer.  This can occur if the receiver is attempting
826 	 * to read more data then can be buffered prior to transmitting on
827 	 * the connection.
828 	 */
829 	if (recvwin == 0)
830 		tp->t_flags |= TF_RXWIN0SENT;
831 	else
832 		tp->t_flags &= ~TF_RXWIN0SENT;
833 
834 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
835 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
836 		th->th_flags |= TH_URG;
837 	} else {
838 		/*
839 		 * If no urgent pointer to send, then we pull
840 		 * the urgent pointer to the left edge of the send window
841 		 * so that it doesn't drift into the send window on sequence
842 		 * number wraparound.
843 		 */
844 		tp->snd_up = tp->snd_una;		/* drag it along */
845 	}
846 
847 #ifdef TCP_SIGNATURE
848 	if (tp->t_flags & TF_SIGNATURE)
849 		tcpsignature_compute(m, len, optlen,
850 				(u_char *)(th + 1) + sigoff, IPSEC_DIR_OUTBOUND);
851 #endif /* TCP_SIGNATURE */
852 
853 	/*
854 	 * Put TCP length in extended header, and then
855 	 * checksum extended header and data.
856 	 */
857 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
858 	if (isipv6) {
859 		/*
860 		 * ip6_plen is not need to be filled now, and will be filled
861 		 * in ip6_output().
862 		 */
863 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
864 				       sizeof(struct tcphdr) + optlen + len);
865 	} else {
866 		m->m_pkthdr.csum_flags = CSUM_TCP;
867 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
868 		if (len + optlen)
869 			th->th_sum = in_addword(th->th_sum,
870 						htons((u_short)(optlen + len)));
871 
872 		/* IP version must be set here for ipv4/ipv6 checking later */
873 		KASSERT(ip->ip_v == IPVERSION,
874 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
875 	}
876 
877 	/*
878 	 * In transmit state, time the transmission and arrange for
879 	 * the retransmit.  In persist state, just set snd_max.
880 	 */
881 	if (!(tp->t_flags & TF_FORCE) ||
882 	    !tcp_callout_active(tp, tp->tt_persist)) {
883 		tcp_seq startseq = tp->snd_nxt;
884 
885 		/*
886 		 * Advance snd_nxt over sequence space of this segment.
887 		 */
888 		if (flags & (TH_SYN | TH_FIN)) {
889 			if (flags & TH_SYN)
890 				tp->snd_nxt++;
891 			if (flags & TH_FIN) {
892 				tp->snd_nxt++;
893 				tp->t_flags |= TF_SENTFIN;
894 			}
895 		}
896 		tp->snd_nxt += len;
897 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
898 			tp->snd_max = tp->snd_nxt;
899 			/*
900 			 * Time this transmission if not a retransmission and
901 			 * not currently timing anything.
902 			 */
903 			if (tp->t_rtttime == 0) {
904 				tp->t_rtttime = ticks;
905 				tp->t_rtseq = startseq;
906 				tcpstat.tcps_segstimed++;
907 			}
908 		}
909 
910 		/*
911 		 * Set retransmit timer if not currently set,
912 		 * and not doing a pure ack or a keep-alive probe.
913 		 * Initial value for retransmit timer is smoothed
914 		 * round-trip time + 2 * round-trip time variance.
915 		 * Initialize shift counter which is used for backoff
916 		 * of retransmit time.
917 		 */
918 		if (!tcp_callout_active(tp, tp->tt_rexmt) &&
919 		    tp->snd_nxt != tp->snd_una) {
920 			if (tcp_callout_active(tp, tp->tt_persist)) {
921 				tcp_callout_stop(tp, tp->tt_persist);
922 				tp->t_rxtshift = 0;
923 			}
924 			tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
925 			    tcp_timer_rexmt);
926 		}
927 	} else {
928 		/*
929 		 * Persist case, update snd_max but since we are in
930 		 * persist mode (no window) we do not update snd_nxt.
931 		 */
932 		int xlen = len;
933 		if (flags & TH_SYN)
934 			++xlen;
935 		if (flags & TH_FIN) {
936 			++xlen;
937 			tp->t_flags |= TF_SENTFIN;
938 		}
939 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
940 			tp->snd_max = tp->snd_nxt + xlen;
941 	}
942 
943 #ifdef TCPDEBUG
944 	/*
945 	 * Trace.
946 	 */
947 	if (so->so_options & SO_DEBUG)
948 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
949 #endif
950 
951 	/*
952 	 * Fill in IP length and desired time to live and
953 	 * send to IP level.  There should be a better way
954 	 * to handle ttl and tos; we could keep them in
955 	 * the template, but need a way to checksum without them.
956 	 */
957 	/*
958 	 * m->m_pkthdr.len should have been set before cksum calcuration,
959 	 * because in6_cksum() need it.
960 	 */
961 	if (isipv6) {
962 		/*
963 		 * we separately set hoplimit for every segment, since the
964 		 * user might want to change the value via setsockopt.
965 		 * Also, desired default hop limit might be changed via
966 		 * Neighbor Discovery.
967 		 */
968 		ip6->ip6_hlim = in6_selecthlim(inp,
969 		    (inp->in6p_route.ro_rt ?
970 		     inp->in6p_route.ro_rt->rt_ifp : NULL));
971 
972 		/* TODO: IPv6 IP6TOS_ECT bit on */
973 		error = ip6_output(m, inp->in6p_outputopts, &inp->in6p_route,
974 				   (so->so_options & SO_DONTROUTE), NULL, NULL,
975 				   inp);
976 	} else {
977 		struct rtentry *rt;
978 		ip->ip_len = m->m_pkthdr.len;
979 #ifdef INET6
980 		if (INP_CHECK_SOCKAF(so, AF_INET6))
981 			ip->ip_ttl = in6_selecthlim(inp,
982 			    (inp->in6p_route.ro_rt ?
983 			     inp->in6p_route.ro_rt->rt_ifp : NULL));
984 		else
985 #endif
986 			ip->ip_ttl = inp->inp_ip_ttl;	/* XXX */
987 
988 		ip->ip_tos = inp->inp_ip_tos;	/* XXX */
989 		/*
990 		 * See if we should do MTU discovery.
991 		 * We do it only if the following are true:
992 		 *	1) we have a valid route to the destination
993 		 *	2) the MTU is not locked (if it is,
994 		 *	   then discovery has been disabled)
995 		 */
996 		if (path_mtu_discovery &&
997 		    (rt = inp->inp_route.ro_rt) && (rt->rt_flags & RTF_UP) &&
998 		    !(rt->rt_rmx.rmx_locks & RTV_MTU))
999 			ip->ip_off |= IP_DF;
1000 
1001 		error = ip_output(m, inp->inp_options, &inp->inp_route,
1002 				  (so->so_options & SO_DONTROUTE) |
1003 				  IP_DEBUGROUTE, NULL, inp);
1004 	}
1005 	if (error) {
1006 
1007 		/*
1008 		 * We know that the packet was lost, so back out the
1009 		 * sequence number advance, if any.
1010 		 */
1011 		if (!(tp->t_flags & TF_FORCE) ||
1012 		    !tcp_callout_active(tp, tp->tt_persist)) {
1013 			/*
1014 			 * No need to check for TH_FIN here because
1015 			 * the TF_SENTFIN flag handles that case.
1016 			 */
1017 			if (!(flags & TH_SYN))
1018 				tp->snd_nxt -= len;
1019 		}
1020 
1021 out:
1022 		if (error == ENOBUFS) {
1023 			/*
1024 			 * If we can't send, make sure there is something
1025 			 * to get us going again later.  Persist state
1026 			 * is not necessarily right, but it is close enough.
1027 			 */
1028 			if (!tcp_callout_active(tp, tp->tt_rexmt) &&
1029 			    !tcp_callout_active(tp, tp->tt_persist)) {
1030 				tp->t_rxtshift = 0;
1031 				tcp_setpersist(tp);
1032 			}
1033 			tcp_quench(inp, 0);
1034 			return (0);
1035 		}
1036 		if (error == EMSGSIZE) {
1037 			/*
1038 			 * ip_output() will have already fixed the route
1039 			 * for us.  tcp_mtudisc() will, as its last action,
1040 			 * initiate retransmission, so it is important to
1041 			 * not do so here.
1042 			 */
1043 			tcp_mtudisc(inp, 0);
1044 			return 0;
1045 		}
1046 		if ((error == EHOSTUNREACH || error == ENETDOWN) &&
1047 		    TCPS_HAVERCVDSYN(tp->t_state)) {
1048 			tp->t_softerror = error;
1049 			return (0);
1050 		}
1051 		return (error);
1052 	}
1053 	tcpstat.tcps_sndtotal++;
1054 
1055 	/*
1056 	 * Data sent (as far as we can tell).
1057 	 *
1058 	 * If this advertises a larger window than any other segment,
1059 	 * then remember the size of the advertised window.
1060 	 *
1061 	 * Any pending ACK has now been sent.
1062 	 */
1063 	if (recvwin > 0 && SEQ_GT(tp->rcv_nxt + recvwin, tp->rcv_adv)) {
1064 		tp->rcv_adv = tp->rcv_nxt + recvwin;
1065 		tp->t_flags &= ~TF_RXRESIZED;
1066 	}
1067 	tp->last_ack_sent = tp->rcv_nxt;
1068 	tp->t_flags &= ~TF_ACKNOW;
1069 	if (tcp_delack_enabled)
1070 		tcp_callout_stop(tp, tp->tt_delack);
1071 	if (sendalot)
1072 		goto again;
1073 	return (0);
1074 }
1075 
1076 void
1077 tcp_setpersist(struct tcpcb *tp)
1078 {
1079 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1080 	int tt;
1081 
1082 	if (tcp_callout_active(tp, tp->tt_rexmt))
1083 		panic("tcp_setpersist: retransmit pending");
1084 	/*
1085 	 * Start/restart persistance timer.
1086 	 */
1087 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift], TCPTV_PERSMIN,
1088 		      TCPTV_PERSMAX);
1089 	tcp_callout_reset(tp, tp->tt_persist, tt, tcp_timer_persist);
1090 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1091 		tp->t_rxtshift++;
1092 }
1093