xref: /freebsd/sys/netinet/tcp_output.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
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  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
34  * $FreeBSD$
35  */
36 
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/sysctl.h>
45 #include <sys/mbuf.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 
51 #include <net/route.h>
52 
53 #include <netinet/in.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56 #include <netinet/in_pcb.h>
57 #include <netinet/ip_var.h>
58 #ifdef INET6
59 #include <netinet6/in6_pcb.h>
60 #include <netinet/ip6.h>
61 #include <netinet6/ip6_var.h>
62 #endif
63 #include <netinet/tcp.h>
64 #define	TCPOUTFLAGS
65 #include <netinet/tcp_fsm.h>
66 #include <netinet/tcp_seq.h>
67 #include <netinet/tcp_timer.h>
68 #include <netinet/tcp_var.h>
69 #include <netinet/tcpip.h>
70 #ifdef TCPDEBUG
71 #include <netinet/tcp_debug.h>
72 #endif
73 
74 #ifdef IPSEC
75 #include <netinet6/ipsec.h>
76 #endif /*IPSEC*/
77 
78 #include <machine/in_cksum.h>
79 
80 #ifdef notyet
81 extern struct mbuf *m_copypack();
82 #endif
83 
84 static int path_mtu_discovery = 1;
85 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_RW,
86 	&path_mtu_discovery, 1, "Enable Path MTU Discovery");
87 
88 int ss_fltsz = 1;
89 SYSCTL_INT(_net_inet_tcp, OID_AUTO, slowstart_flightsize, CTLFLAG_RW,
90 	&ss_fltsz, 1, "Slow start flight size");
91 
92 int ss_fltsz_local = TCP_MAXWIN;               /* something large */
93 SYSCTL_INT(_net_inet_tcp, OID_AUTO, local_slowstart_flightsize, CTLFLAG_RW,
94 	&ss_fltsz_local, 1, "Slow start flight size for local networks");
95 
96 int     tcp_do_newreno = 1;
97 SYSCTL_INT(_net_inet_tcp, OID_AUTO, newreno, CTLFLAG_RW, &tcp_do_newreno,
98         0, "Enable NewReno Algorithms");
99 /*
100  * Tcp output routine: figure out what should be sent and send it.
101  */
102 int
103 tcp_output(tp)
104 	register struct tcpcb *tp;
105 {
106 	register struct socket *so = tp->t_inpcb->inp_socket;
107 	register long len, win;
108 	int off, flags, error;
109 	register struct mbuf *m;
110 	struct ip *ip = NULL;
111 	register struct ipovly *ipov = NULL;
112 #ifdef INET6
113 	struct ip6_hdr *ip6 = NULL;
114 #endif /* INET6 */
115 	register struct tcphdr *th;
116 	u_char opt[TCP_MAXOLEN];
117 	unsigned ipoptlen, optlen, hdrlen;
118 	int idle, sendalot;
119 	int maxburst = TCP_MAXBURST;
120 	struct rmxp_tao *taop;
121 	struct rmxp_tao tao_noncached;
122 #ifdef INET6
123 	int isipv6;
124 #endif
125 
126 #ifdef INET6
127 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
128 #endif
129 
130 	/*
131 	 * Determine length of data that should be transmitted,
132 	 * and flags that will be used.
133 	 * If there is some data or critical controls (SYN, RST)
134 	 * to send, then transmit; otherwise, investigate further.
135 	 */
136 	idle = (tp->snd_max == tp->snd_una);
137 	if (idle && (ticks - tp->t_rcvtime) >= tp->t_rxtcur) {
138 		/*
139 		 * We have been idle for "a while" and no acks are
140 		 * expected to clock out any data we send --
141 		 * slow start to get ack "clock" running again.
142 		 *
143 		 * Set the slow-start flight size depending on whether
144 		 * this is a local network or not.
145 		 */
146 		if (
147 #ifdef INET6
148 		    (isipv6 && in6_localaddr(&tp->t_inpcb->in6p_faddr)) ||
149 		    (!isipv6 &&
150 #endif
151 		     in_localaddr(tp->t_inpcb->inp_faddr)
152 #ifdef INET6
153 		     )
154 #endif
155 		    )
156 			tp->snd_cwnd = tp->t_maxseg * ss_fltsz_local;
157 		else
158 			tp->snd_cwnd = tp->t_maxseg * ss_fltsz;
159 	}
160 again:
161 	sendalot = 0;
162 	off = tp->snd_nxt - tp->snd_una;
163 	win = min(tp->snd_wnd, tp->snd_cwnd);
164 
165 	flags = tcp_outflags[tp->t_state];
166 	/*
167 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
168 	 * state flags.
169 	 */
170 	if (tp->t_flags & TF_NEEDFIN)
171 		flags |= TH_FIN;
172 	if (tp->t_flags & TF_NEEDSYN)
173 		flags |= TH_SYN;
174 
175 	/*
176 	 * If in persist timeout with window of 0, send 1 byte.
177 	 * Otherwise, if window is small but nonzero
178 	 * and timer expired, we will send what we can
179 	 * and go to transmit state.
180 	 */
181 	if (tp->t_force) {
182 		if (win == 0) {
183 			/*
184 			 * If we still have some data to send, then
185 			 * clear the FIN bit.  Usually this would
186 			 * happen below when it realizes that we
187 			 * aren't sending all the data.  However,
188 			 * if we have exactly 1 byte of unsent data,
189 			 * then it won't clear the FIN bit below,
190 			 * and if we are in persist state, we wind
191 			 * up sending the packet without recording
192 			 * that we sent the FIN bit.
193 			 *
194 			 * We can't just blindly clear the FIN bit,
195 			 * because if we don't have any more data
196 			 * to send then the probe will be the FIN
197 			 * itself.
198 			 */
199 			if (off < so->so_snd.sb_cc)
200 				flags &= ~TH_FIN;
201 			win = 1;
202 		} else {
203 			callout_stop(tp->tt_persist);
204 			tp->t_rxtshift = 0;
205 		}
206 	}
207 
208 	len = (long)ulmin(so->so_snd.sb_cc, win) - off;
209 
210 	if ((taop = tcp_gettaocache(tp->t_inpcb)) == NULL) {
211 		taop = &tao_noncached;
212 		bzero(taop, sizeof(*taop));
213 	}
214 
215 	/*
216 	 * Lop off SYN bit if it has already been sent.  However, if this
217 	 * is SYN-SENT state and if segment contains data and if we don't
218 	 * know that foreign host supports TAO, suppress sending segment.
219 	 */
220 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
221 		flags &= ~TH_SYN;
222 		off--, len++;
223 		if (len > 0 && tp->t_state == TCPS_SYN_SENT &&
224 		    taop->tao_ccsent == 0)
225 			return 0;
226 	}
227 
228 	/*
229 	 * Be careful not to send data and/or FIN on SYN segments
230 	 * in cases when no CC option will be sent.
231 	 * This measure is needed to prevent interoperability problems
232 	 * with not fully conformant TCP implementations.
233 	 */
234 	if ((flags & TH_SYN) &&
235 	    ((tp->t_flags & TF_NOOPT) || !(tp->t_flags & TF_REQ_CC) ||
236 	     ((flags & TH_ACK) && !(tp->t_flags & TF_RCVD_CC)))) {
237 		len = 0;
238 		flags &= ~TH_FIN;
239 	}
240 
241 	if (len < 0) {
242 		/*
243 		 * If FIN has been sent but not acked,
244 		 * but we haven't been called to retransmit,
245 		 * len will be -1.  Otherwise, window shrank
246 		 * after we sent into it.  If window shrank to 0,
247 		 * cancel pending retransmit, pull snd_nxt back
248 		 * to (closed) window, and set the persist timer
249 		 * if it isn't already going.  If the window didn't
250 		 * close completely, just wait for an ACK.
251 		 */
252 		len = 0;
253 		if (win == 0) {
254 			callout_stop(tp->tt_rexmt);
255 			tp->t_rxtshift = 0;
256 			tp->snd_nxt = tp->snd_una;
257 			if (!callout_active(tp->tt_persist))
258 				tcp_setpersist(tp);
259 		}
260 	}
261 	if (len > tp->t_maxseg) {
262 		len = tp->t_maxseg;
263 		sendalot = 1;
264 	}
265 	if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))
266 		flags &= ~TH_FIN;
267 
268 	win = sbspace(&so->so_rcv);
269 
270 	/*
271 	 * Sender silly window avoidance.  If connection is idle
272 	 * and can send all data, a maximum segment,
273 	 * at least a maximum default-size segment do it,
274 	 * or are forced, do it; otherwise don't bother.
275 	 * If peer's buffer is tiny, then send
276 	 * when window is at least half open.
277 	 * If retransmitting (possibly after persist timer forced us
278 	 * to send into a small window), then must resend.
279 	 */
280 	if (len) {
281 		if (len == tp->t_maxseg)
282 			goto send;
283 		if (!(tp->t_flags & TF_MORETOCOME) &&
284 		    (idle || tp->t_flags & TF_NODELAY) &&
285 		    (tp->t_flags & TF_NOPUSH) == 0 &&
286 		    len + off >= so->so_snd.sb_cc)
287 			goto send;
288 		if (tp->t_force)
289 			goto send;
290 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
291 			goto send;
292 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
293 			goto send;
294 	}
295 
296 	/*
297 	 * Compare available window to amount of window
298 	 * known to peer (as advertised window less
299 	 * next expected input).  If the difference is at least two
300 	 * max size segments, or at least 50% of the maximum possible
301 	 * window, then want to send a window update to peer.
302 	 */
303 	if (win > 0) {
304 		/*
305 		 * "adv" is the amount we can increase the window,
306 		 * taking into account that we are limited by
307 		 * TCP_MAXWIN << tp->rcv_scale.
308 		 */
309 		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
310 			(tp->rcv_adv - tp->rcv_nxt);
311 
312 		if (adv >= (long) (2 * tp->t_maxseg))
313 			goto send;
314 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
315 			goto send;
316 	}
317 
318 	/*
319 	 * Send if we owe peer an ACK.
320 	 */
321 	if (tp->t_flags & TF_ACKNOW)
322 		goto send;
323 	if ((flags & TH_RST) ||
324 	    ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
325 		goto send;
326 	if (SEQ_GT(tp->snd_up, tp->snd_una))
327 		goto send;
328 	/*
329 	 * If our state indicates that FIN should be sent
330 	 * and we have not yet done so, or we're retransmitting the FIN,
331 	 * then we need to send.
332 	 */
333 	if (flags & TH_FIN &&
334 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
335 		goto send;
336 
337 	/*
338 	 * TCP window updates are not reliable, rather a polling protocol
339 	 * using ``persist'' packets is used to insure receipt of window
340 	 * updates.  The three ``states'' for the output side are:
341 	 *	idle			not doing retransmits or persists
342 	 *	persisting		to move a small or zero window
343 	 *	(re)transmitting	and thereby not persisting
344 	 *
345 	 * callout_active(tp->tt_persist)
346 	 *	is true when we are in persist state.
347 	 * tp->t_force
348 	 *	is set when we are called to send a persist packet.
349 	 * callout_active(tp->tt_rexmt)
350 	 *	is set when we are retransmitting
351 	 * The output side is idle when both timers are zero.
352 	 *
353 	 * If send window is too small, there is data to transmit, and no
354 	 * retransmit or persist is pending, then go to persist state.
355 	 * If nothing happens soon, send when timer expires:
356 	 * if window is nonzero, transmit what we can,
357 	 * otherwise force out a byte.
358 	 */
359 	if (so->so_snd.sb_cc && !callout_active(tp->tt_rexmt) &&
360 	    !callout_active(tp->tt_persist)) {
361 		tp->t_rxtshift = 0;
362 		tcp_setpersist(tp);
363 	}
364 
365 	/*
366 	 * No reason to send a segment, just return.
367 	 */
368 	return (0);
369 
370 send:
371 	/*
372 	 * Before ESTABLISHED, force sending of initial options
373 	 * unless TCP set not to do any options.
374 	 * NOTE: we assume that the IP/TCP header plus TCP options
375 	 * always fit in a single mbuf, leaving room for a maximum
376 	 * link header, i.e.
377 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN
378 	 */
379 	optlen = 0;
380 #ifdef INET6
381 	if (isipv6)
382 		hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
383 	else
384 #endif
385 	hdrlen = sizeof (struct tcpiphdr);
386 	if (flags & TH_SYN) {
387 		tp->snd_nxt = tp->iss;
388 		if ((tp->t_flags & TF_NOOPT) == 0) {
389 			u_short mss;
390 
391 			opt[0] = TCPOPT_MAXSEG;
392 			opt[1] = TCPOLEN_MAXSEG;
393 			mss = htons((u_short) tcp_mssopt(tp));
394 			(void)memcpy(opt + 2, &mss, sizeof(mss));
395 			optlen = TCPOLEN_MAXSEG;
396 
397 			if ((tp->t_flags & TF_REQ_SCALE) &&
398 			    ((flags & TH_ACK) == 0 ||
399 			    (tp->t_flags & TF_RCVD_SCALE))) {
400 				*((u_int32_t *)(opt + optlen)) = htonl(
401 					TCPOPT_NOP << 24 |
402 					TCPOPT_WINDOW << 16 |
403 					TCPOLEN_WINDOW << 8 |
404 					tp->request_r_scale);
405 				optlen += 4;
406 			}
407 		}
408  	}
409 
410  	/*
411 	 * Send a timestamp and echo-reply if this is a SYN and our side
412 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
413 	 * and our peer have sent timestamps in our SYN's.
414  	 */
415  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
416  	    (flags & TH_RST) == 0 &&
417 	    ((flags & TH_ACK) == 0 ||
418 	     (tp->t_flags & TF_RCVD_TSTMP))) {
419 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
420 
421  		/* Form timestamp option as shown in appendix A of RFC 1323. */
422  		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
423  		*lp++ = htonl(ticks);
424  		*lp   = htonl(tp->ts_recent);
425  		optlen += TCPOLEN_TSTAMP_APPA;
426  	}
427 
428  	/*
429 	 * Send `CC-family' options if our side wants to use them (TF_REQ_CC),
430 	 * options are allowed (!TF_NOOPT) and it's not a RST.
431  	 */
432  	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
433  	     (flags & TH_RST) == 0) {
434 		switch (flags & (TH_SYN|TH_ACK)) {
435 		/*
436 		 * This is a normal ACK, send CC if we received CC before
437 		 * from our peer.
438 		 */
439 		case TH_ACK:
440 			if (!(tp->t_flags & TF_RCVD_CC))
441 				break;
442 			/*FALLTHROUGH*/
443 
444 		/*
445 		 * We can only get here in T/TCP's SYN_SENT* state, when
446 		 * we're a sending a non-SYN segment without waiting for
447 		 * the ACK of our SYN.  A check above assures that we only
448 		 * do this if our peer understands T/TCP.
449 		 */
450 		case 0:
451 			opt[optlen++] = TCPOPT_NOP;
452 			opt[optlen++] = TCPOPT_NOP;
453 			opt[optlen++] = TCPOPT_CC;
454 			opt[optlen++] = TCPOLEN_CC;
455 			*(u_int32_t *)&opt[optlen] = htonl(tp->cc_send);
456 
457 			optlen += 4;
458 			break;
459 
460 		/*
461 		 * This is our initial SYN, check whether we have to use
462 		 * CC or CC.new.
463 		 */
464 		case TH_SYN:
465 			opt[optlen++] = TCPOPT_NOP;
466 			opt[optlen++] = TCPOPT_NOP;
467 			opt[optlen++] = tp->t_flags & TF_SENDCCNEW ?
468 						TCPOPT_CCNEW : TCPOPT_CC;
469 			opt[optlen++] = TCPOLEN_CC;
470 			*(u_int32_t *)&opt[optlen] = htonl(tp->cc_send);
471  			optlen += 4;
472 			break;
473 
474 		/*
475 		 * This is a SYN,ACK; send CC and CC.echo if we received
476 		 * CC from our peer.
477 		 */
478 		case (TH_SYN|TH_ACK):
479 			if (tp->t_flags & TF_RCVD_CC) {
480 				opt[optlen++] = TCPOPT_NOP;
481 				opt[optlen++] = TCPOPT_NOP;
482 				opt[optlen++] = TCPOPT_CC;
483 				opt[optlen++] = TCPOLEN_CC;
484 				*(u_int32_t *)&opt[optlen] =
485 					htonl(tp->cc_send);
486 				optlen += 4;
487 				opt[optlen++] = TCPOPT_NOP;
488 				opt[optlen++] = TCPOPT_NOP;
489 				opt[optlen++] = TCPOPT_CCECHO;
490 				opt[optlen++] = TCPOLEN_CC;
491 				*(u_int32_t *)&opt[optlen] =
492 					htonl(tp->cc_recv);
493 				optlen += 4;
494 			}
495 			break;
496 		}
497  	}
498 
499  	hdrlen += optlen;
500 
501 #ifdef INET6
502 	if (isipv6)
503 		ipoptlen = ip6_optlen(tp->t_inpcb);
504 	else
505 #endif
506       {
507 	if (tp->t_inpcb->inp_options) {
508 		ipoptlen = tp->t_inpcb->inp_options->m_len -
509 				offsetof(struct ipoption, ipopt_list);
510 	} else {
511 		ipoptlen = 0;
512 	}
513       }
514 #ifdef IPSEC
515 	ipoptlen += ipsec_hdrsiz_tcp(tp);
516 #endif
517 
518 	/*
519 	 * Adjust data length if insertion of options will
520 	 * bump the packet length beyond the t_maxopd length.
521 	 * Clear the FIN bit because we cut off the tail of
522 	 * the segment.
523 	 */
524 	if (len + optlen + ipoptlen > tp->t_maxopd) {
525 		/*
526 		 * If there is still more to send, don't close the connection.
527 		 */
528 		flags &= ~TH_FIN;
529 		len = tp->t_maxopd - optlen - ipoptlen;
530 		sendalot = 1;
531 	}
532 
533 /*#ifdef DIAGNOSTIC*/
534 #ifdef INET6
535  	if (max_linkhdr + hdrlen > MCLBYTES)
536 		panic("tcphdr too big");
537 #else
538  	if (max_linkhdr + hdrlen > MHLEN)
539 		panic("tcphdr too big");
540 #endif
541 /*#endif*/
542 
543 	/*
544 	 * Grab a header mbuf, attaching a copy of data to
545 	 * be transmitted, and initialize the header from
546 	 * the template for sends on this connection.
547 	 */
548 	if (len) {
549 		if (tp->t_force && len == 1)
550 			tcpstat.tcps_sndprobe++;
551 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
552 			tcpstat.tcps_sndrexmitpack++;
553 			tcpstat.tcps_sndrexmitbyte += len;
554 		} else {
555 			tcpstat.tcps_sndpack++;
556 			tcpstat.tcps_sndbyte += len;
557 		}
558 #ifdef notyet
559 		if ((m = m_copypack(so->so_snd.sb_mb, off,
560 		    (int)len, max_linkhdr + hdrlen)) == 0) {
561 			error = ENOBUFS;
562 			goto out;
563 		}
564 		/*
565 		 * m_copypack left space for our hdr; use it.
566 		 */
567 		m->m_len += hdrlen;
568 		m->m_data -= hdrlen;
569 #else
570 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
571 		if (m == NULL) {
572 			error = ENOBUFS;
573 			goto out;
574 		}
575 #ifdef INET6
576 		if (MHLEN < hdrlen + max_linkhdr) {
577 			MCLGET(m, M_DONTWAIT);
578 			if ((m->m_flags & M_EXT) == 0) {
579 				m_freem(m);
580 				error = ENOBUFS;
581 				goto out;
582 			}
583 		}
584 #endif
585 		m->m_data += max_linkhdr;
586 		m->m_len = hdrlen;
587 		if (len <= MHLEN - hdrlen - max_linkhdr) {
588 			m_copydata(so->so_snd.sb_mb, off, (int) len,
589 			    mtod(m, caddr_t) + hdrlen);
590 			m->m_len += len;
591 		} else {
592 			m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
593 			if (m->m_next == 0) {
594 				(void) m_free(m);
595 				error = ENOBUFS;
596 				goto out;
597 			}
598 		}
599 #endif
600 		/*
601 		 * If we're sending everything we've got, set PUSH.
602 		 * (This will keep happy those implementations which only
603 		 * give data to the user when a buffer fills or
604 		 * a PUSH comes in.)
605 		 */
606 		if (off + len == so->so_snd.sb_cc)
607 			flags |= TH_PUSH;
608 	} else {
609 		if (tp->t_flags & TF_ACKNOW)
610 			tcpstat.tcps_sndacks++;
611 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
612 			tcpstat.tcps_sndctrl++;
613 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
614 			tcpstat.tcps_sndurg++;
615 		else
616 			tcpstat.tcps_sndwinup++;
617 
618 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
619 		if (m == NULL) {
620 			error = ENOBUFS;
621 			goto out;
622 		}
623 #ifdef INET6
624 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
625 		    MHLEN >= hdrlen) {
626 			MH_ALIGN(m, hdrlen);
627 		} else
628 #endif
629 		m->m_data += max_linkhdr;
630 		m->m_len = hdrlen;
631 	}
632 	m->m_pkthdr.rcvif = (struct ifnet *)0;
633 	if (tp->t_template == 0)
634 		panic("tcp_output");
635 #ifdef INET6
636 	if (isipv6) {
637 		ip6 = mtod(m, struct ip6_hdr *);
638 		th = (struct tcphdr *)(ip6 + 1);
639 		bcopy((caddr_t)tp->t_template->tt_ipgen, (caddr_t)ip6,
640 		      sizeof(struct ip6_hdr));
641 		bcopy((caddr_t)&tp->t_template->tt_t, (caddr_t)th,
642 		      sizeof(struct tcphdr));
643 	} else
644 #endif /* INET6 */
645       {
646 	ip = mtod(m, struct ip *);
647 	ipov = (struct ipovly *)ip;
648 	th = (struct tcphdr *)(ip + 1);
649 	/* this picks up the pseudo header (w/o the length) */
650 	bcopy((caddr_t)tp->t_template->tt_ipgen, (caddr_t)ip,
651 	      sizeof(struct ip));
652 	bcopy((caddr_t)&tp->t_template->tt_t, (caddr_t)th,
653 	      sizeof(struct tcphdr));
654       }
655 
656 	/*
657 	 * Fill in fields, remembering maximum advertised
658 	 * window for use in delaying messages about window sizes.
659 	 * If resending a FIN, be sure not to use a new sequence number.
660 	 */
661 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
662 	    tp->snd_nxt == tp->snd_max)
663 		tp->snd_nxt--;
664 	/*
665 	 * If we are doing retransmissions, then snd_nxt will
666 	 * not reflect the first unsent octet.  For ACK only
667 	 * packets, we do not want the sequence number of the
668 	 * retransmitted packet, we want the sequence number
669 	 * of the next unsent octet.  So, if there is no data
670 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
671 	 * when filling in ti_seq.  But if we are in persist
672 	 * state, snd_max might reflect one byte beyond the
673 	 * right edge of the window, so use snd_nxt in that
674 	 * case, since we know we aren't doing a retransmission.
675 	 * (retransmit and persist are mutually exclusive...)
676 	 */
677 	if (len || (flags & (TH_SYN|TH_FIN))
678 	    || callout_active(tp->tt_persist))
679 		th->th_seq = htonl(tp->snd_nxt);
680 	else
681 		th->th_seq = htonl(tp->snd_max);
682 	th->th_ack = htonl(tp->rcv_nxt);
683 	if (optlen) {
684 		bcopy(opt, th + 1, optlen);
685 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
686 	}
687 	th->th_flags = flags;
688 	/*
689 	 * Calculate receive window.  Don't shrink window,
690 	 * but avoid silly window syndrome.
691 	 */
692 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)tp->t_maxseg)
693 		win = 0;
694 	if (win < (long)(tp->rcv_adv - tp->rcv_nxt))
695 		win = (long)(tp->rcv_adv - tp->rcv_nxt);
696 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
697 		win = (long)TCP_MAXWIN << tp->rcv_scale;
698 	th->th_win = htons((u_short) (win>>tp->rcv_scale));
699 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
700 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
701 		th->th_flags |= TH_URG;
702 	} else
703 		/*
704 		 * If no urgent pointer to send, then we pull
705 		 * the urgent pointer to the left edge of the send window
706 		 * so that it doesn't drift into the send window on sequence
707 		 * number wraparound.
708 		 */
709 		tp->snd_up = tp->snd_una;		/* drag it along */
710 
711 	/*
712 	 * Put TCP length in extended header, and then
713 	 * checksum extended header and data.
714 	 */
715 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
716 #ifdef INET6
717 	if (isipv6)
718 		/*
719 		 * ip6_plen is not need to be filled now, and will be filled
720 		 * in ip6_output.
721 		 */
722 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
723 				       sizeof(struct tcphdr) + optlen + len);
724 	else
725 #endif /* INET6 */
726       {
727 	m->m_pkthdr.csum_flags = CSUM_TCP;
728 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
729 	if (len + optlen)
730 		th->th_sum = in_addword(th->th_sum,
731 		    htons((u_short)(optlen + len)));
732 
733 	/* IP version must be set here for ipv4/ipv6 checking later */
734 	KASSERT(ip->ip_v == IPVERSION,
735 	    ("%s: IP version incorrect: %d", __FUNCTION__, ip->ip_v));
736       }
737 
738 	/*
739 	 * In transmit state, time the transmission and arrange for
740 	 * the retransmit.  In persist state, just set snd_max.
741 	 */
742 	if (tp->t_force == 0 || !callout_active(tp->tt_persist)) {
743 		tcp_seq startseq = tp->snd_nxt;
744 
745 		/*
746 		 * Advance snd_nxt over sequence space of this segment.
747 		 */
748 		if (flags & (TH_SYN|TH_FIN)) {
749 			if (flags & TH_SYN)
750 				tp->snd_nxt++;
751 			if (flags & TH_FIN) {
752 				tp->snd_nxt++;
753 				tp->t_flags |= TF_SENTFIN;
754 			}
755 		}
756 		tp->snd_nxt += len;
757 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
758 			tp->snd_max = tp->snd_nxt;
759 			/*
760 			 * Time this transmission if not a retransmission and
761 			 * not currently timing anything.
762 			 */
763 			if (tp->t_rtttime == 0) {
764 				tp->t_rtttime = ticks;
765 				tp->t_rtseq = startseq;
766 				tcpstat.tcps_segstimed++;
767 			}
768 		}
769 
770 		/*
771 		 * Set retransmit timer if not currently set,
772 		 * and not doing an ack or a keep-alive probe.
773 		 * Initial value for retransmit timer is smoothed
774 		 * round-trip time + 2 * round-trip time variance.
775 		 * Initialize shift counter which is used for backoff
776 		 * of retransmit time.
777 		 */
778 		if (!callout_active(tp->tt_rexmt) &&
779 		    tp->snd_nxt != tp->snd_una) {
780 			if (callout_active(tp->tt_persist)) {
781 				callout_stop(tp->tt_persist);
782 				tp->t_rxtshift = 0;
783 			}
784 			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
785 				      tcp_timer_rexmt, tp);
786 		}
787 	} else
788 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
789 			tp->snd_max = tp->snd_nxt + len;
790 
791 #ifdef TCPDEBUG
792 	/*
793 	 * Trace.
794 	 */
795 	if (so->so_options & SO_DEBUG)
796 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
797 #endif
798 
799 	/*
800 	 * Fill in IP length and desired time to live and
801 	 * send to IP level.  There should be a better way
802 	 * to handle ttl and tos; we could keep them in
803 	 * the template, but need a way to checksum without them.
804 	 */
805 	/*
806 	 * m->m_pkthdr.len should have been set before cksum calcuration,
807 	 * because in6_cksum() need it.
808 	 */
809 #ifdef INET6
810 	if (isipv6) {
811 		/*
812 		 * we separately set hoplimit for every segment, since the
813 		 * user might want to change the value via setsockopt.
814 		 * Also, desired default hop limit might be changed via
815 		 * Neighbor Discovery.
816 		 */
817 		ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb,
818 					       tp->t_inpcb->in6p_route.ro_rt ?
819 					       tp->t_inpcb->in6p_route.ro_rt->rt_ifp
820 					       : NULL);
821 
822 		/* TODO: IPv6 IP6TOS_ECT bit on */
823 #ifdef IPSEC
824 		ipsec_setsocket(m, so);
825 #endif /*IPSEC*/
826 		error = ip6_output(m,
827 			    tp->t_inpcb->in6p_outputopts,
828 			    &tp->t_inpcb->in6p_route,
829 			    (so->so_options & SO_DONTROUTE), NULL, NULL);
830 	} else
831 #endif /* INET6 */
832     {
833 	struct rtentry *rt;
834 	ip->ip_len = m->m_pkthdr.len;
835 #ifdef INET6
836  	if (INP_CHECK_SOCKAF(so, AF_INET6))
837  		ip->ip_ttl = in6_selecthlim(tp->t_inpcb,
838  					    tp->t_inpcb->in6p_route.ro_rt ?
839  					    tp->t_inpcb->in6p_route.ro_rt->rt_ifp
840  					    : NULL);
841  	else
842 #endif /* INET6 */
843 	ip->ip_ttl = tp->t_inpcb->inp_ip_ttl;	/* XXX */
844 	ip->ip_tos = tp->t_inpcb->inp_ip_tos;	/* XXX */
845 	/*
846 	 * See if we should do MTU discovery.  We do it only if the following
847 	 * are true:
848 	 *	1) we have a valid route to the destination
849 	 *	2) the MTU is not locked (if it is, then discovery has been
850 	 *	   disabled)
851 	 */
852 	if (path_mtu_discovery
853 	    && (rt = tp->t_inpcb->inp_route.ro_rt)
854 	    && rt->rt_flags & RTF_UP
855 	    && !(rt->rt_rmx.rmx_locks & RTV_MTU)) {
856 		ip->ip_off |= IP_DF;
857 	}
858 #ifdef IPSEC
859  	ipsec_setsocket(m, so);
860 #endif /*IPSEC*/
861 	error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
862 	    (so->so_options & SO_DONTROUTE), 0);
863     }
864 	if (error) {
865 
866 		/*
867 		 * We know that the packet was lost, so back out the
868 		 * sequence number advance, if any.
869 		 */
870 		if (tp->t_force == 0 || !callout_active(tp->tt_persist)) {
871 			/*
872 			 * No need to check for TH_FIN here because
873 			 * the TF_SENTFIN flag handles that case.
874 			 */
875 			if ((flags & TH_SYN) == 0)
876 				tp->snd_nxt -= len;
877 		}
878 
879 out:
880 		if (error == ENOBUFS) {
881 	                if (!callout_active(tp->tt_rexmt) &&
882                             !callout_active(tp->tt_persist))
883 	                        callout_reset(tp->tt_rexmt, tp->t_rxtcur,
884                                       tcp_timer_rexmt, tp);
885 			tcp_quench(tp->t_inpcb, 0);
886 			return (0);
887 		}
888 		if (error == EMSGSIZE) {
889 			/*
890 			 * ip_output() will have already fixed the route
891 			 * for us.  tcp_mtudisc() will, as its last action,
892 			 * initiate retransmission, so it is important to
893 			 * not do so here.
894 			 */
895 			tcp_mtudisc(tp->t_inpcb, 0);
896 			return 0;
897 		}
898 		if ((error == EHOSTUNREACH || error == ENETDOWN)
899 		    && TCPS_HAVERCVDSYN(tp->t_state)) {
900 			tp->t_softerror = error;
901 			return (0);
902 		}
903 		return (error);
904 	}
905 	tcpstat.tcps_sndtotal++;
906 
907 	/*
908 	 * Data sent (as far as we can tell).
909 	 * If this advertises a larger window than any other segment,
910 	 * then remember the size of the advertised window.
911 	 * Any pending ACK has now been sent.
912 	 */
913 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
914 		tp->rcv_adv = tp->rcv_nxt + win;
915 	tp->last_ack_sent = tp->rcv_nxt;
916 	tp->t_flags &= ~TF_ACKNOW;
917 	if (tcp_delack_enabled)
918 		callout_stop(tp->tt_delack);
919 	if (sendalot && (!tcp_do_newreno || --maxburst))
920 		goto again;
921 	return (0);
922 }
923 
924 void
925 tcp_setpersist(tp)
926 	register struct tcpcb *tp;
927 {
928 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
929 	int tt;
930 
931 	if (callout_active(tp->tt_rexmt))
932 		panic("tcp_setpersist: retransmit pending");
933 	/*
934 	 * Start/restart persistance timer.
935 	 */
936 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
937 		      TCPTV_PERSMIN, TCPTV_PERSMAX);
938 	callout_reset(tp->tt_persist, tt, tcp_timer_persist, tp);
939 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
940 		tp->t_rxtshift++;
941 }
942