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