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