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