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