xref: /openbsd-src/sys/netinet/tcp_output.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /*	$OpenBSD: tcp_output.c,v 1.123 2017/10/25 12:38:21 job Exp $	*/
2 /*	$NetBSD: tcp_output.c,v 1.16 1997/06/03 16:17:09 kml Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include "pf.h"
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/mbuf.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/kernel.h>
80 
81 #include <net/route.h>
82 
83 #include <netinet/in.h>
84 #include <netinet/ip.h>
85 #include <netinet/in_pcb.h>
86 #include <netinet/ip_var.h>
87 #include <netinet/tcp.h>
88 #define	TCPOUTFLAGS
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcp_debug.h>
94 
95 #ifdef notyet
96 extern struct mbuf *m_copypack();
97 #endif
98 
99 extern int tcprexmtthresh;
100 
101 #ifdef TCP_SACK_DEBUG
102 void tcp_print_holes(struct tcpcb *tp);
103 
104 void
105 tcp_print_holes(struct tcpcb *tp)
106 {
107 	struct sackhole *p = tp->snd_holes;
108 	if (p == NULL)
109 		return;
110 	printf("Hole report: start--end dups rxmit\n");
111 	while (p) {
112 		printf("%x--%x d %d r %x\n", p->start, p->end, p->dups,
113 		    p->rxmit);
114 		p = p->next;
115 	}
116 	printf("\n");
117 }
118 #endif /* TCP_SACK_DEBUG */
119 
120 /*
121  * Returns pointer to a sackhole if there are any pending retransmissions;
122  * NULL otherwise.
123  */
124 struct sackhole *
125 tcp_sack_output(struct tcpcb *tp)
126 {
127 	struct sackhole *p;
128 
129 	if (!tp->sack_enable)
130 		return (NULL);
131 	p = tp->snd_holes;
132 	while (p) {
133 		if (p->dups >= tcprexmtthresh && SEQ_LT(p->rxmit, p->end)) {
134 			if (SEQ_LT(p->rxmit, tp->snd_una)) {/* old SACK hole */
135 				p = p->next;
136 				continue;
137 			}
138 #ifdef TCP_SACK_DEBUG
139 			if (p)
140 				tcp_print_holes(tp);
141 #endif
142 			return (p);
143 		}
144 		p = p->next;
145 	}
146 	return (NULL);
147 }
148 
149 /*
150  * After a timeout, the SACK list may be rebuilt.  This SACK information
151  * should be used to avoid retransmitting SACKed data.  This function
152  * traverses the SACK list to see if snd_nxt should be moved forward.
153  */
154 
155 void
156 tcp_sack_adjust(struct tcpcb *tp)
157 {
158 	struct sackhole *cur = tp->snd_holes;
159 	if (cur == NULL)
160 		return; /* No holes */
161 	if (SEQ_GEQ(tp->snd_nxt, tp->rcv_lastsack))
162 		return; /* We're already beyond any SACKed blocks */
163 	/*
164 	 * Two cases for which we want to advance snd_nxt:
165 	 * i) snd_nxt lies between end of one hole and beginning of another
166 	 * ii) snd_nxt lies between end of last hole and rcv_lastsack
167 	 */
168 	while (cur->next) {
169 		if (SEQ_LT(tp->snd_nxt, cur->end))
170 			return;
171 		if (SEQ_GEQ(tp->snd_nxt, cur->next->start))
172 			cur = cur->next;
173 		else {
174 			tp->snd_nxt = cur->next->start;
175 			return;
176 		}
177 	}
178 	if (SEQ_LT(tp->snd_nxt, cur->end))
179 		return;
180 	tp->snd_nxt = tp->rcv_lastsack;
181 	return;
182 }
183 
184 /*
185  * Tcp output routine: figure out what should be sent and send it.
186  */
187 int
188 tcp_output(struct tcpcb *tp)
189 {
190 	struct socket *so = tp->t_inpcb->inp_socket;
191 	long len, win, txmaxseg;
192 	int off, flags, error;
193 	struct mbuf *m;
194 	struct tcphdr *th;
195 	u_int32_t optbuf[howmany(MAX_TCPOPTLEN, sizeof(u_int32_t))];
196 	u_char *opt = (u_char *)optbuf;
197 	unsigned int optlen, hdrlen, packetlen;
198 	int idle, sendalot = 0;
199 	int i, sack_rxmit = 0;
200 	struct sackhole *p;
201 	int maxburst = TCP_MAXBURST;
202 #ifdef TCP_SIGNATURE
203 	unsigned int sigoff;
204 #endif /* TCP_SIGNATURE */
205 #ifdef TCP_ECN
206 	int needect;
207 #endif
208 
209 	if (tp->t_flags & TF_BLOCKOUTPUT) {
210 		tp->t_flags |= TF_NEEDOUTPUT;
211 		return (0);
212 	} else
213 		tp->t_flags &= ~TF_NEEDOUTPUT;
214 
215 #if defined(TCP_SIGNATURE) && defined(DIAGNOSTIC)
216 	if (tp->sack_enable && (tp->t_flags & TF_SIGNATURE))
217 		return (EINVAL);
218 #endif /* defined(TCP_SIGNATURE) && defined(DIAGNOSTIC) */
219 
220 	/*
221 	 * Determine length of data that should be transmitted,
222 	 * and flags that will be used.
223 	 * If there is some data or critical controls (SYN, RST)
224 	 * to send, then transmit; otherwise, investigate further.
225 	 */
226 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
227 	if (idle && (tcp_now - tp->t_rcvtime) >= tp->t_rxtcur)
228 		/*
229 		 * We have been idle for "a while" and no acks are
230 		 * expected to clock out any data we send --
231 		 * slow start to get ack "clock" running again.
232 		 */
233 		tp->snd_cwnd = 2 * tp->t_maxseg;
234 
235 	/* remember 'idle' for next invocation of tcp_output */
236 	if (idle && soissending(so)) {
237 		tp->t_flags |= TF_LASTIDLE;
238 		idle = 0;
239 	} else
240 		tp->t_flags &= ~TF_LASTIDLE;
241 
242 again:
243 	/*
244 	 * If we've recently taken a timeout, snd_max will be greater than
245 	 * snd_nxt.  There may be SACK information that allows us to avoid
246 	 * resending already delivered data.  Adjust snd_nxt accordingly.
247 	 */
248 	if (tp->sack_enable && SEQ_LT(tp->snd_nxt, tp->snd_max))
249 		tcp_sack_adjust(tp);
250 	off = tp->snd_nxt - tp->snd_una;
251 	win = ulmin(tp->snd_wnd, tp->snd_cwnd);
252 
253 	flags = tcp_outflags[tp->t_state];
254 
255 	/*
256 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
257 	 * to send out new data (when sendalot is 1), bypass this function.
258 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
259 	 * we're replacing a (future) new transmission with a retransmission
260 	 * now, and we previously incremented snd_cwnd in tcp_input().
261 	 */
262 	if (tp->sack_enable && !sendalot) {
263 		if (tp->t_dupacks >= tcprexmtthresh &&
264 		    (p = tcp_sack_output(tp))) {
265 			off = p->rxmit - tp->snd_una;
266 			sack_rxmit = 1;
267 			/* Coalesce holes into a single retransmission */
268 			len = min(tp->t_maxseg, p->end - p->rxmit);
269 			if (SEQ_LT(tp->snd_una, tp->snd_last))
270 				tp->snd_cwnd -= tp->t_maxseg;
271 		}
272 	}
273 
274 	sendalot = 0;
275 	/*
276 	 * If in persist timeout with window of 0, send 1 byte.
277 	 * Otherwise, if window is small but nonzero
278 	 * and timer expired, we will send what we can
279 	 * and go to transmit state.
280 	 */
281 	if (tp->t_force) {
282 		if (win == 0) {
283 			/*
284 			 * If we still have some data to send, then
285 			 * clear the FIN bit.  Usually this would
286 			 * happen below when it realizes that we
287 			 * aren't sending all the data.  However,
288 			 * if we have exactly 1 byte of unset data,
289 			 * then it won't clear the FIN bit below,
290 			 * and if we are in persist state, we wind
291 			 * up sending the packet without recording
292 			 * that we sent the FIN bit.
293 			 *
294 			 * We can't just blindly clear the FIN bit,
295 			 * because if we don't have any more data
296 			 * to send then the probe will be the FIN
297 			 * itself.
298 			 */
299 			if (off < so->so_snd.sb_cc)
300 				flags &= ~TH_FIN;
301 			win = 1;
302 		} else {
303 			TCP_TIMER_DISARM(tp, TCPT_PERSIST);
304 			tp->t_rxtshift = 0;
305 		}
306 	}
307 
308 	if (!sack_rxmit) {
309 		len = ulmin(so->so_snd.sb_cc, win) - off;
310 	}
311 
312 	if (len < 0) {
313 		/*
314 		 * If FIN has been sent but not acked,
315 		 * but we haven't been called to retransmit,
316 		 * len will be -1.  Otherwise, window shrank
317 		 * after we sent into it.  If window shrank to 0,
318 		 * cancel pending retransmit, pull snd_nxt back
319 		 * to (closed) window, and set the persist timer
320 		 * if it isn't already going.  If the window didn't
321 		 * close completely, just wait for an ACK.
322 		 */
323 		len = 0;
324 		if (win == 0) {
325 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
326 			tp->t_rxtshift = 0;
327 			tp->snd_nxt = tp->snd_una;
328 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
329 				tcp_setpersist(tp);
330 		}
331 	}
332 
333         /*
334          * Never send more than half a buffer full.  This insures that we can
335          * always keep 2 packets on the wire, no matter what SO_SNDBUF is, and
336          * therefore acks will never be delayed unless we run out of data to
337          * transmit.
338          */
339 	txmaxseg = ulmin(so->so_snd.sb_hiwat / 2, tp->t_maxseg);
340 
341 	if (len > txmaxseg) {
342 		len = txmaxseg;
343 		sendalot = 1;
344 	}
345 	if (off + len < so->so_snd.sb_cc)
346 		flags &= ~TH_FIN;
347 
348 	win = sbspace(so, &so->so_rcv);
349 
350 	/*
351 	 * Sender silly window avoidance.  If connection is idle
352 	 * and can send all data, a maximum segment,
353 	 * at least a maximum default-size segment do it,
354 	 * or are forced, do it; otherwise don't bother.
355 	 * If peer's buffer is tiny, then send
356 	 * when window is at least half open.
357 	 * If retransmitting (possibly after persist timer forced us
358 	 * to send into a small window), then must resend.
359 	 */
360 	if (len) {
361 		if (len == txmaxseg)
362 			goto send;
363 		if ((idle || (tp->t_flags & TF_NODELAY)) &&
364 		    len + off >= so->so_snd.sb_cc && !soissending(so) &&
365 		    (tp->t_flags & TF_NOPUSH) == 0)
366 			goto send;
367 		if (tp->t_force)
368 			goto send;
369 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
370 			goto send;
371 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
372 			goto send;
373 		if (sack_rxmit)
374 			goto send;
375 	}
376 
377 	/*
378 	 * Compare available window to amount of window
379 	 * known to peer (as advertised window less
380 	 * next expected input).  If the difference is at least two
381 	 * max size segments, or at least 50% of the maximum possible
382 	 * window, then want to send a window update to peer.
383 	 */
384 	if (win > 0) {
385 		/*
386 		 * "adv" is the amount we can increase the window,
387 		 * taking into account that we are limited by
388 		 * TCP_MAXWIN << tp->rcv_scale.
389 		 */
390 		long adv = lmin(win, (long)TCP_MAXWIN << tp->rcv_scale) -
391 			(tp->rcv_adv - tp->rcv_nxt);
392 
393 		if (adv >= (long) (2 * tp->t_maxseg))
394 			goto send;
395 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
396 			goto send;
397 	}
398 
399 	/*
400 	 * Send if we owe peer an ACK.
401 	 */
402 	if (tp->t_flags & TF_ACKNOW)
403 		goto send;
404 	if (flags & (TH_SYN|TH_RST))
405 		goto send;
406 	if (SEQ_GT(tp->snd_up, tp->snd_una))
407 		goto send;
408 	/*
409 	 * If our state indicates that FIN should be sent
410 	 * and we have not yet done so, or we're retransmitting the FIN,
411 	 * then we need to send.
412 	 */
413 	if (flags & TH_FIN &&
414 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
415 		goto send;
416 	/*
417 	 * In SACK, it is possible for tcp_output to fail to send a segment
418 	 * after the retransmission timer has been turned off.  Make sure
419 	 * that the retransmission timer is set.
420 	 */
421 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
422 	    TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
423 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
424 		TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
425 		return (0);
426 	}
427 
428 	/*
429 	 * TCP window updates are not reliable, rather a polling protocol
430 	 * using ``persist'' packets is used to insure receipt of window
431 	 * updates.  The three ``states'' for the output side are:
432 	 *	idle			not doing retransmits or persists
433 	 *	persisting		to move a small or zero window
434 	 *	(re)transmitting	and thereby not persisting
435 	 *
436 	 * tp->t_timer[TCPT_PERSIST]
437 	 *	is set when we are in persist state.
438 	 * tp->t_force
439 	 *	is set when we are called to send a persist packet.
440 	 * tp->t_timer[TCPT_REXMT]
441 	 *	is set when we are retransmitting
442 	 * The output side is idle when both timers are zero.
443 	 *
444 	 * If send window is too small, there is data to transmit, and no
445 	 * retransmit or persist is pending, then go to persist state.
446 	 * If nothing happens soon, send when timer expires:
447 	 * if window is nonzero, transmit what we can,
448 	 * otherwise force out a byte.
449 	 */
450 	if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
451 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
452 		tp->t_rxtshift = 0;
453 		tcp_setpersist(tp);
454 	}
455 
456 	/*
457 	 * No reason to send a segment, just return.
458 	 */
459 	return (0);
460 
461 send:
462 	/*
463 	 * Before ESTABLISHED, force sending of initial options
464 	 * unless TCP set not to do any options.
465 	 * NOTE: we assume that the IP/TCP header plus TCP options
466 	 * always fit in a single mbuf, leaving room for a maximum
467 	 * link header, i.e.
468 	 *	max_linkhdr + sizeof(network header) + sizeof(struct tcphdr +
469 	 *		optlen <= MHLEN
470 	 */
471 	optlen = 0;
472 
473 	switch (tp->pf) {
474 	case 0:	/*default to PF_INET*/
475 	case PF_INET:
476 		hdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
477 		break;
478 #ifdef INET6
479 	case PF_INET6:
480 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
481 		break;
482 #endif /* INET6 */
483 	default:
484 		return (EPFNOSUPPORT);
485 	}
486 
487 	if (flags & TH_SYN) {
488 		tp->snd_nxt = tp->iss;
489 		if ((tp->t_flags & TF_NOOPT) == 0) {
490 			u_int16_t mss;
491 
492 			opt[0] = TCPOPT_MAXSEG;
493 			opt[1] = 4;
494 			mss = htons((u_int16_t) tcp_mss(tp, 0));
495 			memcpy(opt + 2, &mss, sizeof(mss));
496 			optlen = 4;
497 
498 			if (flags & TH_ACK)
499 				tcp_mss_update(tp);
500 			/*
501 			 * If this is the first SYN of connection (not a SYN
502 			 * ACK), include SACK_PERMIT_HDR option.  If this is a
503 			 * SYN ACK, include SACK_PERMIT_HDR option if peer has
504 			 * already done so.
505 			 */
506 			if (tp->sack_enable && ((flags & TH_ACK) == 0 ||
507 			    (tp->t_flags & TF_SACK_PERMIT))) {
508 				*((u_int32_t *) (opt + optlen)) =
509 				    htonl(TCPOPT_SACK_PERMIT_HDR);
510 				optlen += 4;
511 			}
512 			if ((tp->t_flags & TF_REQ_SCALE) &&
513 			    ((flags & TH_ACK) == 0 ||
514 			    (tp->t_flags & TF_RCVD_SCALE))) {
515 				*((u_int32_t *) (opt + optlen)) = htonl(
516 					TCPOPT_NOP << 24 |
517 					TCPOPT_WINDOW << 16 |
518 					TCPOLEN_WINDOW << 8 |
519 					tp->request_r_scale);
520 				optlen += 4;
521 			}
522 		}
523 	}
524 
525 	/*
526 	 * Send a timestamp and echo-reply if this is a SYN and our side
527 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
528 	 * and our peer have sent timestamps in our SYN's.
529 	 */
530 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
531 	     (flags & TH_RST) == 0 &&
532 	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
533 	     (tp->t_flags & TF_RCVD_TSTMP))) {
534 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
535 
536 		/* Form timestamp option as shown in appendix A of RFC 1323. */
537 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
538 		*lp++ = htonl(tcp_now + tp->ts_modulate);
539 		*lp   = htonl(tp->ts_recent);
540 		optlen += TCPOLEN_TSTAMP_APPA;
541 
542 		/* Set receive buffer autosizing timestamp. */
543 		if (tp->rfbuf_ts == 0)
544 			tp->rfbuf_ts = tcp_now;
545 
546 	}
547 
548 #ifdef TCP_SIGNATURE
549 	if (tp->t_flags & TF_SIGNATURE) {
550 		u_int8_t *bp = (u_int8_t *)(opt + optlen);
551 
552 		/* Send signature option */
553 		*(bp++) = TCPOPT_SIGNATURE;
554 		*(bp++) = TCPOLEN_SIGNATURE;
555 		sigoff = optlen + 2;
556 
557 		{
558 			unsigned int i;
559 
560 			for (i = 0; i < 16; i++)
561 				*(bp++) = 0;
562 		}
563 
564 
565 		/* Pad options list to the next 32 bit boundary and
566 		 * terminate it.
567 		 */
568 		*bp++ = TCPOPT_NOP;
569 		*bp++ = TCPOPT_NOP;
570 
571 		optlen += TCPOLEN_SIGLEN;
572 	}
573 #endif /* TCP_SIGNATURE */
574 
575 	/*
576 	 * Send SACKs if necessary.  This should be the last option processed.
577 	 * Only as many SACKs are sent as are permitted by the maximum options
578 	 * size.  No more than three SACKs are sent.
579 	 */
580 	if (tp->sack_enable && tp->t_state == TCPS_ESTABLISHED &&
581 	    (tp->t_flags & (TF_SACK_PERMIT|TF_NOOPT)) == TF_SACK_PERMIT &&
582 	    tp->rcv_numsacks) {
583 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
584 		u_int32_t *olp = lp++;
585 		int count = 0;  /* actual number of SACKs inserted */
586 		int maxsack = (MAX_TCPOPTLEN - (optlen + 4))/TCPOLEN_SACK;
587 
588 		tcpstat_inc(tcps_sack_snd_opts);
589 		maxsack = min(maxsack, TCP_MAX_SACK);
590 		for (i = 0; (i < tp->rcv_numsacks && count < maxsack); i++) {
591 			struct sackblk sack = tp->sackblks[i];
592 			if (sack.start == 0 && sack.end == 0)
593 				continue;
594 			*lp++ = htonl(sack.start);
595 			*lp++ = htonl(sack.end);
596 			count++;
597 		}
598 		*olp = htonl(TCPOPT_SACK_HDR|(TCPOLEN_SACK*count+2));
599 		optlen += TCPOLEN_SACK*count + 4; /* including leading NOPs */
600 	}
601 
602 #ifdef DIAGNOSTIC
603 	if (optlen > MAX_TCPOPTLEN)
604 		panic("tcp_output: options too long");
605 #endif /* DIAGNOSTIC */
606 
607 	hdrlen += optlen;
608 
609 	/*
610 	 * Adjust data length if insertion of options will
611 	 * bump the packet length beyond the t_maxopd length.
612 	 */
613 	if (len > tp->t_maxopd - optlen) {
614 		len = tp->t_maxopd - optlen;
615 		sendalot = 1;
616 		flags &= ~TH_FIN;
617 	 }
618 
619 #ifdef DIAGNOSTIC
620 	if (max_linkhdr + hdrlen > MCLBYTES)
621 		panic("tcphdr too big");
622 #endif
623 
624 	/*
625 	 * Grab a header mbuf, attaching a copy of data to
626 	 * be transmitted, and initialize the header from
627 	 * the template for sends on this connection.
628 	 */
629 	if (len) {
630 		if (tp->t_force && len == 1)
631 			tcpstat_inc(tcps_sndprobe);
632 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
633 			tcpstat_pkt(tcps_sndrexmitpack, tcps_sndrexmitbyte,
634 			    len);
635 		} else {
636 			tcpstat_pkt(tcps_sndpack, tcps_sndbyte, len);
637 		}
638 #ifdef notyet
639 		if ((m = m_copypack(so->so_snd.sb_mb, off,
640 		    (int)len, max_linkhdr + hdrlen)) == 0) {
641 			error = ENOBUFS;
642 			goto out;
643 		}
644 		/*
645 		 * m_copypack left space for our hdr; use it.
646 		 */
647 		m->m_len += hdrlen;
648 		m->m_data -= hdrlen;
649 #else
650 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
651 		if (m != NULL && max_linkhdr + hdrlen > MHLEN) {
652 			MCLGET(m, M_DONTWAIT);
653 			if ((m->m_flags & M_EXT) == 0) {
654 				m_freem(m);
655 				m = NULL;
656 			}
657 		}
658 		if (m == NULL) {
659 			error = ENOBUFS;
660 			goto out;
661 		}
662 		m->m_data += max_linkhdr;
663 		m->m_len = hdrlen;
664 		if (len <= M_TRAILINGSPACE(m)) {
665 			m_copydata(so->so_snd.sb_mb, off, (int) len,
666 			    mtod(m, caddr_t) + hdrlen);
667 			m->m_len += len;
668 		} else {
669 			m->m_next = m_copym(so->so_snd.sb_mb, off, (int) len,
670 			    M_NOWAIT);
671 			if (m->m_next == 0) {
672 				(void) m_free(m);
673 				error = ENOBUFS;
674 				goto out;
675 			}
676 		}
677 		if (so->so_snd.sb_mb->m_flags & M_PKTHDR)
678 			m->m_pkthdr.ph_loopcnt =
679 			    so->so_snd.sb_mb->m_pkthdr.ph_loopcnt;
680 #endif
681 		/*
682 		 * If we're sending everything we've got, set PUSH.
683 		 * (This will keep happy those implementations which only
684 		 * give data to the user when a buffer fills or
685 		 * a PUSH comes in.)
686 		 */
687 		if (off + len == so->so_snd.sb_cc && !soissending(so))
688 			flags |= TH_PUSH;
689 	} else {
690 		if (tp->t_flags & TF_ACKNOW)
691 			tcpstat_inc(tcps_sndacks);
692 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
693 			tcpstat_inc(tcps_sndctrl);
694 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
695 			tcpstat_inc(tcps_sndurg);
696 		else
697 			tcpstat_inc(tcps_sndwinup);
698 
699 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
700 		if (m != NULL && max_linkhdr + hdrlen > MHLEN) {
701 			MCLGET(m, M_DONTWAIT);
702 			if ((m->m_flags & M_EXT) == 0) {
703 				m_freem(m);
704 				m = NULL;
705 			}
706 		}
707 		if (m == NULL) {
708 			error = ENOBUFS;
709 			goto out;
710 		}
711 		m->m_data += max_linkhdr;
712 		m->m_len = hdrlen;
713 	}
714 	m->m_pkthdr.ph_ifidx = 0;
715 	m->m_pkthdr.len = hdrlen + len;
716 
717 	if (!tp->t_template)
718 		panic("tcp_output");
719 #ifdef DIAGNOSTIC
720 	if (tp->t_template->m_len != hdrlen - optlen)
721 		panic("tcp_output: template len != hdrlen - optlen");
722 #endif /* DIAGNOSTIC */
723 	memcpy(mtod(m, caddr_t), mtod(tp->t_template, caddr_t),
724 	    tp->t_template->m_len);
725 	th = (struct tcphdr *)(mtod(m, caddr_t) + tp->t_template->m_len -
726 		sizeof(struct tcphdr));
727 
728 	/*
729 	 * Fill in fields, remembering maximum advertised
730 	 * window for use in delaying messages about window sizes.
731 	 * If resending a FIN, be sure not to use a new sequence number.
732 	 */
733 	if ((flags & TH_FIN) && (tp->t_flags & TF_SENTFIN) &&
734 	    (tp->snd_nxt == tp->snd_max))
735 		tp->snd_nxt--;
736 	/*
737 	 * If we are doing retransmissions, then snd_nxt will
738 	 * not reflect the first unsent octet.  For ACK only
739 	 * packets, we do not want the sequence number of the
740 	 * retransmitted packet, we want the sequence number
741 	 * of the next unsent octet.  So, if there is no data
742 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
743 	 * when filling in ti_seq.  But if we are in persist
744 	 * state, snd_max might reflect one byte beyond the
745 	 * right edge of the window, so use snd_nxt in that
746 	 * case, since we know we aren't doing a retransmission.
747 	 * (retransmit and persist are mutually exclusive...)
748 	 */
749 	if (len || (flags & (TH_SYN|TH_FIN)) || TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
750 		th->th_seq = htonl(tp->snd_nxt);
751 	else
752 		th->th_seq = htonl(tp->snd_max);
753 
754 	if (sack_rxmit) {
755 		/*
756 		 * If sendalot was turned on (due to option stuffing), turn it
757 		 * off. Properly set th_seq field.  Advance the ret'x pointer
758 		 * by len.
759 		 */
760 		if (sendalot)
761 			sendalot = 0;
762 		th->th_seq = htonl(p->rxmit);
763 		p->rxmit += len;
764 		tcpstat_pkt(tcps_sack_rexmits, tcps_sack_rexmit_bytes, len);
765 	}
766 
767 	th->th_ack = htonl(tp->rcv_nxt);
768 	if (optlen) {
769 		memcpy(th + 1, opt, optlen);
770 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
771 	}
772 #ifdef TCP_ECN
773 	if (tcp_do_ecn) {
774 		/*
775 		 * if we have received congestion experienced segs,
776 		 * set ECE bit.
777 		 */
778 		if (tp->t_flags & TF_RCVD_CE) {
779 			flags |= TH_ECE;
780 			tcpstat_inc(tcps_ecn_sndece);
781 		}
782 		if (!(tp->t_flags & TF_DISABLE_ECN)) {
783 			/*
784 			 * if this is a SYN seg, set ECE and CWR.
785 			 * set only ECE for SYN-ACK if peer supports ECN.
786 			 */
787 			if ((flags & (TH_SYN|TH_ACK)) == TH_SYN)
788 				flags |= (TH_ECE|TH_CWR);
789 			else if ((tp->t_flags & TF_ECN_PERMIT) &&
790 				 (flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK))
791 				flags |= TH_ECE;
792 		}
793 		/*
794 		 * if we have reduced the congestion window, notify
795 		 * the peer by setting CWR bit.
796 		 */
797 		if ((tp->t_flags & TF_ECN_PERMIT) &&
798 		    (tp->t_flags & TF_SEND_CWR)) {
799 			flags |= TH_CWR;
800 			tp->t_flags &= ~TF_SEND_CWR;
801 			tcpstat_inc(tcps_ecn_sndcwr);
802 		}
803 	}
804 #endif
805 	th->th_flags = flags;
806 
807 	/*
808 	 * Calculate receive window.  Don't shrink window,
809 	 * but avoid silly window syndrome.
810 	 */
811 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)tp->t_maxseg)
812 		win = 0;
813 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
814 		win = (long)TCP_MAXWIN << tp->rcv_scale;
815 	if (win < (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt))
816 		win = (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt);
817 	if (flags & TH_RST)
818 		win = 0;
819 	th->th_win = htons((u_int16_t) (win>>tp->rcv_scale));
820 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
821 		u_int32_t urp = tp->snd_up - tp->snd_nxt;
822 		if (urp > IP_MAXPACKET)
823 			urp = IP_MAXPACKET;
824 		th->th_urp = htons((u_int16_t)urp);
825 		th->th_flags |= TH_URG;
826 	} else
827 		/*
828 		 * If no urgent pointer to send, then we pull
829 		 * the urgent pointer to the left edge of the send window
830 		 * so that it doesn't drift into the send window on sequence
831 		 * number wraparound.
832 		 */
833 		tp->snd_up = tp->snd_una;		/* drag it along */
834 
835 #ifdef TCP_SIGNATURE
836 	if (tp->t_flags & TF_SIGNATURE) {
837 		int iphlen;
838 		union sockaddr_union src, dst;
839 		struct tdb *tdb;
840 
841 		bzero(&src, sizeof(union sockaddr_union));
842 		bzero(&dst, sizeof(union sockaddr_union));
843 
844 		switch (tp->pf) {
845 		case 0:	/*default to PF_INET*/
846 		case AF_INET:
847 			iphlen = sizeof(struct ip);
848 			src.sa.sa_len = sizeof(struct sockaddr_in);
849 			src.sa.sa_family = AF_INET;
850 			src.sin.sin_addr = mtod(m, struct ip *)->ip_src;
851 			dst.sa.sa_len = sizeof(struct sockaddr_in);
852 			dst.sa.sa_family = AF_INET;
853 			dst.sin.sin_addr = mtod(m, struct ip *)->ip_dst;
854 			break;
855 #ifdef INET6
856 		case AF_INET6:
857 			iphlen = sizeof(struct ip6_hdr);
858 			src.sa.sa_len = sizeof(struct sockaddr_in6);
859 			src.sa.sa_family = AF_INET6;
860 			src.sin6.sin6_addr = mtod(m, struct ip6_hdr *)->ip6_src;
861 			dst.sa.sa_len = sizeof(struct sockaddr_in6);
862 			dst.sa.sa_family = AF_INET6;
863 			dst.sin6.sin6_addr = mtod(m, struct ip6_hdr *)->ip6_dst;
864 			break;
865 #endif /* INET6 */
866 		}
867 
868 		tdb = gettdbbysrcdst(rtable_l2(tp->t_inpcb->inp_rtableid),
869 		    0, &src, &dst, IPPROTO_TCP);
870 		if (tdb == NULL) {
871 			m_freem(m);
872 			return (EPERM);
873 		}
874 
875 		if (tcp_signature(tdb, tp->pf, m, th, iphlen, 0,
876 		    mtod(m, caddr_t) + hdrlen - optlen + sigoff) < 0) {
877 			m_freem(m);
878 			return (EINVAL);
879 		}
880 	}
881 #endif /* TCP_SIGNATURE */
882 
883 	/* Defer checksumming until later (ip_output() or hardware) */
884 	m->m_pkthdr.csum_flags |= M_TCP_CSUM_OUT;
885 
886 	/*
887 	 * In transmit state, time the transmission and arrange for
888 	 * the retransmit.  In persist state, just set snd_max.
889 	 */
890 	if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
891 		tcp_seq startseq = tp->snd_nxt;
892 
893 		/*
894 		 * Advance snd_nxt over sequence space of this segment.
895 		 */
896 		if (flags & (TH_SYN|TH_FIN)) {
897 			if (flags & TH_SYN)
898 				tp->snd_nxt++;
899 			if (flags & TH_FIN) {
900 				tp->snd_nxt++;
901 				tp->t_flags |= TF_SENTFIN;
902 			}
903 		}
904 		if (tp->sack_enable) {
905 			if (sack_rxmit && (p->rxmit != tp->snd_nxt)) {
906 				goto timer;
907 			}
908 		}
909 		tp->snd_nxt += len;
910 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
911 			tp->snd_max = tp->snd_nxt;
912 			/*
913 			 * Time this transmission if not a retransmission and
914 			 * not currently timing anything.
915 			 */
916 			if (tp->t_rtttime == 0) {
917 				tp->t_rtttime = tcp_now;
918 				tp->t_rtseq = startseq;
919 				tcpstat_inc(tcps_segstimed);
920 			}
921 		}
922 
923 		/*
924 		 * Set retransmit timer if not currently set,
925 		 * and not doing an ack or a keep-alive probe.
926 		 * Initial value for retransmit timer is smoothed
927 		 * round-trip time + 2 * round-trip time variance.
928 		 * Initialize shift counter which is used for backoff
929 		 * of retransmit time.
930 		 */
931  timer:
932 		if (tp->sack_enable && sack_rxmit &&
933 		    TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
934 		    tp->snd_nxt != tp->snd_max) {
935 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
936 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
937 				TCP_TIMER_DISARM(tp, TCPT_PERSIST);
938 				tp->t_rxtshift = 0;
939 			}
940 		}
941 
942 		if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
943 		    tp->snd_nxt != tp->snd_una) {
944 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
945 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
946 				TCP_TIMER_DISARM(tp, TCPT_PERSIST);
947 				tp->t_rxtshift = 0;
948 			}
949 		}
950 
951 		if (len == 0 && so->so_snd.sb_cc &&
952 		    TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
953 		    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
954 			/*
955 			 * Avoid a situation where we do not set persist timer
956 			 * after a zero window condition. For example:
957 			 * 1) A -> B: packet with enough data to fill the window
958 			 * 2) B -> A: ACK for #1 + new data (0 window
959 			 *    advertisement)
960 			 * 3) A -> B: ACK for #2, 0 len packet
961 			 *
962 			 * In this case, A will not activate the persist timer,
963 			 * because it chose to send a packet. Unless tcp_output
964 			 * is called for some other reason (delayed ack timer,
965 			 * another input packet from B, socket syscall), A will
966 			 * not send zero window probes.
967 			 *
968 			 * So, if you send a 0-length packet, but there is data
969 			 * in the socket buffer, and neither the rexmt or
970 			 * persist timer is already set, then activate the
971 			 * persist timer.
972 			 */
973 			tp->t_rxtshift = 0;
974 			tcp_setpersist(tp);
975 		}
976 	} else
977 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
978 			tp->snd_max = tp->snd_nxt + len;
979 
980 	tcp_update_sndspace(tp);
981 
982 	/*
983 	 * Trace.
984 	 */
985 	if (so->so_options & SO_DEBUG)
986 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, caddr_t), 0,
987 			len);
988 
989 	/*
990 	 * Fill in IP length and desired time to live and
991 	 * send to IP level.  There should be a better way
992 	 * to handle ttl and tos; we could keep them in
993 	 * the template, but need a way to checksum without them.
994 	 */
995 
996 #ifdef TCP_ECN
997 	/*
998 	 * if peer is ECN capable, set the ECT bit in the IP header.
999 	 * but don't set ECT for a pure ack, a retransmit or a window probe.
1000 	 */
1001 	needect = 0;
1002 	if (tcp_do_ecn && (tp->t_flags & TF_ECN_PERMIT)) {
1003 		if (len == 0 || SEQ_LT(tp->snd_nxt, tp->snd_max) ||
1004 		    (tp->t_force && len == 1)) {
1005 			/* don't set ECT */
1006 		} else {
1007 			needect = 1;
1008 			tcpstat_inc(tcps_ecn_sndect);
1009 		}
1010 	}
1011 #endif
1012 
1013 	/* force routing table */
1014 	m->m_pkthdr.ph_rtableid = tp->t_inpcb->inp_rtableid;
1015 
1016 #if NPF > 0
1017 	m->m_pkthdr.pf.inp = tp->t_inpcb;
1018 #endif
1019 
1020 	switch (tp->pf) {
1021 	case 0:	/*default to PF_INET*/
1022 	case AF_INET:
1023 		{
1024 			struct ip *ip;
1025 
1026 			ip = mtod(m, struct ip *);
1027 			ip->ip_len = htons(m->m_pkthdr.len);
1028 			packetlen = m->m_pkthdr.len;
1029 			ip->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;
1030 			ip->ip_tos = tp->t_inpcb->inp_ip.ip_tos;
1031 #ifdef TCP_ECN
1032 			if (needect)
1033 				ip->ip_tos |= IPTOS_ECN_ECT0;
1034 #endif
1035 		}
1036 		error = ip_output(m, tp->t_inpcb->inp_options,
1037 			&tp->t_inpcb->inp_route,
1038 			(ip_mtudisc ? IP_MTUDISC : 0), NULL, tp->t_inpcb, 0);
1039 		break;
1040 #ifdef INET6
1041 	case AF_INET6:
1042 		{
1043 			struct ip6_hdr *ip6;
1044 
1045 			ip6 = mtod(m, struct ip6_hdr *);
1046 			ip6->ip6_plen = m->m_pkthdr.len -
1047 				sizeof(struct ip6_hdr);
1048 			packetlen = m->m_pkthdr.len;
1049 			ip6->ip6_nxt = IPPROTO_TCP;
1050 			ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb);
1051 #ifdef TCP_ECN
1052 			if (needect)
1053 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
1054 #endif
1055 		}
1056 		error = ip6_output(m, tp->t_inpcb->inp_outputopts6,
1057 			  &tp->t_inpcb->inp_route6,
1058 			  0, NULL, tp->t_inpcb);
1059 		break;
1060 #endif /* INET6 */
1061 	}
1062 
1063 	if (error) {
1064 out:
1065 		if (error == ENOBUFS) {
1066 			/*
1067 			 * If the interface queue is full, or IP cannot
1068 			 * get an mbuf, trigger TCP slow start.
1069 			 */
1070 			tp->snd_cwnd = tp->t_maxseg;
1071 			return (0);
1072 		}
1073 		if (error == EMSGSIZE) {
1074 			/*
1075 			 * ip_output() will have already fixed the route
1076 			 * for us.  tcp_mtudisc() will, as its last action,
1077 			 * initiate retransmission, so it is important to
1078 			 * not do so here.
1079 			 */
1080 			tcp_mtudisc(tp->t_inpcb, -1);
1081 			return (0);
1082 		}
1083 		if (error == EACCES)	/* translate pf(4) error for userland */
1084 			error = EHOSTUNREACH;
1085 		if ((error == EHOSTUNREACH || error == ENETDOWN) &&
1086 		    TCPS_HAVERCVDSYN(tp->t_state)) {
1087 			tp->t_softerror = error;
1088 			return (0);
1089 		}
1090 
1091 		/* Restart the delayed ACK timer, if necessary. */
1092 		if (tp->t_flags & TF_DELACK)
1093 			TCP_RESTART_DELACK(tp);
1094 
1095 		return (error);
1096 	}
1097 
1098 	if (packetlen > tp->t_pmtud_mtu_sent)
1099 		tp->t_pmtud_mtu_sent = packetlen;
1100 
1101 	tcpstat_inc(tcps_sndtotal);
1102 	if (tp->t_flags & TF_DELACK)
1103 		tcpstat_inc(tcps_delack);
1104 
1105 	/*
1106 	 * Data sent (as far as we can tell).
1107 	 * If this advertises a larger window than any other segment,
1108 	 * then remember the size of the advertised window.
1109 	 * Any pending ACK has now been sent.
1110 	 */
1111 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
1112 		tp->rcv_adv = tp->rcv_nxt + win;
1113 	tp->last_ack_sent = tp->rcv_nxt;
1114 	tp->t_flags &= ~TF_ACKNOW;
1115 	TCP_CLEAR_DELACK(tp);
1116 	if (sendalot && --maxburst)
1117 		goto again;
1118 	return (0);
1119 }
1120 
1121 void
1122 tcp_setpersist(struct tcpcb *tp)
1123 {
1124 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + TCP_RTT_BASE_SHIFT);
1125 	int nticks;
1126 
1127 	if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
1128 		panic("tcp_output REXMT");
1129 	/*
1130 	 * Start/restart persistence timer.
1131 	 */
1132 	if (t < tp->t_rttmin)
1133 		t = tp->t_rttmin;
1134 	TCPT_RANGESET(nticks, t * tcp_backoff[tp->t_rxtshift],
1135 	    TCPTV_PERSMIN, TCPTV_PERSMAX);
1136 	TCP_TIMER_ARM(tp, TCPT_PERSIST, nticks);
1137 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1138 		tp->t_rxtshift++;
1139 }
1140