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