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