xref: /dragonfly/sys/netinet/tcp_output.c (revision d9f85b33)
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
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 DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
63  * $FreeBSD: src/sys/netinet/tcp_output.c,v 1.39.2.20 2003/01/29 22:45:36 hsu Exp $
64  */
65 
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68 #include "opt_ipsec.h"
69 #include "opt_tcpdebug.h"
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75 #include <sys/mbuf.h>
76 #include <sys/domain.h>
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/in_cksum.h>
81 #include <sys/thread.h>
82 #include <sys/globaldata.h>
83 
84 #include <net/if_var.h>
85 #include <net/route.h>
86 #include <net/netmsg2.h>
87 #include <net/netisr2.h>
88 
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/in_pcb.h>
93 #include <netinet/ip_var.h>
94 #include <netinet6/in6_pcb.h>
95 #include <netinet/ip6.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet/tcp.h>
98 #define	TCPOUTFLAGS
99 #include <netinet/tcp_fsm.h>
100 #include <netinet/tcp_seq.h>
101 #include <netinet/tcp_timer.h>
102 #include <netinet/tcp_timer2.h>
103 #include <netinet/tcp_var.h>
104 #include <netinet/tcpip.h>
105 #ifdef TCPDEBUG
106 #include <netinet/tcp_debug.h>
107 #endif
108 
109 #ifdef IPSEC
110 #include <netinet6/ipsec.h>
111 #endif /*IPSEC*/
112 
113 #ifdef FAST_IPSEC
114 #include <netproto/ipsec/ipsec.h>
115 #define	IPSEC
116 #endif /*FAST_IPSEC*/
117 
118 #ifdef notyet
119 extern struct mbuf *m_copypack();
120 #endif
121 
122 int path_mtu_discovery = 1;
123 SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_RW,
124 	&path_mtu_discovery, 1, "Enable Path MTU Discovery");
125 
126 static int avoid_pure_win_update = 1;
127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, avoid_pure_win_update, CTLFLAG_RW,
128 	&avoid_pure_win_update, 1, "Avoid pure window updates when possible");
129 
130 /*
131  * 1 - enabled for increasing and decreasing the buffer size
132  * 2 - enabled only for increasing the buffer size
133  */
134 int tcp_do_autosndbuf = 1;
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto, CTLFLAG_RW,
136     &tcp_do_autosndbuf, 0, "Enable automatic send buffer sizing");
137 
138 int tcp_autosndbuf_inc = 8*1024;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_inc, CTLFLAG_RW,
140     &tcp_autosndbuf_inc, 0, "Incrementor step size of automatic send buffer");
141 
142 int tcp_autosndbuf_min = 32768;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_min, CTLFLAG_RW,
144     &tcp_autosndbuf_min, 0, "Min size of automatic send buffer");
145 
146 int tcp_autosndbuf_max = 2*1024*1024;
147 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_max, CTLFLAG_RW,
148     &tcp_autosndbuf_max, 0, "Max size of automatic send buffer");
149 
150 int tcp_prio_synack = 1;
151 SYSCTL_INT(_net_inet_tcp, OID_AUTO, prio_synack, CTLFLAG_RW,
152     &tcp_prio_synack, 0, "Prioritize SYN, SYN|ACK and pure ACK");
153 
154 static int tcp_idle_cwv = 1;
155 SYSCTL_INT(_net_inet_tcp, OID_AUTO, idle_cwv, CTLFLAG_RW,
156     &tcp_idle_cwv, 0,
157     "Congestion window validation after idle period (part of RFC2861)");
158 
159 static int tcp_idle_restart = 1;
160 SYSCTL_INT(_net_inet_tcp, OID_AUTO, idle_restart, CTLFLAG_RW,
161     &tcp_idle_restart, 0, "Reset congestion window after idle period");
162 
163 static int tcp_do_tso = 1;
164 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso, CTLFLAG_RW,
165     &tcp_do_tso, 0, "Enable TCP Segmentation Offload (TSO)");
166 
167 static int tcp_fairsend = 4;
168 SYSCTL_INT(_net_inet_tcp, OID_AUTO, fairsend, CTLFLAG_RW,
169     &tcp_fairsend, 0,
170     "Amount of segments sent before yield to other senders or receivers");
171 
172 static void	tcp_idle_cwnd_validate(struct tcpcb *);
173 
174 static int	tcp_tso_getsize(struct tcpcb *tp, u_int *segsz, u_int *hlen);
175 static void	tcp_output_sched(struct tcpcb *tp);
176 
177 /*
178  * Tcp output routine: figure out what should be sent and send it.
179  */
180 int
181 tcp_output(struct tcpcb *tp)
182 {
183 	struct inpcb * const inp = tp->t_inpcb;
184 	struct socket *so = inp->inp_socket;
185 	long len, recvwin, sendwin;
186 	int nsacked = 0;
187 	int off, flags, error = 0;
188 #ifdef TCP_SIGNATURE
189 	int sigoff = 0;
190 #endif
191 	struct mbuf *m;
192 	struct ip *ip;
193 	struct tcphdr *th;
194 	u_char opt[TCP_MAXOLEN];
195 	unsigned int ipoptlen, optlen, hdrlen;
196 	int idle;
197 	boolean_t sendalot;
198 	struct ip6_hdr *ip6;
199 #ifdef INET6
200 	const boolean_t isipv6 = INP_ISIPV6(inp);
201 #else
202 	const boolean_t isipv6 = FALSE;
203 #endif
204 	boolean_t can_tso = FALSE, use_tso;
205 	boolean_t report_sack, idle_cwv = FALSE;
206 	u_int segsz, tso_hlen, tso_lenmax = 0;
207 	int segcnt = 0;
208 	boolean_t need_sched = FALSE;
209 
210 	KKASSERT(so->so_port == &curthread->td_msgport);
211 
212 	/*
213 	 * Determine length of data that should be transmitted,
214 	 * and flags that will be used.
215 	 * If there is some data or critical controls (SYN, RST)
216 	 * to send, then transmit; otherwise, investigate further.
217 	 */
218 
219 	/*
220 	 * If we have been idle for a while, the send congestion window
221 	 * could be no longer representative of the current state of the
222 	 * link; need to validate congestion window.  However, we should
223 	 * not perform congestion window validation here, since we could
224 	 * be asked to send pure ACK.
225 	 */
226 	if (tp->snd_max == tp->snd_una &&
227 	    (ticks - tp->snd_last) >= tp->t_rxtcur && tcp_idle_restart)
228 		idle_cwv = TRUE;
229 
230 	/*
231 	 * Calculate whether the transmit stream was previously idle
232 	 * and adjust TF_LASTIDLE for the next time.
233 	 */
234 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
235 	if (idle && (tp->t_flags & TF_MORETOCOME))
236 		tp->t_flags |= TF_LASTIDLE;
237 	else
238 		tp->t_flags &= ~TF_LASTIDLE;
239 
240 	if (TCP_DO_SACK(tp) && tp->snd_nxt != tp->snd_max &&
241 	    !IN_FASTRECOVERY(tp))
242 		nsacked = tcp_sack_bytes_below(&tp->scb, tp->snd_nxt);
243 
244 	/*
245 	 * Find out whether TSO could be used or not
246 	 *
247 	 * For TSO capable devices, the following assumptions apply to
248 	 * the processing of TCP flags:
249 	 * - If FIN is set on the large TCP segment, the device must set
250 	 *   FIN on the last segment that it creates from the large TCP
251 	 *   segment.
252 	 * - If PUSH is set on the large TCP segment, the device must set
253 	 *   PUSH on the last segment that it creates from the large TCP
254 	 *   segment.
255 	 */
256 #if !defined(IPSEC) && !defined(FAST_IPSEC)
257 	if (tcp_do_tso
258 #ifdef TCP_SIGNATURE
259 	    && (tp->t_flags & TF_SIGNATURE) == 0
260 #endif
261 	) {
262 		if (!isipv6) {
263 			struct rtentry *rt = inp->inp_route.ro_rt;
264 
265 			if (rt != NULL && (rt->rt_flags & RTF_UP) &&
266 			    (rt->rt_ifp->if_hwassist & CSUM_TSO)) {
267 				can_tso = TRUE;
268 				tso_lenmax = rt->rt_ifp->if_tsolen;
269 			}
270 		}
271 	}
272 #endif	/* !IPSEC && !FAST_IPSEC */
273 
274 again:
275 	m = NULL;
276 	ip = NULL;
277 	th = NULL;
278 	ip6 = NULL;
279 
280 	if ((tp->t_flags & (TF_SACK_PERMITTED | TF_NOOPT)) ==
281 		TF_SACK_PERMITTED &&
282 	    (!TAILQ_EMPTY(&tp->t_segq) ||
283 	     tp->reportblk.rblk_start != tp->reportblk.rblk_end))
284 		report_sack = TRUE;
285 	else
286 		report_sack = FALSE;
287 
288 	/* Make use of SACK information when slow-starting after a RTO. */
289 	if (TCP_DO_SACK(tp) && tp->snd_nxt != tp->snd_max &&
290 	    !IN_FASTRECOVERY(tp)) {
291 		tcp_seq old_snd_nxt = tp->snd_nxt;
292 
293 		tcp_sack_skip_sacked(&tp->scb, &tp->snd_nxt);
294 		nsacked += tp->snd_nxt - old_snd_nxt;
295 	}
296 
297 	sendalot = FALSE;
298 	off = tp->snd_nxt - tp->snd_una;
299 	sendwin = min(tp->snd_wnd, tp->snd_cwnd + nsacked);
300 	sendwin = min(sendwin, tp->snd_bwnd);
301 
302 	flags = tcp_outflags[tp->t_state];
303 	/*
304 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
305 	 * state flags.
306 	 */
307 	if (tp->t_flags & TF_NEEDFIN)
308 		flags |= TH_FIN;
309 	if (tp->t_flags & TF_NEEDSYN)
310 		flags |= TH_SYN;
311 
312 	/*
313 	 * If in persist timeout with window of 0, send 1 byte.
314 	 * Otherwise, if window is small but nonzero
315 	 * and timer expired, we will send what we can
316 	 * and go to transmit state.
317 	 */
318 	if (tp->t_flags & TF_FORCE) {
319 		if (sendwin == 0) {
320 			/*
321 			 * If we still have some data to send, then
322 			 * clear the FIN bit.  Usually this would
323 			 * happen below when it realizes that we
324 			 * aren't sending all the data.  However,
325 			 * if we have exactly 1 byte of unsent data,
326 			 * then it won't clear the FIN bit below,
327 			 * and if we are in persist state, we wind
328 			 * up sending the packet without recording
329 			 * that we sent the FIN bit.
330 			 *
331 			 * We can't just blindly clear the FIN bit,
332 			 * because if we don't have any more data
333 			 * to send then the probe will be the FIN
334 			 * itself.
335 			 */
336 			if (off < so->so_snd.ssb_cc)
337 				flags &= ~TH_FIN;
338 			sendwin = 1;
339 		} else {
340 			tcp_callout_stop(tp, tp->tt_persist);
341 			tp->t_rxtshift = 0;
342 		}
343 	}
344 
345 	/*
346 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
347 	 * offset will be > 0 even if so_snd.ssb_cc is 0, resulting in
348 	 * a negative length.  This can also occur when TCP opens up
349 	 * its congestion window while receiving additional duplicate
350 	 * acks after fast-retransmit because TCP will reset snd_nxt
351 	 * to snd_max after the fast-retransmit.
352 	 *
353 	 * A negative length can also occur when we are in the
354 	 * TCPS_SYN_RECEIVED state due to a simultanious connect where
355 	 * our SYN has not been acked yet.
356 	 *
357 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
358 	 * be set to snd_una, the offset will be 0, and the length may
359 	 * wind up 0.
360 	 */
361 	len = (long)ulmin(so->so_snd.ssb_cc, sendwin) - off;
362 
363 	/*
364 	 * Lop off SYN bit if it has already been sent.  However, if this
365 	 * is SYN-SENT state and if segment contains data, suppress sending
366 	 * segment (sending the segment would be an option if we still
367 	 * did TAO and the remote host supported it).
368 	 */
369 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
370 		flags &= ~TH_SYN;
371 		off--, len++;
372 		if (len > 0 && tp->t_state == TCPS_SYN_SENT) {
373 			tp->t_flags &= ~(TF_ACKNOW | TF_XMITNOW);
374 			return 0;
375 		}
376 	}
377 
378 	/*
379 	 * Be careful not to send data and/or FIN on SYN segments.
380 	 * This measure is needed to prevent interoperability problems
381 	 * with not fully conformant TCP implementations.
382 	 */
383 	if (flags & TH_SYN) {
384 		len = 0;
385 		flags &= ~TH_FIN;
386 	}
387 
388 	if (len < 0) {
389 		/*
390 		 * A negative len can occur if our FIN has been sent but not
391 		 * acked, or if we are in a simultanious connect in the
392 		 * TCPS_SYN_RECEIVED state with our SYN sent but not yet
393 		 * acked.
394 		 *
395 		 * If our window has contracted to 0 in the FIN case
396 		 * (which can only occur if we have NOT been called to
397 		 * retransmit as per code a few paragraphs up) then we
398 		 * want to shift the retransmit timer over to the
399 		 * persist timer.
400 		 *
401 		 * However, if we are in the TCPS_SYN_RECEIVED state
402 		 * (the SYN case) we will be in a simultanious connect and
403 		 * the window may be zero degeneratively.  In this case we
404 		 * do not want to shift to the persist timer after the SYN
405 		 * or the SYN+ACK transmission.
406 		 */
407 		len = 0;
408 		if (sendwin == 0 && tp->t_state != TCPS_SYN_RECEIVED) {
409 			tcp_callout_stop(tp, tp->tt_rexmt);
410 			tp->t_rxtshift = 0;
411 			tp->snd_nxt = tp->snd_una;
412 			if (!tcp_callout_active(tp, tp->tt_persist))
413 				tcp_setpersist(tp);
414 		}
415 	}
416 
417 	KASSERT(len >= 0, ("%s: len < 0", __func__));
418 	/*
419 	 * Automatic sizing of send socket buffer.  Often the send buffer
420 	 * size is not optimally adjusted to the actual network conditions
421 	 * at hand (delay bandwidth product).  Setting the buffer size too
422 	 * small limits throughput on links with high bandwidth and high
423 	 * delay (eg. trans-continental/oceanic links).  Setting the
424 	 * buffer size too big consumes too much real kernel memory,
425 	 * especially with many connections on busy servers.
426 	 *
427 	 * The criteria to step up the send buffer one notch are:
428 	 *  1. receive window of remote host is larger than send buffer
429 	 *     (with a fudge factor of 5/4th);
430 	 *  2. hiwat has not significantly exceeded bwnd (inflight)
431 	 *     (bwnd is a maximal value if inflight is disabled).
432 	 *  3. send buffer is filled to 7/8th with data (so we actually
433 	 *     have data to make use of it);
434 	 *  4. hiwat has not hit maximal automatic size;
435 	 *  5. our send window (slow start and cogestion controlled) is
436 	 *     larger than sent but unacknowledged data in send buffer.
437 	 *
438 	 * The remote host receive window scaling factor may limit the
439 	 * growing of the send buffer before it reaches its allowed
440 	 * maximum.
441 	 *
442 	 * It scales directly with slow start or congestion window
443 	 * and does at most one step per received ACK.  This fast
444 	 * scaling has the drawback of growing the send buffer beyond
445 	 * what is strictly necessary to make full use of a given
446 	 * delay*bandwith product.  However testing has shown this not
447 	 * to be much of an problem.  At worst we are trading wasting
448 	 * of available bandwith (the non-use of it) for wasting some
449 	 * socket buffer memory.
450 	 *
451 	 * The criteria for shrinking the buffer is based solely on
452 	 * the inflight code (snd_bwnd).  If inflight is disabled,
453 	 * the buffer will not be shrinked.  Note that snd_bwnd already
454 	 * has a fudge factor.  Our test adds a little hysteresis.
455 	 */
456 	if (tcp_do_autosndbuf && (so->so_snd.ssb_flags & SSB_AUTOSIZE)) {
457 		const int asbinc = tcp_autosndbuf_inc;
458 		const int hiwat = so->so_snd.ssb_hiwat;
459 		const int lowat = so->so_snd.ssb_lowat;
460 		u_long newsize;
461 
462 		if ((tp->snd_wnd / 4 * 5) >= hiwat &&
463 		    so->so_snd.ssb_cc >= (hiwat / 8 * 7) &&
464 		    hiwat < tp->snd_bwnd + hiwat / 10 &&
465 		    hiwat + asbinc < tcp_autosndbuf_max &&
466 		    hiwat < (TCP_MAXWIN << tp->snd_scale) &&
467 		    sendwin >= (so->so_snd.ssb_cc -
468 				(tp->snd_nxt - tp->snd_una))) {
469 			newsize = ulmin(hiwat + asbinc, tcp_autosndbuf_max);
470 			if (!ssb_reserve(&so->so_snd, newsize, so, NULL))
471 				atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
472 #if 0
473 			if (newsize >= (TCP_MAXWIN << tp->snd_scale))
474 				atomic_clear_int(&so->so_snd.ssb_flags, SSB_AUTOSIZE);
475 #endif
476 		} else if ((long)tp->snd_bwnd <
477 			   (long)(hiwat * 3 / 4 - lowat - asbinc) &&
478 			   hiwat > tp->t_maxseg * 2 + asbinc &&
479 			   hiwat + asbinc >= tcp_autosndbuf_min &&
480 			   tcp_do_autosndbuf == 1) {
481 			newsize = ulmax(hiwat - asbinc, tp->t_maxseg * 2);
482 			ssb_reserve(&so->so_snd, newsize, so, NULL);
483 		}
484 	}
485 
486 	/*
487 	 * Don't use TSO, if:
488 	 * - Congestion window needs validation
489 	 * - There are SACK blocks to report
490 	 * - RST or SYN flags is set
491 	 * - URG will be set
492 	 *
493 	 * XXX
494 	 * Checking for SYN|RST looks overkill, just to be safe than sorry
495 	 */
496 	use_tso = can_tso;
497 	if (report_sack || idle_cwv || (flags & (TH_RST | TH_SYN)))
498 		use_tso = FALSE;
499 	if (use_tso) {
500 		tcp_seq ugr_nxt = tp->snd_nxt;
501 
502 		if ((flags & TH_FIN) && (tp->t_flags & TF_SENTFIN) &&
503 		    tp->snd_nxt == tp->snd_max)
504 			--ugr_nxt;
505 
506 		if (SEQ_GT(tp->snd_up, ugr_nxt))
507 			use_tso = FALSE;
508 	}
509 
510 	if (use_tso) {
511 		/*
512 		 * Find out segment size and header length for TSO
513 		 */
514 		error = tcp_tso_getsize(tp, &segsz, &tso_hlen);
515 		if (error)
516 			use_tso = FALSE;
517 	}
518 	if (!use_tso) {
519 		segsz = tp->t_maxseg;
520 		tso_hlen = 0; /* not used */
521 	}
522 
523 	/*
524 	 * Truncate to the maximum segment length if not TSO, and ensure that
525 	 * FIN is removed if the length no longer contains the last data byte.
526 	 */
527 	if (len > segsz) {
528 		if (!use_tso) {
529 			len = segsz;
530 			++segcnt;
531 		} else {
532 			int nsegs;
533 
534 			if (__predict_false(tso_lenmax < segsz))
535 				tso_lenmax = segsz << 1;
536 
537 			/*
538 			 * Truncate TSO transfers to (IP_MAXPACKET - iphlen -
539 			 * thoff), and make sure that we send equal size
540 			 * transfers down the stack (rather than big-small-
541 			 * big-small-...).
542 			 */
543 			len = min(len, tso_lenmax);
544 			nsegs = min(len, (IP_MAXPACKET - tso_hlen)) / segsz;
545 			KKASSERT(nsegs > 0);
546 
547 			len = nsegs * segsz;
548 
549 			if (len <= segsz) {
550 				use_tso = FALSE;
551 				++segcnt;
552 			} else {
553 				segcnt += nsegs;
554 			}
555 		}
556 		sendalot = TRUE;
557 	} else {
558 		use_tso = FALSE;
559 		if (len > 0)
560 			++segcnt;
561 	}
562 	if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.ssb_cc))
563 		flags &= ~TH_FIN;
564 
565 	recvwin = ssb_space(&so->so_rcv);
566 
567 	/*
568 	 * Sender silly window avoidance.   We transmit under the following
569 	 * conditions when len is non-zero:
570 	 *
571 	 *	- We have a full segment
572 	 *	- This is the last buffer in a write()/send() and we are
573 	 *	  either idle or running NODELAY
574 	 *	- we've timed out (e.g. persist timer)
575 	 *	- we have more then 1/2 the maximum send window's worth of
576 	 *	  data (receiver may be limiting the window size)
577 	 *	- we need to retransmit
578 	 */
579 	if (len) {
580 		if (len >= segsz)
581 			goto send;
582 		/*
583 		 * NOTE! on localhost connections an 'ack' from the remote
584 		 * end may occur synchronously with the output and cause
585 		 * us to flush a buffer queued with moretocome.  XXX
586 		 *
587 		 * note: the len + off check is almost certainly unnecessary.
588 		 */
589 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
590 		    (idle || (tp->t_flags & TF_NODELAY)) &&
591 		    len + off >= so->so_snd.ssb_cc &&
592 		    !(tp->t_flags & TF_NOPUSH)) {
593 			goto send;
594 		}
595 		if (tp->t_flags & TF_FORCE)		/* typ. timeout case */
596 			goto send;
597 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
598 			goto send;
599 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
600 			goto send;
601 		if (tp->t_flags & TF_XMITNOW)
602 			goto send;
603 	}
604 
605 	/*
606 	 * Compare available window to amount of window
607 	 * known to peer (as advertised window less
608 	 * next expected input).  If the difference is at least two
609 	 * max size segments, or at least 50% of the maximum possible
610 	 * window, then want to send a window update to peer.
611 	 */
612 	if (recvwin > 0) {
613 		/*
614 		 * "adv" is the amount we can increase the window,
615 		 * taking into account that we are limited by
616 		 * TCP_MAXWIN << tp->rcv_scale.
617 		 */
618 		long adv = min(recvwin, (long)TCP_MAXWIN << tp->rcv_scale) -
619 			(tp->rcv_adv - tp->rcv_nxt);
620 		long hiwat;
621 
622 		/*
623 		 * This ack case typically occurs when the user has drained
624 		 * the TCP socket buffer sufficiently to warrent an ack
625 		 * containing a 'pure window update'... that is, an ack that
626 		 * ONLY updates the tcp window.
627 		 *
628 		 * It is unclear why we would need to do a pure window update
629 		 * past 2 segments if we are going to do one at 1/2 the high
630 		 * water mark anyway, especially since under normal conditions
631 		 * the user program will drain the socket buffer quickly.
632 		 * The 2-segment pure window update will often add a large
633 		 * number of extra, unnecessary acks to the stream.
634 		 *
635 		 * avoid_pure_win_update now defaults to 1.
636 		 */
637 		if (avoid_pure_win_update == 0 ||
638 		    (tp->t_flags & TF_RXRESIZED)) {
639 			if (adv >= (long) (2 * segsz)) {
640 				goto send;
641 			}
642 		}
643 		hiwat = (long)(TCP_MAXWIN << tp->rcv_scale);
644 		if (hiwat > (long)so->so_rcv.ssb_hiwat)
645 			hiwat = (long)so->so_rcv.ssb_hiwat;
646 		if (adv >= hiwat / 2)
647 			goto send;
648 	}
649 
650 	/*
651 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
652 	 * is also a catch-all for the retransmit timer timeout case.
653 	 */
654 	if (tp->t_flags & TF_ACKNOW)
655 		goto send;
656 	if ((flags & TH_RST) ||
657 	    ((flags & TH_SYN) && !(tp->t_flags & TF_NEEDSYN)))
658 		goto send;
659 	if (SEQ_GT(tp->snd_up, tp->snd_una))
660 		goto send;
661 	/*
662 	 * If our state indicates that FIN should be sent
663 	 * and we have not yet done so, then we need to send.
664 	 */
665 	if ((flags & TH_FIN) &&
666 	    (!(tp->t_flags & TF_SENTFIN) || tp->snd_nxt == tp->snd_una))
667 		goto send;
668 
669 	/*
670 	 * TCP window updates are not reliable, rather a polling protocol
671 	 * using ``persist'' packets is used to insure receipt of window
672 	 * updates.  The three ``states'' for the output side are:
673 	 *	idle			not doing retransmits or persists
674 	 *	persisting		to move a small or zero window
675 	 *	(re)transmitting	and thereby not persisting
676 	 *
677 	 * tcp_callout_active(tp, tp->tt_persist)
678 	 *	is true when we are in persist state.
679 	 * The TF_FORCE flag in tp->t_flags
680 	 *	is set when we are called to send a persist packet.
681 	 * tcp_callout_active(tp, tp->tt_rexmt)
682 	 *	is set when we are retransmitting
683 	 * The output side is idle when both timers are zero.
684 	 *
685 	 * If send window is too small, there is data to transmit, and no
686 	 * retransmit or persist is pending, then go to persist state.
687 	 *
688 	 * If nothing happens soon, send when timer expires:
689 	 * if window is nonzero, transmit what we can, otherwise force out
690 	 * a byte.
691 	 *
692 	 * Don't try to set the persist state if we are in TCPS_SYN_RECEIVED
693 	 * with data pending.  This situation can occur during a
694 	 * simultanious connect.
695 	 */
696 	if (so->so_snd.ssb_cc > 0 &&
697 	    tp->t_state != TCPS_SYN_RECEIVED &&
698 	    !tcp_callout_active(tp, tp->tt_rexmt) &&
699 	    !tcp_callout_active(tp, tp->tt_persist)) {
700 		tp->t_rxtshift = 0;
701 		tcp_setpersist(tp);
702 	}
703 
704 	/*
705 	 * No reason to send a segment, just return.
706 	 */
707 	tp->t_flags &= ~TF_XMITNOW;
708 	return (0);
709 
710 send:
711 	if (need_sched && len > 0) {
712 		tcp_output_sched(tp);
713 		return 0;
714 	}
715 
716 	/*
717 	 * Before ESTABLISHED, force sending of initial options
718 	 * unless TCP set not to do any options.
719 	 * NOTE: we assume that the IP/TCP header plus TCP options
720 	 * always fit in a single mbuf, leaving room for a maximum
721 	 * link header, i.e.
722 	 *	max_linkhdr + sizeof(struct tcpiphdr) + optlen <= MCLBYTES
723 	 */
724 	optlen = 0;
725 	if (isipv6)
726 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
727 	else
728 		hdrlen = sizeof(struct tcpiphdr);
729 	if (flags & TH_SYN) {
730 		tp->snd_nxt = tp->iss;
731 		if (!(tp->t_flags & TF_NOOPT)) {
732 			u_short mss;
733 
734 			opt[0] = TCPOPT_MAXSEG;
735 			opt[1] = TCPOLEN_MAXSEG;
736 			mss = htons((u_short) tcp_mssopt(tp));
737 			memcpy(opt + 2, &mss, sizeof mss);
738 			optlen = TCPOLEN_MAXSEG;
739 
740 			if ((tp->t_flags & TF_REQ_SCALE) &&
741 			    (!(flags & TH_ACK) ||
742 			     (tp->t_flags & TF_RCVD_SCALE))) {
743 				*((u_int32_t *)(opt + optlen)) = htonl(
744 					TCPOPT_NOP << 24 |
745 					TCPOPT_WINDOW << 16 |
746 					TCPOLEN_WINDOW << 8 |
747 					tp->request_r_scale);
748 				optlen += 4;
749 			}
750 
751 			if ((tcp_do_sack && !(flags & TH_ACK)) ||
752 			    tp->t_flags & TF_SACK_PERMITTED) {
753 				uint32_t *lp = (uint32_t *)(opt + optlen);
754 
755 				*lp = htonl(TCPOPT_SACK_PERMITTED_ALIGNED);
756 				optlen += TCPOLEN_SACK_PERMITTED_ALIGNED;
757 			}
758 		}
759 	}
760 
761 	/*
762 	 * Send a timestamp and echo-reply if this is a SYN and our side
763 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
764 	 * and our peer have sent timestamps in our SYN's.
765 	 */
766 	if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
767 	    !(flags & TH_RST) &&
768 	    (!(flags & TH_ACK) || (tp->t_flags & TF_RCVD_TSTMP))) {
769 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
770 
771 		/* Form timestamp option as shown in appendix A of RFC 1323. */
772 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
773 		*lp++ = htonl(ticks);
774 		*lp   = htonl(tp->ts_recent);
775 		optlen += TCPOLEN_TSTAMP_APPA;
776 	}
777 
778 	/* Set receive buffer autosizing timestamp. */
779 	if (tp->rfbuf_ts == 0 && (so->so_rcv.ssb_flags & SSB_AUTOSIZE))
780 		tp->rfbuf_ts = ticks;
781 
782 	/*
783 	 * If this is a SACK connection and we have a block to report,
784 	 * fill in the SACK blocks in the TCP options.
785 	 */
786 	if (report_sack)
787 		tcp_sack_fill_report(tp, opt, &optlen);
788 
789 #ifdef TCP_SIGNATURE
790 	if (tp->t_flags & TF_SIGNATURE) {
791 		int i;
792 		u_char *bp;
793 		/*
794 		 * Initialize TCP-MD5 option (RFC2385)
795 		 */
796 		bp = (u_char *)opt + optlen;
797 		*bp++ = TCPOPT_SIGNATURE;
798 		*bp++ = TCPOLEN_SIGNATURE;
799 		sigoff = optlen + 2;
800 		for (i = 0; i < TCP_SIGLEN; i++)
801 			*bp++ = 0;
802 		optlen += TCPOLEN_SIGNATURE;
803 		/*
804 		 * Terminate options list and maintain 32-bit alignment.
805 		 */
806 		*bp++ = TCPOPT_NOP;
807 		*bp++ = TCPOPT_EOL;
808 		optlen += 2;
809 	}
810 #endif /* TCP_SIGNATURE */
811 	KASSERT(optlen <= TCP_MAXOLEN, ("too many TCP options"));
812 	hdrlen += optlen;
813 
814 	if (isipv6) {
815 		ipoptlen = ip6_optlen(inp);
816 	} else {
817 		if (inp->inp_options) {
818 			ipoptlen = inp->inp_options->m_len -
819 			    offsetof(struct ipoption, ipopt_list);
820 		} else {
821 			ipoptlen = 0;
822 		}
823 	}
824 #ifdef IPSEC
825 	ipoptlen += ipsec_hdrsiz_tcp(tp);
826 #endif
827 
828 	if (use_tso) {
829 		/* TSO segment length must be multiple of segment size */
830 		KASSERT(len >= (2 * segsz) && (len % segsz == 0),
831 		    ("invalid TSO len %ld, segsz %u", len, segsz));
832 	} else {
833 		KASSERT(len <= segsz,
834 		    ("invalid len %ld, segsz %u", len, segsz));
835 
836 		/*
837 		 * Adjust data length if insertion of options will bump
838 		 * the packet length beyond the t_maxopd length.  Clear
839 		 * FIN to prevent premature closure since there is still
840 		 * more data to send after this (now truncated) packet.
841 		 *
842 		 * If just the options do not fit we are in a no-win
843 		 * situation and we treat it as an unreachable host.
844 		 */
845 		if (len + optlen + ipoptlen > tp->t_maxopd) {
846 			if (tp->t_maxopd <= optlen + ipoptlen) {
847 				static time_t last_optlen_report;
848 
849 				if (last_optlen_report != time_uptime) {
850 					last_optlen_report = time_uptime;
851 					kprintf("tcpcb %p: MSS (%d) too "
852 					    "small to hold options!\n",
853 					    tp, tp->t_maxopd);
854 				}
855 				error = EHOSTUNREACH;
856 				goto out;
857 			} else {
858 				flags &= ~TH_FIN;
859 				len = tp->t_maxopd - optlen - ipoptlen;
860 				sendalot = TRUE;
861 			}
862 		}
863 	}
864 
865 #ifdef INET6
866 	KASSERT(max_linkhdr + hdrlen <= MCLBYTES, ("tcphdr too big"));
867 #else
868 	KASSERT(max_linkhdr + hdrlen <= MHLEN, ("tcphdr too big"));
869 #endif
870 
871 	/*
872 	 * Grab a header mbuf, attaching a copy of data to
873 	 * be transmitted, and initialize the header from
874 	 * the template for sends on this connection.
875 	 */
876 	if (len) {
877 		if ((tp->t_flags & TF_FORCE) && len == 1)
878 			tcpstat.tcps_sndprobe++;
879 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
880 			if (tp->snd_nxt == tp->snd_una)
881 				tp->snd_max_rexmt = tp->snd_max;
882 			if (nsacked) {
883 				tcpstat.tcps_sndsackrtopack++;
884 				tcpstat.tcps_sndsackrtobyte += len;
885 			}
886 			tcpstat.tcps_sndrexmitpack++;
887 			tcpstat.tcps_sndrexmitbyte += len;
888 		} else {
889 			tcpstat.tcps_sndpack++;
890 			tcpstat.tcps_sndbyte += len;
891 		}
892 		if (idle_cwv) {
893 			idle_cwv = FALSE;
894 			tcp_idle_cwnd_validate(tp);
895 		}
896 		/* Update last send time after CWV */
897 		tp->snd_last = ticks;
898 #ifdef notyet
899 		if ((m = m_copypack(so->so_snd.ssb_mb, off, (int)len,
900 		    max_linkhdr + hdrlen)) == NULL) {
901 			error = ENOBUFS;
902 			goto after_th;
903 		}
904 		/*
905 		 * m_copypack left space for our hdr; use it.
906 		 */
907 		m->m_len += hdrlen;
908 		m->m_data -= hdrlen;
909 #else
910 #ifndef INET6
911 		m = m_gethdr(M_NOWAIT, MT_HEADER);
912 #else
913 		m = m_getl(hdrlen + max_linkhdr, M_NOWAIT, MT_HEADER,
914 			   M_PKTHDR, NULL);
915 #endif
916 		if (m == NULL) {
917 			error = ENOBUFS;
918 			goto after_th;
919 		}
920 		m->m_data += max_linkhdr;
921 		m->m_len = hdrlen;
922 		if (len <= MHLEN - hdrlen - max_linkhdr) {
923 			m_copydata(so->so_snd.ssb_mb, off, (int) len,
924 			    mtod(m, caddr_t) + hdrlen);
925 			m->m_len += len;
926 		} else {
927 			m->m_next = m_copy(so->so_snd.ssb_mb, off, (int) len);
928 			if (m->m_next == NULL) {
929 				m_free(m);
930 				m = NULL;
931 				error = ENOBUFS;
932 				goto after_th;
933 			}
934 		}
935 #endif
936 		/*
937 		 * If we're sending everything we've got, set PUSH.
938 		 * (This will keep happy those implementations which only
939 		 * give data to the user when a buffer fills or
940 		 * a PUSH comes in.)
941 		 */
942 		if (off + len == so->so_snd.ssb_cc)
943 			flags |= TH_PUSH;
944 	} else {
945 		if (tp->t_flags & TF_ACKNOW)
946 			tcpstat.tcps_sndacks++;
947 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
948 			tcpstat.tcps_sndctrl++;
949 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
950 			tcpstat.tcps_sndurg++;
951 		else
952 			tcpstat.tcps_sndwinup++;
953 
954 		MGETHDR(m, M_NOWAIT, MT_HEADER);
955 		if (m == NULL) {
956 			error = ENOBUFS;
957 			goto after_th;
958 		}
959 		if (isipv6 &&
960 		    (hdrlen + max_linkhdr > MHLEN) && hdrlen <= MHLEN)
961 			MH_ALIGN(m, hdrlen);
962 		else
963 			m->m_data += max_linkhdr;
964 		m->m_len = hdrlen;
965 
966 		/*
967 		 * Prioritize SYN, SYN|ACK and pure ACK.
968 		 * Leave FIN and RST as they are.
969 		 */
970 		if (tcp_prio_synack && (flags & (TH_FIN | TH_RST)) == 0)
971 			m->m_flags |= M_PRIO;
972 	}
973 	m->m_pkthdr.rcvif = NULL;
974 	if (isipv6) {
975 		ip6 = mtod(m, struct ip6_hdr *);
976 		th = (struct tcphdr *)(ip6 + 1);
977 		tcp_fillheaders(tp, ip6, th, use_tso);
978 	} else {
979 		ip = mtod(m, struct ip *);
980 		th = (struct tcphdr *)(ip + 1);
981 		/* this picks up the pseudo header (w/o the length) */
982 		tcp_fillheaders(tp, ip, th, use_tso);
983 	}
984 after_th:
985 	/*
986 	 * Fill in fields, remembering maximum advertised
987 	 * window for use in delaying messages about window sizes.
988 	 * If resending a FIN, be sure not to use a new sequence number.
989 	 */
990 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
991 	    tp->snd_nxt == tp->snd_max)
992 		tp->snd_nxt--;
993 
994 	if (th != NULL) {
995 		/*
996 		 * If we are doing retransmissions, then snd_nxt will
997 		 * not reflect the first unsent octet.  For ACK only
998 		 * packets, we do not want the sequence number of the
999 		 * retransmitted packet, we want the sequence number
1000 		 * of the next unsent octet.  So, if there is no data
1001 		 * (and no SYN or FIN), use snd_max instead of snd_nxt
1002 		 * when filling in ti_seq.  But if we are in persist
1003 		 * state, snd_max might reflect one byte beyond the
1004 		 * right edge of the window, so use snd_nxt in that
1005 		 * case, since we know we aren't doing a retransmission.
1006 		 * (retransmit and persist are mutually exclusive...)
1007 		 */
1008 		if (len || (flags & (TH_SYN|TH_FIN)) ||
1009 		    tcp_callout_active(tp, tp->tt_persist))
1010 			th->th_seq = htonl(tp->snd_nxt);
1011 		else
1012 			th->th_seq = htonl(tp->snd_max);
1013 		th->th_ack = htonl(tp->rcv_nxt);
1014 		if (optlen) {
1015 			bcopy(opt, th + 1, optlen);
1016 			th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1017 		}
1018 		th->th_flags = flags;
1019 	}
1020 
1021 	/*
1022 	 * Calculate receive window.  Don't shrink window, but avoid
1023 	 * silly window syndrome by sending a 0 window if the actual
1024 	 * window is less then one segment.
1025 	 */
1026 	if (recvwin < (long)(so->so_rcv.ssb_hiwat / 4) &&
1027 	    recvwin < (long)segsz)
1028 		recvwin = 0;
1029 	if (recvwin < (tcp_seq_diff_t)(tp->rcv_adv - tp->rcv_nxt))
1030 		recvwin = (tcp_seq_diff_t)(tp->rcv_adv - tp->rcv_nxt);
1031 	if (recvwin > (long)TCP_MAXWIN << tp->rcv_scale)
1032 		recvwin = (long)TCP_MAXWIN << tp->rcv_scale;
1033 
1034 	/*
1035 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
1036 	 * a 0 window.  This may cause the remote transmitter to stall.  This
1037 	 * flag tells soreceive() to disable delayed acknowledgements when
1038 	 * draining the buffer.  This can occur if the receiver is attempting
1039 	 * to read more data then can be buffered prior to transmitting on
1040 	 * the connection.
1041 	 */
1042 	if (recvwin == 0)
1043 		tp->t_flags |= TF_RXWIN0SENT;
1044 	else
1045 		tp->t_flags &= ~TF_RXWIN0SENT;
1046 
1047 	if (th != NULL)
1048 		th->th_win = htons((u_short) (recvwin>>tp->rcv_scale));
1049 
1050 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1051 		KASSERT(!use_tso, ("URG with TSO"));
1052 		if (th != NULL) {
1053 			th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
1054 			th->th_flags |= TH_URG;
1055 		}
1056 	} else {
1057 		/*
1058 		 * If no urgent pointer to send, then we pull
1059 		 * the urgent pointer to the left edge of the send window
1060 		 * so that it doesn't drift into the send window on sequence
1061 		 * number wraparound.
1062 		 */
1063 		tp->snd_up = tp->snd_una;		/* drag it along */
1064 	}
1065 
1066 	if (th != NULL) {
1067 #ifdef TCP_SIGNATURE
1068 		if (tp->t_flags & TF_SIGNATURE) {
1069 			tcpsignature_compute(m, len, optlen,
1070 			    (u_char *)(th + 1) + sigoff, IPSEC_DIR_OUTBOUND);
1071 		}
1072 #endif /* TCP_SIGNATURE */
1073 
1074 		/*
1075 		 * Put TCP length in extended header, and then
1076 		 * checksum extended header and data.
1077 		 */
1078 		m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
1079 		if (isipv6) {
1080 			/*
1081 			 * ip6_plen is not need to be filled now, and will be
1082 			 * filled in ip6_output().
1083 			 */
1084 			th->th_sum = in6_cksum(m, IPPROTO_TCP,
1085 			    sizeof(struct ip6_hdr),
1086 			    sizeof(struct tcphdr) + optlen + len);
1087 		} else {
1088 			m->m_pkthdr.csum_thlen = sizeof(struct tcphdr) + optlen;
1089 			if (use_tso) {
1090 				m->m_pkthdr.csum_flags = CSUM_TSO;
1091 				m->m_pkthdr.tso_segsz = segsz;
1092 			} else {
1093 				m->m_pkthdr.csum_flags = CSUM_TCP;
1094 				m->m_pkthdr.csum_data =
1095 				    offsetof(struct tcphdr, th_sum);
1096 				if (len + optlen) {
1097 					th->th_sum = in_addword(th->th_sum,
1098 					    htons((u_short)(optlen + len)));
1099 				}
1100 			}
1101 
1102 			/*
1103 			 * IP version must be set here for ipv4/ipv6 checking
1104 			 * later
1105 			 */
1106 			KASSERT(ip->ip_v == IPVERSION,
1107 			    ("%s: IP version incorrect: %d",
1108 			     __func__, ip->ip_v));
1109 		}
1110 	}
1111 
1112 	/*
1113 	 * In transmit state, time the transmission and arrange for
1114 	 * the retransmit.  In persist state, just set snd_max.
1115 	 */
1116 	if (!(tp->t_flags & TF_FORCE) ||
1117 	    !tcp_callout_active(tp, tp->tt_persist)) {
1118 		tcp_seq startseq = tp->snd_nxt;
1119 
1120 		/*
1121 		 * Advance snd_nxt over sequence space of this segment.
1122 		 */
1123 		if (flags & (TH_SYN | TH_FIN)) {
1124 			if (flags & TH_SYN)
1125 				tp->snd_nxt++;
1126 			if (flags & TH_FIN) {
1127 				tp->snd_nxt++;
1128 				tp->t_flags |= TF_SENTFIN;
1129 			}
1130 		}
1131 		tp->snd_nxt += len;
1132 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1133 			tp->snd_max = tp->snd_nxt;
1134 			/*
1135 			 * Time this transmission if not a retransmission and
1136 			 * not currently timing anything.
1137 			 */
1138 			if (tp->t_rtttime == 0) {
1139 				tp->t_rtttime = ticks;
1140 				tp->t_rtseq = startseq;
1141 				tcpstat.tcps_segstimed++;
1142 			}
1143 		}
1144 
1145 		/*
1146 		 * Set retransmit timer if not currently set,
1147 		 * and not doing a pure ack or a keep-alive probe.
1148 		 * Initial value for retransmit timer is smoothed
1149 		 * round-trip time + 2 * round-trip time variance.
1150 		 * Initialize shift counter which is used for backoff
1151 		 * of retransmit time.
1152 		 */
1153 		if (!tcp_callout_active(tp, tp->tt_rexmt) &&
1154 		    tp->snd_nxt != tp->snd_una) {
1155 			if (tcp_callout_active(tp, tp->tt_persist)) {
1156 				tcp_callout_stop(tp, tp->tt_persist);
1157 				tp->t_rxtshift = 0;
1158 			}
1159 			tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
1160 			    tcp_timer_rexmt);
1161 		} else if (len == 0 && so->so_snd.ssb_cc &&
1162 			   tp->t_state > TCPS_SYN_RECEIVED &&
1163 			   !tcp_callout_active(tp, tp->tt_rexmt) &&
1164 			   !tcp_callout_active(tp, tp->tt_persist)) {
1165 			/*
1166 			 * Avoid a situation where we do not set persist timer
1167 			 * after a zero window condition. For example:
1168 			 * 1) A -> B: packet with enough data to fill the window
1169 			 * 2) B -> A: ACK for #1 + new data (0 window
1170 			 *    advertisement)
1171 			 * 3) A -> B: ACK for #2, 0 len packet
1172 			 *
1173 			 * In this case, A will not activate the persist timer,
1174 			 * because it chose to send a packet. Unless tcp_output
1175 			 * is called for some other reason (delayed ack timer,
1176 			 * another input packet from B, socket syscall), A will
1177 			 * not send zero window probes.
1178 			 *
1179 			 * So, if you send a 0-length packet, but there is data
1180 			 * in the socket buffer, and neither the rexmt or
1181 			 * persist timer is already set, then activate the
1182 			 * persist timer.
1183 			 */
1184 			tp->t_rxtshift = 0;
1185 			tcp_setpersist(tp);
1186 		}
1187 	} else {
1188 		/*
1189 		 * Persist case, update snd_max but since we are in
1190 		 * persist mode (no window) we do not update snd_nxt.
1191 		 */
1192 		int xlen = len;
1193 		if (flags & TH_SYN)
1194 			panic("tcp_output: persist timer to send SYN");
1195 		if (flags & TH_FIN) {
1196 			++xlen;
1197 			tp->t_flags |= TF_SENTFIN;
1198 		}
1199 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1200 			tp->snd_max = tp->snd_nxt + xlen;
1201 	}
1202 
1203 	if (th != NULL) {
1204 #ifdef TCPDEBUG
1205 		/* Trace. */
1206 		if (so->so_options & SO_DEBUG) {
1207 			tcp_trace(TA_OUTPUT, tp->t_state, tp,
1208 			    mtod(m, void *), th, 0);
1209 		}
1210 #endif
1211 
1212 		/*
1213 		 * Fill in IP length and desired time to live and
1214 		 * send to IP level.  There should be a better way
1215 		 * to handle ttl and tos; we could keep them in
1216 		 * the template, but need a way to checksum without them.
1217 		 */
1218 		/*
1219 		 * m->m_pkthdr.len should have been set before cksum
1220 		 * calcuration, because in6_cksum() need it.
1221 		 */
1222 		if (isipv6) {
1223 			/*
1224 			 * we separately set hoplimit for every segment,
1225 			 * since the user might want to change the value
1226 			 * via setsockopt.  Also, desired default hop
1227 			 * limit might be changed via Neighbor Discovery.
1228 			 */
1229 			ip6->ip6_hlim = in6_selecthlim(inp,
1230 			    (inp->in6p_route.ro_rt ?
1231 			     inp->in6p_route.ro_rt->rt_ifp : NULL));
1232 
1233 			/* TODO: IPv6 IP6TOS_ECT bit on */
1234 			error = ip6_output(m, inp->in6p_outputopts,
1235 			    &inp->in6p_route, (so->so_options & SO_DONTROUTE),
1236 			    NULL, NULL, inp);
1237 		} else {
1238 			struct rtentry *rt;
1239 
1240 			KASSERT(!INP_CHECK_SOCKAF(so, AF_INET6), ("inet6 pcb"));
1241 
1242 			ip->ip_len = m->m_pkthdr.len;
1243 			ip->ip_ttl = inp->inp_ip_ttl;	/* XXX */
1244 			ip->ip_tos = inp->inp_ip_tos;	/* XXX */
1245 			/*
1246 			 * See if we should do MTU discovery.
1247 			 * We do it only if the following are true:
1248 			 *	1) we have a valid route to the destination
1249 			 *	2) the MTU is not locked (if it is,
1250 			 *	   then discovery has been disabled)
1251 			 */
1252 			if (path_mtu_discovery &&
1253 			    (rt = inp->inp_route.ro_rt) &&
1254 			    (rt->rt_flags & RTF_UP) &&
1255 			    !(rt->rt_rmx.rmx_locks & RTV_MTU))
1256 				ip->ip_off |= IP_DF;
1257 
1258 			KASSERT(inp->inp_flags & INP_HASH,
1259 			    ("inpcb has no hash"));
1260 			m_sethash(m, inp->inp_hashval);
1261 			error = ip_output(m, inp->inp_options, &inp->inp_route,
1262 					  (so->so_options & SO_DONTROUTE) |
1263 					  IP_DEBUGROUTE, NULL, inp);
1264 		}
1265 	} else {
1266 		KASSERT(error != 0, ("no error, but th not set"));
1267 	}
1268 	if (error) {
1269 		tp->t_flags &= ~(TF_ACKNOW | TF_XMITNOW);
1270 
1271 		/*
1272 		 * We know that the packet was lost, so back out the
1273 		 * sequence number advance, if any.
1274 		 */
1275 		if (!(tp->t_flags & TF_FORCE) ||
1276 		    !tcp_callout_active(tp, tp->tt_persist)) {
1277 			/*
1278 			 * No need to check for TH_FIN here because
1279 			 * the TF_SENTFIN flag handles that case.
1280 			 */
1281 			if (!(flags & TH_SYN))
1282 				tp->snd_nxt -= len;
1283 		}
1284 
1285 out:
1286 		if (error == ENOBUFS) {
1287 			KASSERT((len == 0 && (flags & (TH_SYN | TH_FIN)) == 0) ||
1288 			    tcp_callout_active(tp, tp->tt_rexmt) ||
1289 			    tcp_callout_active(tp, tp->tt_persist),
1290 			    ("neither rexmt nor persist timer is set"));
1291 			return (0);
1292 		}
1293 		if (error == EMSGSIZE) {
1294 			/*
1295 			 * ip_output() will have already fixed the route
1296 			 * for us.  tcp_mtudisc() will, as its last action,
1297 			 * initiate retransmission, so it is important to
1298 			 * not do so here.
1299 			 */
1300 			tcp_mtudisc(inp, 0);
1301 			return 0;
1302 		}
1303 		if ((error == EHOSTUNREACH || error == ENETDOWN) &&
1304 		    TCPS_HAVERCVDSYN(tp->t_state)) {
1305 			tp->t_softerror = error;
1306 			return (0);
1307 		}
1308 		return (error);
1309 	}
1310 	tcpstat.tcps_sndtotal++;
1311 
1312 	/*
1313 	 * Data sent (as far as we can tell).
1314 	 *
1315 	 * If this advertises a larger window than any other segment,
1316 	 * then remember the size of the advertised window.
1317 	 *
1318 	 * Any pending ACK has now been sent.
1319 	 */
1320 	if (recvwin > 0 && SEQ_GT(tp->rcv_nxt + recvwin, tp->rcv_adv)) {
1321 		tp->rcv_adv = tp->rcv_nxt + recvwin;
1322 		tp->t_flags &= ~TF_RXRESIZED;
1323 	}
1324 	tp->last_ack_sent = tp->rcv_nxt;
1325 	tp->t_flags &= ~(TF_ACKNOW | TF_XMITNOW);
1326 	if (tcp_delack_enabled)
1327 		tcp_callout_stop(tp, tp->tt_delack);
1328 	if (sendalot) {
1329 		if (tcp_fairsend > 0 && (tp->t_flags & TF_FAIRSEND) &&
1330 		    segcnt >= tcp_fairsend)
1331 			need_sched = TRUE;
1332 		goto again;
1333 	}
1334 	return (0);
1335 }
1336 
1337 void
1338 tcp_setpersist(struct tcpcb *tp)
1339 {
1340 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
1341 	int tt;
1342 
1343 	if (tp->t_state == TCPS_SYN_SENT ||
1344 	    tp->t_state == TCPS_SYN_RECEIVED) {
1345 		panic("tcp_setpersist: not established yet, current %s",
1346 		      tp->t_state == TCPS_SYN_SENT ?
1347 		      "SYN_SENT" : "SYN_RECEIVED");
1348 	}
1349 
1350 	if (tcp_callout_active(tp, tp->tt_rexmt))
1351 		panic("tcp_setpersist: retransmit pending");
1352 	/*
1353 	 * Start/restart persistance timer.
1354 	 */
1355 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift], TCPTV_PERSMIN,
1356 		      TCPTV_PERSMAX);
1357 	tcp_callout_reset(tp, tp->tt_persist, tt, tcp_timer_persist);
1358 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1359 		tp->t_rxtshift++;
1360 }
1361 
1362 static void
1363 tcp_idle_cwnd_validate(struct tcpcb *tp)
1364 {
1365 	u_long initial_cwnd = tcp_initial_window(tp);
1366 	u_long min_cwnd;
1367 
1368 	tcpstat.tcps_sndidle++;
1369 
1370 	/* According to RFC5681: RW=min(IW,cwnd) */
1371 	min_cwnd = min(tp->snd_cwnd, initial_cwnd);
1372 
1373 	if (tcp_idle_cwv) {
1374 		u_long idle_time, decay_cwnd;
1375 
1376 		/*
1377 		 * RFC2861, but only after idle period.
1378 		 */
1379 
1380 		/*
1381 		 * Before the congestion window is reduced, ssthresh
1382 		 * is set to the maximum of its current value and 3/4
1383 		 * cwnd.  If the sender then has more data to send
1384 		 * than the decayed cwnd allows, the TCP will slow-
1385 		 * start (perform exponential increase) at least
1386 		 * half-way back up to the old value of cwnd.
1387 		 */
1388 		tp->snd_ssthresh = max(tp->snd_ssthresh,
1389 		    (3 * tp->snd_cwnd) / 4);
1390 
1391 		/*
1392 		 * Decay the congestion window by half for every RTT
1393 		 * that the flow remains inactive.
1394 		 *
1395 		 * The difference between our implementation and
1396 		 * RFC2861 is that we don't allow cwnd to go below
1397 		 * the value allowed by RFC5681 (min_cwnd).
1398 		 */
1399 		idle_time = ticks - tp->snd_last;
1400 		decay_cwnd = tp->snd_cwnd;
1401 		while (idle_time >= tp->t_rxtcur &&
1402 		    decay_cwnd > min_cwnd) {
1403 			decay_cwnd >>= 1;
1404 			idle_time -= tp->t_rxtcur;
1405 		}
1406 		tp->snd_cwnd = max(decay_cwnd, min_cwnd);
1407 	} else {
1408 		/*
1409 		 * Slow-start from scratch to re-determine the send
1410 		 * congestion window.
1411 		 */
1412 		tp->snd_cwnd = min_cwnd;
1413 	}
1414 
1415 	/* Restart ABC counting during congestion avoidance */
1416 	tp->snd_wacked = 0;
1417 }
1418 
1419 static int
1420 tcp_tso_getsize(struct tcpcb *tp, u_int *segsz, u_int *hlen0)
1421 {
1422 	struct inpcb * const inp = tp->t_inpcb;
1423 #ifdef INET6
1424 	const boolean_t isipv6 = INP_ISIPV6(inp);
1425 #else
1426 	const boolean_t isipv6 = FALSE;
1427 #endif
1428 	unsigned int ipoptlen, optlen;
1429 	u_int hlen;
1430 
1431 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
1432 
1433 	if (isipv6) {
1434 		ipoptlen = ip6_optlen(inp);
1435 	} else {
1436 		if (inp->inp_options) {
1437 			ipoptlen = inp->inp_options->m_len -
1438 			    offsetof(struct ipoption, ipopt_list);
1439 		} else {
1440 			ipoptlen = 0;
1441 		}
1442 	}
1443 #ifdef IPSEC
1444 	ipoptlen += ipsec_hdrsiz_tcp(tp);
1445 #endif
1446 	hlen += ipoptlen;
1447 
1448 	optlen = 0;
1449 	if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
1450 	    (tp->t_flags & TF_RCVD_TSTMP))
1451 		optlen += TCPOLEN_TSTAMP_APPA;
1452 	hlen += optlen;
1453 
1454 	if (tp->t_maxopd <= optlen + ipoptlen)
1455 		return EHOSTUNREACH;
1456 
1457 	*segsz = tp->t_maxopd - optlen - ipoptlen;
1458 	*hlen0 = hlen;
1459 	return 0;
1460 }
1461 
1462 static void
1463 tcp_output_sched_handler(netmsg_t nmsg)
1464 {
1465 	struct tcpcb *tp = nmsg->lmsg.u.ms_resultp;
1466 
1467 	/* Reply ASAP */
1468 	crit_enter();
1469 	lwkt_replymsg(&nmsg->lmsg, 0);
1470 	crit_exit();
1471 
1472 	tcp_output_fair(tp);
1473 }
1474 
1475 void
1476 tcp_output_init(struct tcpcb *tp)
1477 {
1478 	netmsg_init(tp->tt_sndmore, NULL, &netisr_adone_rport, MSGF_DROPABLE,
1479 	    tcp_output_sched_handler);
1480 	tp->tt_sndmore->lmsg.u.ms_resultp = tp;
1481 }
1482 
1483 void
1484 tcp_output_cancel(struct tcpcb *tp)
1485 {
1486 	/*
1487 	 * This message is still pending to be processed;
1488 	 * drop it.  Optimized.
1489 	 */
1490 	crit_enter();
1491 	if ((tp->tt_sndmore->lmsg.ms_flags & MSGF_DONE) == 0) {
1492 		lwkt_dropmsg(&tp->tt_sndmore->lmsg);
1493 	}
1494 	crit_exit();
1495 }
1496 
1497 boolean_t
1498 tcp_output_pending(struct tcpcb *tp)
1499 {
1500 	if ((tp->tt_sndmore->lmsg.ms_flags & MSGF_DONE) == 0)
1501 		return TRUE;
1502 	else
1503 		return FALSE;
1504 }
1505 
1506 static void
1507 tcp_output_sched(struct tcpcb *tp)
1508 {
1509 	crit_enter();
1510 	if (tp->tt_sndmore->lmsg.ms_flags & MSGF_DONE)
1511 		lwkt_sendmsg(netisr_cpuport(mycpuid), &tp->tt_sndmore->lmsg);
1512 	crit_exit();
1513 }
1514 
1515 /*
1516  * Fairsend
1517  *
1518  * Yield to other senders or receivers on the same netisr if the current
1519  * TCP stream has sent tcp_fairsend segments and is going to burst more
1520  * segments.  Bursting large amount of segements in a single TCP stream
1521  * could delay other senders' segments and receivers' ACKs quite a lot,
1522  * if others segments and ACKs are queued on to the same hardware transmit
1523  * queue; thus cause unfairness between senders and suppress receiving
1524  * performance.
1525  *
1526  * Fairsend should be performed at the places that do not affect segment
1527  * sending during congestion control, e.g.
1528  * - User requested output
1529  * - ACK input triggered output
1530  *
1531  * NOTE:
1532  * For devices that are TSO capable, their TSO aggregation size limit could
1533  * affect fairsend.
1534  */
1535 int
1536 tcp_output_fair(struct tcpcb *tp)
1537 {
1538 	int ret;
1539 
1540 	tp->t_flags |= TF_FAIRSEND;
1541 	ret = tcp_output(tp);
1542 	tp->t_flags &= ~TF_FAIRSEND;
1543 
1544 	return ret;
1545 }
1546