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