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