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