xref: /freebsd/sys/netinet/tcp_output.c (revision ac952dd274e8895c460c6e937b9f4b095b3f60d5)
1c398230bSWarner Losh /*-
2d7f570e6SGarrett Wollman  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4df8bae1dSRodney W. Grimes  *
5df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
6df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
7df8bae1dSRodney W. Grimes  * are met:
8df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
9df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
10df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
11df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
12df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
13fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
14df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
15df8bae1dSRodney W. Grimes  *    without specific prior written permission.
16df8bae1dSRodney W. Grimes  *
17df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
28df8bae1dSRodney W. Grimes  *
29d7f570e6SGarrett Wollman  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
30df8bae1dSRodney W. Grimes  */
31df8bae1dSRodney W. Grimes 
324b421e2dSMike Silbersack #include <sys/cdefs.h>
334b421e2dSMike Silbersack __FBSDID("$FreeBSD$");
344b421e2dSMike Silbersack 
351cfd4b53SBruce M Simpson #include "opt_inet.h"
36fb59c426SYoshinobu Inoue #include "opt_inet6.h"
373a2a9f79SYoshinobu Inoue #include "opt_ipsec.h"
380cc12cc5SJoerg Wunsch #include "opt_tcpdebug.h"
390cc12cc5SJoerg Wunsch 
40df8bae1dSRodney W. Grimes #include <sys/param.h>
41df8bae1dSRodney W. Grimes #include <sys/systm.h>
42686cdd19SJun-ichiro itojun Hagino #include <sys/domain.h>
43bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
4439bc9de5SLawrence Stewart #include <sys/hhook.h>
45bd79708dSJonathan T. Looney #endif
46fb919e4dSMark Murray #include <sys/kernel.h>
47fb919e4dSMark Murray #include <sys/lock.h>
48fb919e4dSMark Murray #include <sys/mbuf.h>
49fb919e4dSMark Murray #include <sys/mutex.h>
50df8bae1dSRodney W. Grimes #include <sys/protosw.h>
5157f60867SMark Johnston #include <sys/sdt.h>
52df8bae1dSRodney W. Grimes #include <sys/socket.h>
53df8bae1dSRodney W. Grimes #include <sys/socketvar.h>
54fb919e4dSMark Murray #include <sys/sysctl.h>
55df8bae1dSRodney W. Grimes 
564b79449eSBjoern A. Zeeb #include <net/if.h>
57df8bae1dSRodney W. Grimes #include <net/route.h>
58530c0060SRobert Watson #include <net/vnet.h>
59df8bae1dSRodney W. Grimes 
60df8bae1dSRodney W. Grimes #include <netinet/in.h>
6157f60867SMark Johnston #include <netinet/in_kdtrace.h>
62df8bae1dSRodney W. Grimes #include <netinet/in_systm.h>
63df8bae1dSRodney W. Grimes #include <netinet/ip.h>
64df8bae1dSRodney W. Grimes #include <netinet/in_pcb.h>
65df8bae1dSRodney W. Grimes #include <netinet/ip_var.h>
66ef39adf0SAndre Oppermann #include <netinet/ip_options.h>
67fb59c426SYoshinobu Inoue #ifdef INET6
68686cdd19SJun-ichiro itojun Hagino #include <netinet6/in6_pcb.h>
69686cdd19SJun-ichiro itojun Hagino #include <netinet/ip6.h>
70fb59c426SYoshinobu Inoue #include <netinet6/ip6_var.h>
71fb59c426SYoshinobu Inoue #endif
72281a0fd4SPatrick Kelsey #ifdef TCP_RFC7413
73281a0fd4SPatrick Kelsey #include <netinet/tcp_fastopen.h>
74281a0fd4SPatrick Kelsey #endif
752de3e790SGleb Smirnoff #include <netinet/tcp.h>
76df8bae1dSRodney W. Grimes #define	TCPOUTFLAGS
77df8bae1dSRodney W. Grimes #include <netinet/tcp_fsm.h>
78df8bae1dSRodney W. Grimes #include <netinet/tcp_seq.h>
79df8bae1dSRodney W. Grimes #include <netinet/tcp_timer.h>
80df8bae1dSRodney W. Grimes #include <netinet/tcp_var.h>
81df8bae1dSRodney W. Grimes #include <netinet/tcpip.h>
824644fda3SGleb Smirnoff #include <netinet/cc/cc.h>
8386a996e6SHiren Panchasara #ifdef TCPPCAP
8486a996e6SHiren Panchasara #include <netinet/tcp_pcap.h>
8586a996e6SHiren Panchasara #endif
86610ee2f9SDavid Greenman #ifdef TCPDEBUG
87df8bae1dSRodney W. Grimes #include <netinet/tcp_debug.h>
88610ee2f9SDavid Greenman #endif
8909fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
9009fe6320SNavdeep Parhar #include <netinet/tcp_offload.h>
9109fe6320SNavdeep Parhar #endif
92df8bae1dSRodney W. Grimes 
93fcf59617SAndrey V. Elsukov #include <netipsec/ipsec_support.h>
94b9234fafSSam Leffler 
95db4f9cc7SJonathan Lemon #include <machine/in_cksum.h>
96db4f9cc7SJonathan Lemon 
97aed55708SRobert Watson #include <security/mac/mac_framework.h>
98aed55708SRobert Watson 
9982cea7e6SBjoern A. Zeeb VNET_DEFINE(int, path_mtu_discovery) = 1;
1006df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, path_mtu_discovery, CTLFLAG_VNET | CTLFLAG_RW,
101eddfbb76SRobert Watson 	&VNET_NAME(path_mtu_discovery), 1,
102eddfbb76SRobert Watson 	"Enable Path MTU Discovery");
1039a039a5fSDavid Greenman 
10482cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_tso) = 1;
10582cea7e6SBjoern A. Zeeb #define	V_tcp_do_tso		VNET(tcp_do_tso)
1066df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso, CTLFLAG_VNET | CTLFLAG_RW,
107eddfbb76SRobert Watson 	&VNET_NAME(tcp_do_tso), 0,
108eddfbb76SRobert Watson 	"Enable TCP Segmentation Offload");
109b3c0f300SAndre Oppermann 
110873789cbSAndre Oppermann VNET_DEFINE(int, tcp_sendspace) = 1024*32;
111873789cbSAndre Oppermann #define	V_tcp_sendspace	VNET(tcp_sendspace)
1126df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, TCPCTL_SENDSPACE, sendspace, CTLFLAG_VNET | CTLFLAG_RW,
113873789cbSAndre Oppermann 	&VNET_NAME(tcp_sendspace), 0, "Initial send socket buffer size");
114873789cbSAndre Oppermann 
11582cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_do_autosndbuf) = 1;
11682cea7e6SBjoern A. Zeeb #define	V_tcp_do_autosndbuf	VNET(tcp_do_autosndbuf)
1176df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto, CTLFLAG_VNET | CTLFLAG_RW,
118eddfbb76SRobert Watson 	&VNET_NAME(tcp_do_autosndbuf), 0,
119eddfbb76SRobert Watson 	"Enable automatic send buffer sizing");
1206741ecf5SAndre Oppermann 
12182cea7e6SBjoern A. Zeeb VNET_DEFINE(int, tcp_autosndbuf_inc) = 8*1024;
12282cea7e6SBjoern A. Zeeb #define	V_tcp_autosndbuf_inc	VNET(tcp_autosndbuf_inc)
1236df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_inc, CTLFLAG_VNET | CTLFLAG_RW,
124eddfbb76SRobert Watson 	&VNET_NAME(tcp_autosndbuf_inc), 0,
1258b615593SMarko Zec 	"Incrementor step size of automatic send buffer");
1266741ecf5SAndre Oppermann 
127b233773bSBjoern A. Zeeb VNET_DEFINE(int, tcp_autosndbuf_max) = 2*1024*1024;
12882cea7e6SBjoern A. Zeeb #define	V_tcp_autosndbuf_max	VNET(tcp_autosndbuf_max)
1296df8a710SGleb Smirnoff SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_max, CTLFLAG_VNET | CTLFLAG_RW,
130eddfbb76SRobert Watson 	&VNET_NAME(tcp_autosndbuf_max), 0,
1318b615593SMarko Zec 	"Max size of automatic send buffer");
1326741ecf5SAndre Oppermann 
133*ac952dd2SSean Bruno VNET_DEFINE(int, tcp_sendbuf_auto_lowat) = 0;
134*ac952dd2SSean Bruno #define	V_tcp_sendbuf_auto_lowat	VNET(tcp_sendbuf_auto_lowat)
135*ac952dd2SSean Bruno SYSCTL_INT(_net_inet_tcp, OID_AUTO, sendbuf_auto_lowat, CTLFLAG_VNET | CTLFLAG_RW,
136*ac952dd2SSean Bruno 	&VNET_NAME(tcp_sendbuf_auto_lowat), 0,
137*ac952dd2SSean Bruno 	"Modify threshold for auto send buffer growth to account for SO_SNDLOWAT");
138*ac952dd2SSean Bruno 
139425b7639SSepherosa Ziehau /*
140425b7639SSepherosa Ziehau  * Make sure that either retransmit or persist timer is set for SYN, FIN and
141425b7639SSepherosa Ziehau  * non-ACK.
142425b7639SSepherosa Ziehau  */
143425b7639SSepherosa Ziehau #define TCP_XMIT_TIMER_ASSERT(tp, len, th_flags)			\
144425b7639SSepherosa Ziehau 	KASSERT(((len) == 0 && ((th_flags) & (TH_SYN | TH_FIN)) == 0) ||\
145425b7639SSepherosa Ziehau 	    tcp_timer_active((tp), TT_REXMT) ||				\
146425b7639SSepherosa Ziehau 	    tcp_timer_active((tp), TT_PERSIST),				\
147425b7639SSepherosa Ziehau 	    ("neither rexmt nor persist timer is set"))
148425b7639SSepherosa Ziehau 
149bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
15039bc9de5SLawrence Stewart static void inline	hhook_run_tcp_est_out(struct tcpcb *tp,
15139bc9de5SLawrence Stewart 			    struct tcphdr *th, struct tcpopt *to,
1523ac12506SJonathan T. Looney 			    uint32_t len, int tso);
153bd79708dSJonathan T. Looney #endif
154dbc42409SLawrence Stewart static void inline	cc_after_idle(struct tcpcb *tp);
155dbc42409SLawrence Stewart 
156bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
157dbc42409SLawrence Stewart /*
1580f5e7edcSKevin Lo  * Wrapper for the TCP established output helper hook.
15939bc9de5SLawrence Stewart  */
16039bc9de5SLawrence Stewart static void inline
16139bc9de5SLawrence Stewart hhook_run_tcp_est_out(struct tcpcb *tp, struct tcphdr *th,
1623ac12506SJonathan T. Looney     struct tcpopt *to, uint32_t len, int tso)
16339bc9de5SLawrence Stewart {
16439bc9de5SLawrence Stewart 	struct tcp_hhook_data hhook_data;
16539bc9de5SLawrence Stewart 
16639bc9de5SLawrence Stewart 	if (V_tcp_hhh[HHOOK_TCP_EST_OUT]->hhh_nhooks > 0) {
16739bc9de5SLawrence Stewart 		hhook_data.tp = tp;
16839bc9de5SLawrence Stewart 		hhook_data.th = th;
16939bc9de5SLawrence Stewart 		hhook_data.to = to;
17039bc9de5SLawrence Stewart 		hhook_data.len = len;
17139bc9de5SLawrence Stewart 		hhook_data.tso = tso;
17239bc9de5SLawrence Stewart 
17339bc9de5SLawrence Stewart 		hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_OUT], &hhook_data,
17439bc9de5SLawrence Stewart 		    tp->osd);
17539bc9de5SLawrence Stewart 	}
17639bc9de5SLawrence Stewart }
177bd79708dSJonathan T. Looney #endif
17839bc9de5SLawrence Stewart 
17939bc9de5SLawrence Stewart /*
180dbc42409SLawrence Stewart  * CC wrapper hook functions
181dbc42409SLawrence Stewart  */
182dbc42409SLawrence Stewart static void inline
183dbc42409SLawrence Stewart cc_after_idle(struct tcpcb *tp)
184dbc42409SLawrence Stewart {
185dbc42409SLawrence Stewart 	INP_WLOCK_ASSERT(tp->t_inpcb);
186dbc42409SLawrence Stewart 
187dbc42409SLawrence Stewart 	if (CC_ALGO(tp)->after_idle != NULL)
188dbc42409SLawrence Stewart 		CC_ALGO(tp)->after_idle(tp->ccv);
189dbc42409SLawrence Stewart }
1906741ecf5SAndre Oppermann 
191df8bae1dSRodney W. Grimes /*
192df8bae1dSRodney W. Grimes  * Tcp output routine: figure out what should be sent and send it.
193df8bae1dSRodney W. Grimes  */
194df8bae1dSRodney W. Grimes int
195f10e85d7SLuigi Rizzo tcp_output(struct tcpcb *tp)
196df8bae1dSRodney W. Grimes {
197f10e85d7SLuigi Rizzo 	struct socket *so = tp->t_inpcb->inp_socket;
1983ac12506SJonathan T. Looney 	int32_t len;
1993ac12506SJonathan T. Looney 	uint32_t recwin, sendwin;
200b287c6c7SBjoern A. Zeeb 	int off, flags, error = 0;	/* Keep compiler happy */
201f10e85d7SLuigi Rizzo 	struct mbuf *m;
202fb59c426SYoshinobu Inoue 	struct ip *ip = NULL;
203f10e85d7SLuigi Rizzo 	struct ipovly *ipov = NULL;
204f10e85d7SLuigi Rizzo 	struct tcphdr *th;
205a0292f23SGarrett Wollman 	u_char opt[TCP_MAXOLEN];
206a04884fcSBill Fenner 	unsigned ipoptlen, optlen, hdrlen;
207fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
2089ad0173dSBjoern A. Zeeb 	unsigned ipsec_optlen = 0;
2099ad0173dSBjoern A. Zeeb #endif
210df8bae1dSRodney W. Grimes 	int idle, sendalot;
21102a1a643SAndre Oppermann 	int sack_rxmit, sack_bytes_rxmt;
2126d90faf3SPaul Saab 	struct sackhole *p;
213df0633a1SGleb Smirnoff 	int tso, mtu;
21402a1a643SAndre Oppermann 	struct tcpopt to;
215262c1c1aSMatthew Dillon #if 0
21646f58482SJonathan Lemon 	int maxburst = TCP_MAXBURST;
217262c1c1aSMatthew Dillon #endif
218fb59c426SYoshinobu Inoue #ifdef INET6
219f10e85d7SLuigi Rizzo 	struct ip6_hdr *ip6 = NULL;
220fb59c426SYoshinobu Inoue 	int isipv6;
221fb59c426SYoshinobu Inoue 
222fb59c426SYoshinobu Inoue 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
223fb59c426SYoshinobu Inoue #endif
224df8bae1dSRodney W. Grimes 
2258501a69cSRobert Watson 	INP_WLOCK_ASSERT(tp->t_inpcb);
2263d6ade3aSJennifer Yang 
22709fe6320SNavdeep Parhar #ifdef TCP_OFFLOAD
22809fe6320SNavdeep Parhar 	if (tp->t_flags & TF_TOE)
22909fe6320SNavdeep Parhar 		return (tcp_offload_output(tp));
23009fe6320SNavdeep Parhar #endif
23109fe6320SNavdeep Parhar 
232281a0fd4SPatrick Kelsey #ifdef TCP_RFC7413
233281a0fd4SPatrick Kelsey 	/*
234281a0fd4SPatrick Kelsey 	 * For TFO connections in SYN_RECEIVED, only allow the initial
235281a0fd4SPatrick Kelsey 	 * SYN|ACK and those sent by the retransmit timer.
236281a0fd4SPatrick Kelsey 	 */
23768bd7ed1SJonathan T. Looney 	if (IS_FASTOPEN(tp->t_flags) &&
238281a0fd4SPatrick Kelsey 	    (tp->t_state == TCPS_SYN_RECEIVED) &&
239a4641f4eSPedro F. Giffuni 	    SEQ_GT(tp->snd_max, tp->snd_una) &&    /* initial SYN|ACK sent */
240281a0fd4SPatrick Kelsey 	    (tp->snd_nxt != tp->snd_una))          /* not a retransmit */
241281a0fd4SPatrick Kelsey 		return (0);
242281a0fd4SPatrick Kelsey #endif
243df8bae1dSRodney W. Grimes 	/*
244df8bae1dSRodney W. Grimes 	 * Determine length of data that should be transmitted,
245df8bae1dSRodney W. Grimes 	 * and flags that will be used.
246df8bae1dSRodney W. Grimes 	 * If there is some data or critical controls (SYN, RST)
247df8bae1dSRodney W. Grimes 	 * to send, then transmit; otherwise, investigate further.
248df8bae1dSRodney W. Grimes 	 */
249c24d5daeSJayanth Vijayaraghavan 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
2502ea8da28SLawrence Stewart 	if (idle && ticks - tp->t_rcvtime >= tp->t_rxtcur)
2512ea8da28SLawrence Stewart 		cc_after_idle(tp);
252c24d5daeSJayanth Vijayaraghavan 	tp->t_flags &= ~TF_LASTIDLE;
253c24d5daeSJayanth Vijayaraghavan 	if (idle) {
254c24d5daeSJayanth Vijayaraghavan 		if (tp->t_flags & TF_MORETOCOME) {
255c24d5daeSJayanth Vijayaraghavan 			tp->t_flags |= TF_LASTIDLE;
256c24d5daeSJayanth Vijayaraghavan 			idle = 0;
257c24d5daeSJayanth Vijayaraghavan 		}
258c24d5daeSJayanth Vijayaraghavan 	}
259df8bae1dSRodney W. Grimes again:
2606d90faf3SPaul Saab 	/*
2616d90faf3SPaul Saab 	 * If we've recently taken a timeout, snd_max will be greater than
2626d90faf3SPaul Saab 	 * snd_nxt.  There may be SACK information that allows us to avoid
2636d90faf3SPaul Saab 	 * resending already delivered data.  Adjust snd_nxt accordingly.
2646d90faf3SPaul Saab 	 */
2653529149eSAndre Oppermann 	if ((tp->t_flags & TF_SACK_PERMIT) &&
2663529149eSAndre Oppermann 	    SEQ_LT(tp->snd_nxt, tp->snd_max))
2676d90faf3SPaul Saab 		tcp_sack_adjust(tp);
268df8bae1dSRodney W. Grimes 	sendalot = 0;
269153e5b57SAndre Oppermann 	tso = 0;
270df0633a1SGleb Smirnoff 	mtu = 0;
271df8bae1dSRodney W. Grimes 	off = tp->snd_nxt - tp->snd_una;
272201d185bSAndre Oppermann 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
273df8bae1dSRodney W. Grimes 
274df8bae1dSRodney W. Grimes 	flags = tcp_outflags[tp->t_state];
275a0292f23SGarrett Wollman 	/*
2766d90faf3SPaul Saab 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
2776d90faf3SPaul Saab 	 * to send out new data (when sendalot is 1), bypass this function.
2786d90faf3SPaul Saab 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
2796d90faf3SPaul Saab 	 * we're replacing a (future) new transmission with a retransmission
2806d90faf3SPaul Saab 	 * now, and we previously incremented snd_cwnd in tcp_input().
2816d90faf3SPaul Saab 	 */
2826d90faf3SPaul Saab 	/*
2836d90faf3SPaul Saab 	 * Still in sack recovery , reset rxmit flag to zero.
2846d90faf3SPaul Saab 	 */
2856d90faf3SPaul Saab 	sack_rxmit = 0;
286a55db2b6SPaul Saab 	sack_bytes_rxmt = 0;
2876d90faf3SPaul Saab 	len = 0;
2886d90faf3SPaul Saab 	p = NULL;
289dbc42409SLawrence Stewart 	if ((tp->t_flags & TF_SACK_PERMIT) && IN_FASTRECOVERY(tp->t_flags) &&
290a55db2b6SPaul Saab 	    (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
2913ac12506SJonathan T. Looney 		uint32_t cwin;
292a55db2b6SPaul Saab 
2933ac12506SJonathan T. Looney 		cwin =
2943ac12506SJonathan T. Looney 		    imax(min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt, 0);
295f787edd8SJayanth Vijayaraghavan 		/* Do not retransmit SACK segments beyond snd_recover */
296f787edd8SJayanth Vijayaraghavan 		if (SEQ_GT(p->end, tp->snd_recover)) {
297f787edd8SJayanth Vijayaraghavan 			/*
298f787edd8SJayanth Vijayaraghavan 			 * (At least) part of sack hole extends beyond
299f787edd8SJayanth Vijayaraghavan 			 * snd_recover. Check to see if we can rexmit data
300f787edd8SJayanth Vijayaraghavan 			 * for this hole.
301f787edd8SJayanth Vijayaraghavan 			 */
302f787edd8SJayanth Vijayaraghavan 			if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
303f787edd8SJayanth Vijayaraghavan 				/*
304f787edd8SJayanth Vijayaraghavan 				 * Can't rexmit any more data for this hole.
305f787edd8SJayanth Vijayaraghavan 				 * That data will be rexmitted in the next
306f787edd8SJayanth Vijayaraghavan 				 * sack recovery episode, when snd_recover
307f787edd8SJayanth Vijayaraghavan 				 * moves past p->rxmit.
308f787edd8SJayanth Vijayaraghavan 				 */
309f787edd8SJayanth Vijayaraghavan 				p = NULL;
310f787edd8SJayanth Vijayaraghavan 				goto after_sack_rexmit;
311f787edd8SJayanth Vijayaraghavan 			} else
312f787edd8SJayanth Vijayaraghavan 				/* Can rexmit part of the current hole */
3133ac12506SJonathan T. Looney 				len = ((int32_t)ulmin(cwin,
314f787edd8SJayanth Vijayaraghavan 						   tp->snd_recover - p->rxmit));
315f787edd8SJayanth Vijayaraghavan 		} else
3163ac12506SJonathan T. Looney 			len = ((int32_t)ulmin(cwin, p->end - p->rxmit));
3176d90faf3SPaul Saab 		off = p->rxmit - tp->snd_una;
318f787edd8SJayanth Vijayaraghavan 		KASSERT(off >= 0,("%s: sack block to the left of una : %d",
319f787edd8SJayanth Vijayaraghavan 		    __func__, off));
3206d90faf3SPaul Saab 		if (len > 0) {
321ab5c14d8SRobert Watson 			sack_rxmit = 1;
322ab5c14d8SRobert Watson 			sendalot = 1;
32378b50714SRobert Watson 			TCPSTAT_INC(tcps_sack_rexmits);
32478b50714SRobert Watson 			TCPSTAT_ADD(tcps_sack_rexmit_bytes,
32578b50714SRobert Watson 			    min(len, tp->t_maxseg));
3266d90faf3SPaul Saab 		}
3276d90faf3SPaul Saab 	}
328f787edd8SJayanth Vijayaraghavan after_sack_rexmit:
3296d90faf3SPaul Saab 	/*
330a0292f23SGarrett Wollman 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
331a0292f23SGarrett Wollman 	 * state flags.
332a0292f23SGarrett Wollman 	 */
333a0292f23SGarrett Wollman 	if (tp->t_flags & TF_NEEDFIN)
334a0292f23SGarrett Wollman 		flags |= TH_FIN;
335a0292f23SGarrett Wollman 	if (tp->t_flags & TF_NEEDSYN)
336a0292f23SGarrett Wollman 		flags |= TH_SYN;
337a0292f23SGarrett Wollman 
338cf2942b6SRobert Watson 	SOCKBUF_LOCK(&so->so_snd);
339df8bae1dSRodney W. Grimes 	/*
340df8bae1dSRodney W. Grimes 	 * If in persist timeout with window of 0, send 1 byte.
341df8bae1dSRodney W. Grimes 	 * Otherwise, if window is small but nonzero
342df8bae1dSRodney W. Grimes 	 * and timer expired, we will send what we can
343df8bae1dSRodney W. Grimes 	 * and go to transmit state.
344df8bae1dSRodney W. Grimes 	 */
3452cdbfa66SPaul Saab 	if (tp->t_flags & TF_FORCEDATA) {
346201d185bSAndre Oppermann 		if (sendwin == 0) {
347df8bae1dSRodney W. Grimes 			/*
348df8bae1dSRodney W. Grimes 			 * If we still have some data to send, then
349df8bae1dSRodney W. Grimes 			 * clear the FIN bit.  Usually this would
350df8bae1dSRodney W. Grimes 			 * happen below when it realizes that we
351df8bae1dSRodney W. Grimes 			 * aren't sending all the data.  However,
35229089b51SJulian Elischer 			 * if we have exactly 1 byte of unsent data,
353df8bae1dSRodney W. Grimes 			 * then it won't clear the FIN bit below,
354df8bae1dSRodney W. Grimes 			 * and if we are in persist state, we wind
355df8bae1dSRodney W. Grimes 			 * up sending the packet without recording
356df8bae1dSRodney W. Grimes 			 * that we sent the FIN bit.
357df8bae1dSRodney W. Grimes 			 *
358df8bae1dSRodney W. Grimes 			 * We can't just blindly clear the FIN bit,
359df8bae1dSRodney W. Grimes 			 * because if we don't have any more data
360df8bae1dSRodney W. Grimes 			 * to send then the probe will be the FIN
361df8bae1dSRodney W. Grimes 			 * itself.
362df8bae1dSRodney W. Grimes 			 */
363cfa6009eSGleb Smirnoff 			if (off < sbused(&so->so_snd))
364df8bae1dSRodney W. Grimes 				flags &= ~TH_FIN;
365201d185bSAndre Oppermann 			sendwin = 1;
366df8bae1dSRodney W. Grimes 		} else {
367b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_PERSIST, 0);
368df8bae1dSRodney W. Grimes 			tp->t_rxtshift = 0;
369df8bae1dSRodney W. Grimes 		}
370df8bae1dSRodney W. Grimes 	}
371df8bae1dSRodney W. Grimes 
37228257b5cSMatthew Dillon 	/*
37328257b5cSMatthew Dillon 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
37428257b5cSMatthew Dillon 	 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
375201d185bSAndre Oppermann 	 * a negative length.  This can also occur when TCP opens up
37628257b5cSMatthew Dillon 	 * its congestion window while receiving additional duplicate
37728257b5cSMatthew Dillon 	 * acks after fast-retransmit because TCP will reset snd_nxt
37828257b5cSMatthew Dillon 	 * to snd_max after the fast-retransmit.
37928257b5cSMatthew Dillon 	 *
38028257b5cSMatthew Dillon 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
38128257b5cSMatthew Dillon 	 * be set to snd_una, the offset will be 0, and the length may
38228257b5cSMatthew Dillon 	 * wind up 0.
3836d90faf3SPaul Saab 	 *
3846d90faf3SPaul Saab 	 * If sack_rxmit is true we are retransmitting from the scoreboard
3856d90faf3SPaul Saab 	 * in which case len is already set.
38628257b5cSMatthew Dillon 	 */
387a55db2b6SPaul Saab 	if (sack_rxmit == 0) {
388a55db2b6SPaul Saab 		if (sack_bytes_rxmt == 0)
3893ac12506SJonathan T. Looney 			len = ((int32_t)ulmin(sbavail(&so->so_snd), sendwin) -
390cfa6009eSGleb Smirnoff 			    off);
391a55db2b6SPaul Saab 		else {
3923ac12506SJonathan T. Looney 			int32_t cwin;
393a55db2b6SPaul Saab 
394a55db2b6SPaul Saab                         /*
395a55db2b6SPaul Saab 			 * We are inside of a SACK recovery episode and are
396a55db2b6SPaul Saab 			 * sending new data, having retransmitted all the
397a55db2b6SPaul Saab 			 * data possible in the scoreboard.
398a55db2b6SPaul Saab 			 */
3993ac12506SJonathan T. Looney 			len = ((int32_t)min(sbavail(&so->so_snd), tp->snd_wnd) -
400cfa6009eSGleb Smirnoff 			    off);
4018d03f2b5SPaul Saab 			/*
4028d03f2b5SPaul Saab 			 * Don't remove this (len > 0) check !
4038d03f2b5SPaul Saab 			 * We explicitly check for len > 0 here (although it
4048d03f2b5SPaul Saab 			 * isn't really necessary), to work around a gcc
4058d03f2b5SPaul Saab 			 * optimization issue - to force gcc to compute
4068d03f2b5SPaul Saab 			 * len above. Without this check, the computation
4078d03f2b5SPaul Saab 			 * of len is bungled by the optimizer.
4088d03f2b5SPaul Saab 			 */
4098d03f2b5SPaul Saab 			if (len > 0) {
4107d5ed1ceSPaul Saab 				cwin = tp->snd_cwnd -
4117d5ed1ceSPaul Saab 					(tp->snd_nxt - tp->sack_newdata) -
412a55db2b6SPaul Saab 					sack_bytes_rxmt;
413a55db2b6SPaul Saab 				if (cwin < 0)
414a55db2b6SPaul Saab 					cwin = 0;
4153ac12506SJonathan T. Looney 				len = imin(len, cwin);
416a55db2b6SPaul Saab 			}
417a55db2b6SPaul Saab 		}
4188d03f2b5SPaul Saab 	}
419a0292f23SGarrett Wollman 
420a0292f23SGarrett Wollman 	/*
421a0292f23SGarrett Wollman 	 * Lop off SYN bit if it has already been sent.  However, if this
422a0292f23SGarrett Wollman 	 * is SYN-SENT state and if segment contains data and if we don't
423a0292f23SGarrett Wollman 	 * know that foreign host supports TAO, suppress sending segment.
424a0292f23SGarrett Wollman 	 */
425a0292f23SGarrett Wollman 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
4264b8e98d6SQing Li 		if (tp->t_state != TCPS_SYN_RECEIVED)
427a0292f23SGarrett Wollman 			flags &= ~TH_SYN;
428281a0fd4SPatrick Kelsey #ifdef TCP_RFC7413
429281a0fd4SPatrick Kelsey 		/*
430281a0fd4SPatrick Kelsey 		 * When sending additional segments following a TFO SYN|ACK,
431281a0fd4SPatrick Kelsey 		 * do not include the SYN bit.
432281a0fd4SPatrick Kelsey 		 */
43368bd7ed1SJonathan T. Looney 		if (IS_FASTOPEN(tp->t_flags) &&
434281a0fd4SPatrick Kelsey 		    (tp->t_state == TCPS_SYN_RECEIVED))
435281a0fd4SPatrick Kelsey 			flags &= ~TH_SYN;
436281a0fd4SPatrick Kelsey #endif
437a0292f23SGarrett Wollman 		off--, len++;
438a0292f23SGarrett Wollman 	}
439a0292f23SGarrett Wollman 
44081165e48SAndras Olah 	/*
441c94c54e4SAndre Oppermann 	 * Be careful not to send data and/or FIN on SYN segments.
44281165e48SAndras Olah 	 * This measure is needed to prevent interoperability problems
44381165e48SAndras Olah 	 * with not fully conformant TCP implementations.
44481165e48SAndras Olah 	 */
445c94c54e4SAndre Oppermann 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
44681165e48SAndras Olah 		len = 0;
44781165e48SAndras Olah 		flags &= ~TH_FIN;
44881165e48SAndras Olah 	}
44981165e48SAndras Olah 
450281a0fd4SPatrick Kelsey #ifdef TCP_RFC7413
451281a0fd4SPatrick Kelsey 	/*
452281a0fd4SPatrick Kelsey 	 * When retransmitting SYN|ACK on a passively-created TFO socket,
453281a0fd4SPatrick Kelsey 	 * don't include data, as the presence of data may have caused the
454281a0fd4SPatrick Kelsey 	 * original SYN|ACK to have been dropped by a middlebox.
455281a0fd4SPatrick Kelsey 	 */
45668bd7ed1SJonathan T. Looney 	if (IS_FASTOPEN(tp->t_flags) &&
457281a0fd4SPatrick Kelsey 	    (((tp->t_state == TCPS_SYN_RECEIVED) && (tp->t_rxtshift > 0)) ||
458281a0fd4SPatrick Kelsey 	     (flags & TH_RST)))
459281a0fd4SPatrick Kelsey 		len = 0;
460281a0fd4SPatrick Kelsey #endif
46147a8e865SXin LI 	if (len <= 0) {
462df8bae1dSRodney W. Grimes 		/*
463df8bae1dSRodney W. Grimes 		 * If FIN has been sent but not acked,
464df8bae1dSRodney W. Grimes 		 * but we haven't been called to retransmit,
46528257b5cSMatthew Dillon 		 * len will be < 0.  Otherwise, window shrank
466df8bae1dSRodney W. Grimes 		 * after we sent into it.  If window shrank to 0,
4672d8266afSDavid Greenman 		 * cancel pending retransmit, pull snd_nxt back
4682d8266afSDavid Greenman 		 * to (closed) window, and set the persist timer
4692d8266afSDavid Greenman 		 * if it isn't already going.  If the window didn't
4702d8266afSDavid Greenman 		 * close completely, just wait for an ACK.
47147a8e865SXin LI 		 *
47247a8e865SXin LI 		 * We also do a general check here to ensure that
47347a8e865SXin LI 		 * we will set the persist timer when we have data
47447a8e865SXin LI 		 * to send, but a 0-byte window. This makes sure
47547a8e865SXin LI 		 * the persist timer is set even if the packet
47647a8e865SXin LI 		 * hits one of the "goto send" lines below.
477df8bae1dSRodney W. Grimes 		 */
478df8bae1dSRodney W. Grimes 		len = 0;
47947a8e865SXin LI 		if ((sendwin == 0) && (TCPS_HAVEESTABLISHED(tp->t_state)) &&
48047a8e865SXin LI 			(off < (int) sbavail(&so->so_snd))) {
481b8152ba7SAndre Oppermann 			tcp_timer_activate(tp, TT_REXMT, 0);
4822d8266afSDavid Greenman 			tp->t_rxtshift = 0;
483df8bae1dSRodney W. Grimes 			tp->snd_nxt = tp->snd_una;
484b8152ba7SAndre Oppermann 			if (!tcp_timer_active(tp, TT_PERSIST))
4852d8266afSDavid Greenman 				tcp_setpersist(tp);
486df8bae1dSRodney W. Grimes 		}
487df8bae1dSRodney W. Grimes 	}
48828257b5cSMatthew Dillon 
4896741ecf5SAndre Oppermann 	/* len will be >= 0 after this point. */
490c4982faeSBjoern A. Zeeb 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
4916741ecf5SAndre Oppermann 
49228257b5cSMatthew Dillon 	/*
4936741ecf5SAndre Oppermann 	 * Automatic sizing of send socket buffer.  Often the send buffer
4946741ecf5SAndre Oppermann 	 * size is not optimally adjusted to the actual network conditions
4956741ecf5SAndre Oppermann 	 * at hand (delay bandwidth product).  Setting the buffer size too
4966741ecf5SAndre Oppermann 	 * small limits throughput on links with high bandwidth and high
4976741ecf5SAndre Oppermann 	 * delay (eg. trans-continental/oceanic links).  Setting the
4986741ecf5SAndre Oppermann 	 * buffer size too big consumes too much real kernel memory,
4996741ecf5SAndre Oppermann 	 * especially with many connections on busy servers.
5006741ecf5SAndre Oppermann 	 *
5016741ecf5SAndre Oppermann 	 * The criteria to step up the send buffer one notch are:
5026741ecf5SAndre Oppermann 	 *  1. receive window of remote host is larger than send buffer
5036741ecf5SAndre Oppermann 	 *     (with a fudge factor of 5/4th);
5046741ecf5SAndre Oppermann 	 *  2. send buffer is filled to 7/8th with data (so we actually
5056741ecf5SAndre Oppermann 	 *     have data to make use of it);
5066741ecf5SAndre Oppermann 	 *  3. send buffer fill has not hit maximal automatic size;
5076741ecf5SAndre Oppermann 	 *  4. our send window (slow start and cogestion controlled) is
5086741ecf5SAndre Oppermann 	 *     larger than sent but unacknowledged data in send buffer.
5096741ecf5SAndre Oppermann 	 *
5106741ecf5SAndre Oppermann 	 * The remote host receive window scaling factor may limit the
5116741ecf5SAndre Oppermann 	 * growing of the send buffer before it reaches its allowed
5126741ecf5SAndre Oppermann 	 * maximum.
5136741ecf5SAndre Oppermann 	 *
5146741ecf5SAndre Oppermann 	 * It scales directly with slow start or congestion window
5156741ecf5SAndre Oppermann 	 * and does at most one step per received ACK.  This fast
5166741ecf5SAndre Oppermann 	 * scaling has the drawback of growing the send buffer beyond
5176741ecf5SAndre Oppermann 	 * what is strictly necessary to make full use of a given
518a4641f4eSPedro F. Giffuni 	 * delay*bandwidth product.  However testing has shown this not
5196741ecf5SAndre Oppermann 	 * to be much of an problem.  At worst we are trading wasting
520a4641f4eSPedro F. Giffuni 	 * of available bandwidth (the non-use of it) for wasting some
5216741ecf5SAndre Oppermann 	 * socket buffer memory.
5226741ecf5SAndre Oppermann 	 *
5236741ecf5SAndre Oppermann 	 * TODO: Shrink send buffer during idle periods together
5246741ecf5SAndre Oppermann 	 * with congestion window.  Requires another timer.  Has to
5256741ecf5SAndre Oppermann 	 * wait for upcoming tcp timer rewrite.
526cfa6009eSGleb Smirnoff 	 *
527cfa6009eSGleb Smirnoff 	 * XXXGL: should there be used sbused() or sbavail()?
5286741ecf5SAndre Oppermann 	 */
529603724d3SBjoern A. Zeeb 	if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
530*ac952dd2SSean Bruno 		int autosndbuf_mod = 0;
531*ac952dd2SSean Bruno 		if (V_tcp_sendbuf_auto_lowat)
532*ac952dd2SSean Bruno 			autosndbuf_mod = so->so_snd.sb_lowat;
533*ac952dd2SSean Bruno 
534*ac952dd2SSean Bruno 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat - autosndbuf_mod &&
535*ac952dd2SSean Bruno 		    sbused(&so->so_snd) >= (so->so_snd.sb_hiwat / 8 * 7) - autosndbuf_mod &&
536cfa6009eSGleb Smirnoff 		    sbused(&so->so_snd) < V_tcp_autosndbuf_max &&
537cfa6009eSGleb Smirnoff 		    sendwin >= (sbused(&so->so_snd) -
538cfa6009eSGleb Smirnoff 		    (tp->snd_nxt - tp->snd_una))) {
5396741ecf5SAndre Oppermann 			if (!sbreserve_locked(&so->so_snd,
540603724d3SBjoern A. Zeeb 			    min(so->so_snd.sb_hiwat + V_tcp_autosndbuf_inc,
541603724d3SBjoern A. Zeeb 			     V_tcp_autosndbuf_max), so, curthread))
5426741ecf5SAndre Oppermann 				so->so_snd.sb_flags &= ~SB_AUTOSIZE;
5436741ecf5SAndre Oppermann 		}
5446741ecf5SAndre Oppermann 	}
5456741ecf5SAndre Oppermann 
5466741ecf5SAndre Oppermann 	/*
547ed420311SAndre Oppermann 	 * Decide if we can use TCP Segmentation Offloading (if supported by
548ed420311SAndre Oppermann 	 * hardware).
549b3c0f300SAndre Oppermann 	 *
550b3c0f300SAndre Oppermann 	 * TSO may only be used if we are in a pure bulk sending state.  The
551b3c0f300SAndre Oppermann 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and
552b3c0f300SAndre Oppermann 	 * IP options prevent using TSO.  With TSO the TCP header is the same
553b3c0f300SAndre Oppermann 	 * (except for the sequence number) for all generated packets.  This
554b3c0f300SAndre Oppermann 	 * makes it impossible to transmit any options which vary per generated
555b3c0f300SAndre Oppermann 	 * segment or packet.
556b6ff6724SHiren Panchasara 	 *
557b6ff6724SHiren Panchasara 	 * IPv4 handling has a clear separation of ip options and ip header
558b6ff6724SHiren Panchasara 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
559b6ff6724SHiren Panchasara 	 * the right thing below to provide length of just ip options and thus
560b6ff6724SHiren Panchasara 	 * checking for ipoptlen is enough to decide if ip options are present.
56128257b5cSMatthew Dillon 	 */
562fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
5639ad0173dSBjoern A. Zeeb 	/*
5649ad0173dSBjoern A. Zeeb 	 * Pre-calculate here as we save another lookup into the darknesses
5659ad0173dSBjoern A. Zeeb 	 * of IPsec that way and can actually decide if TSO is ok.
5669ad0173dSBjoern A. Zeeb 	 */
567fcf59617SAndrey V. Elsukov #ifdef INET6
568fcf59617SAndrey V. Elsukov 	if (isipv6 && IPSEC_ENABLED(ipv6))
569fcf59617SAndrey V. Elsukov 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, tp->t_inpcb);
570fcf59617SAndrey V. Elsukov #ifdef INET
571fcf59617SAndrey V. Elsukov 	else
5729ad0173dSBjoern A. Zeeb #endif
573fcf59617SAndrey V. Elsukov #endif /* INET6 */
574fcf59617SAndrey V. Elsukov #ifdef INET
575fcf59617SAndrey V. Elsukov 	if (IPSEC_ENABLED(ipv4))
576fcf59617SAndrey V. Elsukov 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, tp->t_inpcb);
577fcf59617SAndrey V. Elsukov #endif /* INET */
578fcf59617SAndrey V. Elsukov #endif /* IPSEC */
579b6ff6724SHiren Panchasara #ifdef INET6
580b6ff6724SHiren Panchasara 	if (isipv6)
581b6ff6724SHiren Panchasara 		ipoptlen = ip6_optlen(tp->t_inpcb);
582b6ff6724SHiren Panchasara 	else
583b6ff6724SHiren Panchasara #endif
584b6ff6724SHiren Panchasara 	if (tp->t_inpcb->inp_options)
585b6ff6724SHiren Panchasara 		ipoptlen = tp->t_inpcb->inp_options->m_len -
586b6ff6724SHiren Panchasara 				offsetof(struct ipoption, ipopt_list);
587b6ff6724SHiren Panchasara 	else
588b6ff6724SHiren Panchasara 		ipoptlen = 0;
589fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
590b6ff6724SHiren Panchasara 	ipoptlen += ipsec_optlen;
591b6ff6724SHiren Panchasara #endif
592b6ff6724SHiren Panchasara 
593ed420311SAndre Oppermann 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > tp->t_maxseg &&
594b3c0f300SAndre Oppermann 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
595b3c0f300SAndre Oppermann 	    tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
596b6ff6724SHiren Panchasara 	    ipoptlen == 0)
597b3c0f300SAndre Oppermann 		tso = 1;
598153e5b57SAndre Oppermann 
5995d3b1b75SJayanth Vijayaraghavan 	if (sack_rxmit) {
600cfa6009eSGleb Smirnoff 		if (SEQ_LT(p->rxmit + len, tp->snd_una + sbused(&so->so_snd)))
601df8bae1dSRodney W. Grimes 			flags &= ~TH_FIN;
6025d3b1b75SJayanth Vijayaraghavan 	} else {
603cfa6009eSGleb Smirnoff 		if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
604cfa6009eSGleb Smirnoff 		    sbused(&so->so_snd)))
6055d3b1b75SJayanth Vijayaraghavan 			flags &= ~TH_FIN;
6065d3b1b75SJayanth Vijayaraghavan 	}
607df8bae1dSRodney W. Grimes 
6083ac12506SJonathan T. Looney 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
6093ac12506SJonathan T. Looney 	    (long)TCP_MAXWIN << tp->rcv_scale);
610df8bae1dSRodney W. Grimes 
611df8bae1dSRodney W. Grimes 	/*
612262c1c1aSMatthew Dillon 	 * Sender silly window avoidance.   We transmit under the following
613262c1c1aSMatthew Dillon 	 * conditions when len is non-zero:
614262c1c1aSMatthew Dillon 	 *
615b3c0f300SAndre Oppermann 	 *	- We have a full segment (or more with TSO)
616262c1c1aSMatthew Dillon 	 *	- This is the last buffer in a write()/send() and we are
617262c1c1aSMatthew Dillon 	 *	  either idle or running NODELAY
618262c1c1aSMatthew Dillon 	 *	- we've timed out (e.g. persist timer)
619262c1c1aSMatthew Dillon 	 *	- we have more then 1/2 the maximum send window's worth of
620262c1c1aSMatthew Dillon 	 *	  data (receiver may be limited the window size)
621262c1c1aSMatthew Dillon 	 *	- we need to retransmit
622df8bae1dSRodney W. Grimes 	 */
623df8bae1dSRodney W. Grimes 	if (len) {
624b3c0f300SAndre Oppermann 		if (len >= tp->t_maxseg)
625df8bae1dSRodney W. Grimes 			goto send;
626262c1c1aSMatthew Dillon 		/*
627262c1c1aSMatthew Dillon 		 * NOTE! on localhost connections an 'ack' from the remote
628262c1c1aSMatthew Dillon 		 * end may occur synchronously with the output and cause
629262c1c1aSMatthew Dillon 		 * us to flush a buffer queued with moretocome.  XXX
630262c1c1aSMatthew Dillon 		 *
631262c1c1aSMatthew Dillon 		 * note: the len + off check is almost certainly unnecessary.
632262c1c1aSMatthew Dillon 		 */
633262c1c1aSMatthew Dillon 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
634262c1c1aSMatthew Dillon 		    (idle || (tp->t_flags & TF_NODELAY)) &&
6353ac12506SJonathan T. Looney 		    (uint32_t)len + (uint32_t)off >= sbavail(&so->so_snd) &&
636262c1c1aSMatthew Dillon 		    (tp->t_flags & TF_NOPUSH) == 0) {
637df8bae1dSRodney W. Grimes 			goto send;
638262c1c1aSMatthew Dillon 		}
6392cdbfa66SPaul Saab 		if (tp->t_flags & TF_FORCEDATA)		/* typ. timeout case */
640df8bae1dSRodney W. Grimes 			goto send;
641a0292f23SGarrett Wollman 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
642df8bae1dSRodney W. Grimes 			goto send;
643262c1c1aSMatthew Dillon 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
644df8bae1dSRodney W. Grimes 			goto send;
6456d90faf3SPaul Saab 		if (sack_rxmit)
6466d90faf3SPaul Saab 			goto send;
647df8bae1dSRodney W. Grimes 	}
648df8bae1dSRodney W. Grimes 
649df8bae1dSRodney W. Grimes 	/*
650f62563d3SAndre Oppermann 	 * Sending of standalone window updates.
651f62563d3SAndre Oppermann 	 *
65278f59b4bSAndre Oppermann 	 * Window updates are important when we close our window due to a
65378f59b4bSAndre Oppermann 	 * full socket buffer and are opening it again after the application
654f62563d3SAndre Oppermann 	 * reads data from it.  Once the window has opened again and the
655f62563d3SAndre Oppermann 	 * remote end starts to send again the ACK clock takes over and
656f62563d3SAndre Oppermann 	 * provides the most current window information.
657f62563d3SAndre Oppermann 	 *
65878f59b4bSAndre Oppermann 	 * We must avoid the silly window syndrome whereas every read
659f62563d3SAndre Oppermann 	 * from the receive buffer, no matter how small, causes a window
660f62563d3SAndre Oppermann 	 * update to be sent.  We also should avoid sending a flurry of
661f62563d3SAndre Oppermann 	 * window updates when the socket buffer had queued a lot of data
662f62563d3SAndre Oppermann 	 * and the application is doing small reads.
663f62563d3SAndre Oppermann 	 *
664f62563d3SAndre Oppermann 	 * Prevent a flurry of pointless window updates by only sending
665f62563d3SAndre Oppermann 	 * an update when we can increase the advertized window by more
666f62563d3SAndre Oppermann 	 * than 1/4th of the socket buffer capacity.  When the buffer is
667f62563d3SAndre Oppermann 	 * getting full or is very small be more aggressive and send an
668f62563d3SAndre Oppermann 	 * update whenever we can increase by two mss sized segments.
669f62563d3SAndre Oppermann 	 * In all other situations the ACK's to new incoming data will
670f62563d3SAndre Oppermann 	 * carry further window increases.
6714249614cSAndre Oppermann 	 *
6724249614cSAndre Oppermann 	 * Don't send an independent window update if a delayed
6734249614cSAndre Oppermann 	 * ACK is pending (it will get piggy-backed on it) or the
6744249614cSAndre Oppermann 	 * remote side already has done a half-close and won't send
675f62563d3SAndre Oppermann 	 * more data.  Skip this if the connection is in T/TCP
676f62563d3SAndre Oppermann 	 * half-open state.
677df8bae1dSRodney W. Grimes 	 */
678b7de7d87SAndre Oppermann 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
6794249614cSAndre Oppermann 	    !(tp->t_flags & TF_DELACK) &&
680b7de7d87SAndre Oppermann 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
681df8bae1dSRodney W. Grimes 		/*
682f62563d3SAndre Oppermann 		 * "adv" is the amount we could increase the window,
683df8bae1dSRodney W. Grimes 		 * taking into account that we are limited by
684df8bae1dSRodney W. Grimes 		 * TCP_MAXWIN << tp->rcv_scale.
685df8bae1dSRodney W. Grimes 		 */
6863ac12506SJonathan T. Looney 		int32_t adv;
687f701e30dSJohn Baldwin 		int oldwin;
688f701e30dSJohn Baldwin 
6893ac12506SJonathan T. Looney 		adv = recwin;
690f701e30dSJohn Baldwin 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
691f701e30dSJohn Baldwin 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
692f701e30dSJohn Baldwin 			adv -= oldwin;
693f701e30dSJohn Baldwin 		} else
694f701e30dSJohn Baldwin 			oldwin = 0;
695df8bae1dSRodney W. Grimes 
696da84b2e6SJohn Baldwin 		/*
6970dda76b8SJonathan T. Looney 		 * If the new window size ends up being the same as or less
6980dda76b8SJonathan T. Looney 		 * than the old size when it is scaled, then don't force
6990dda76b8SJonathan T. Looney 		 * a window update.
700da84b2e6SJohn Baldwin 		 */
7010dda76b8SJonathan T. Looney 		if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
702da84b2e6SJohn Baldwin 			goto dontupdate;
703f62563d3SAndre Oppermann 
7043ac12506SJonathan T. Looney 		if (adv >= (int32_t)(2 * tp->t_maxseg) &&
7053ac12506SJonathan T. Looney 		    (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
7063ac12506SJonathan T. Looney 		     recwin <= (so->so_rcv.sb_hiwat / 8) ||
707f62563d3SAndre Oppermann 		     so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg))
708df8bae1dSRodney W. Grimes 			goto send;
7098d62aae8SMichael Tuexen 		if (2 * adv >= (int32_t)so->so_rcv.sb_hiwat)
7108d62aae8SMichael Tuexen 			goto send;
711df8bae1dSRodney W. Grimes 	}
712da84b2e6SJohn Baldwin dontupdate:
713df8bae1dSRodney W. Grimes 
714df8bae1dSRodney W. Grimes 	/*
71528257b5cSMatthew Dillon 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
71628257b5cSMatthew Dillon 	 * is also a catch-all for the retransmit timer timeout case.
717df8bae1dSRodney W. Grimes 	 */
718df8bae1dSRodney W. Grimes 	if (tp->t_flags & TF_ACKNOW)
719df8bae1dSRodney W. Grimes 		goto send;
720a0292f23SGarrett Wollman 	if ((flags & TH_RST) ||
721a0292f23SGarrett Wollman 	    ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
722df8bae1dSRodney W. Grimes 		goto send;
723df8bae1dSRodney W. Grimes 	if (SEQ_GT(tp->snd_up, tp->snd_una))
724df8bae1dSRodney W. Grimes 		goto send;
725df8bae1dSRodney W. Grimes 	/*
726df8bae1dSRodney W. Grimes 	 * If our state indicates that FIN should be sent
72728257b5cSMatthew Dillon 	 * and we have not yet done so, then we need to send.
728df8bae1dSRodney W. Grimes 	 */
729df8bae1dSRodney W. Grimes 	if (flags & TH_FIN &&
730df8bae1dSRodney W. Grimes 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
731df8bae1dSRodney W. Grimes 		goto send;
7326d90faf3SPaul Saab 	/*
7336d90faf3SPaul Saab 	 * In SACK, it is possible for tcp_output to fail to send a segment
7346d90faf3SPaul Saab 	 * after the retransmission timer has been turned off.  Make sure
7356d90faf3SPaul Saab 	 * that the retransmission timer is set.
7366d90faf3SPaul Saab 	 */
7373529149eSAndre Oppermann 	if ((tp->t_flags & TF_SACK_PERMIT) &&
7383529149eSAndre Oppermann 	    SEQ_GT(tp->snd_max, tp->snd_una) &&
739b8152ba7SAndre Oppermann 	    !tcp_timer_active(tp, TT_REXMT) &&
740b8152ba7SAndre Oppermann 	    !tcp_timer_active(tp, TT_PERSIST)) {
741b8152ba7SAndre Oppermann 		tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
742cf2942b6SRobert Watson 		goto just_return;
7436d90faf3SPaul Saab 	}
744df8bae1dSRodney W. Grimes 	/*
745df8bae1dSRodney W. Grimes 	 * TCP window updates are not reliable, rather a polling protocol
746df8bae1dSRodney W. Grimes 	 * using ``persist'' packets is used to insure receipt of window
747df8bae1dSRodney W. Grimes 	 * updates.  The three ``states'' for the output side are:
748df8bae1dSRodney W. Grimes 	 *	idle			not doing retransmits or persists
749df8bae1dSRodney W. Grimes 	 *	persisting		to move a small or zero window
750df8bae1dSRodney W. Grimes 	 *	(re)transmitting	and thereby not persisting
751df8bae1dSRodney W. Grimes 	 *
752b8152ba7SAndre Oppermann 	 * tcp_timer_active(tp, TT_PERSIST)
7539b8b58e0SJonathan Lemon 	 *	is true when we are in persist state.
7542cdbfa66SPaul Saab 	 * (tp->t_flags & TF_FORCEDATA)
755df8bae1dSRodney W. Grimes 	 *	is set when we are called to send a persist packet.
756b8152ba7SAndre Oppermann 	 * tcp_timer_active(tp, TT_REXMT)
757df8bae1dSRodney W. Grimes 	 *	is set when we are retransmitting
758df8bae1dSRodney W. Grimes 	 * The output side is idle when both timers are zero.
759df8bae1dSRodney W. Grimes 	 *
760df8bae1dSRodney W. Grimes 	 * If send window is too small, there is data to transmit, and no
761df8bae1dSRodney W. Grimes 	 * retransmit or persist is pending, then go to persist state.
762df8bae1dSRodney W. Grimes 	 * If nothing happens soon, send when timer expires:
763df8bae1dSRodney W. Grimes 	 * if window is nonzero, transmit what we can,
764df8bae1dSRodney W. Grimes 	 * otherwise force out a byte.
765df8bae1dSRodney W. Grimes 	 */
766cfa6009eSGleb Smirnoff 	if (sbavail(&so->so_snd) && !tcp_timer_active(tp, TT_REXMT) &&
767b8152ba7SAndre Oppermann 	    !tcp_timer_active(tp, TT_PERSIST)) {
768df8bae1dSRodney W. Grimes 		tp->t_rxtshift = 0;
769df8bae1dSRodney W. Grimes 		tcp_setpersist(tp);
770df8bae1dSRodney W. Grimes 	}
771df8bae1dSRodney W. Grimes 
772df8bae1dSRodney W. Grimes 	/*
773df8bae1dSRodney W. Grimes 	 * No reason to send a segment, just return.
774df8bae1dSRodney W. Grimes 	 */
775cf2942b6SRobert Watson just_return:
776cf2942b6SRobert Watson 	SOCKBUF_UNLOCK(&so->so_snd);
777df8bae1dSRodney W. Grimes 	return (0);
778df8bae1dSRodney W. Grimes 
779df8bae1dSRodney W. Grimes send:
780cf2942b6SRobert Watson 	SOCKBUF_LOCK_ASSERT(&so->so_snd);
781f6f6703fSSean Bruno 	if (len > 0) {
782f6f6703fSSean Bruno 		if (len >= tp->t_maxseg)
783f6f6703fSSean Bruno 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
784f6f6703fSSean Bruno 		else
785f6f6703fSSean Bruno 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
786f6f6703fSSean Bruno 	}
787df8bae1dSRodney W. Grimes 	/*
788df8bae1dSRodney W. Grimes 	 * Before ESTABLISHED, force sending of initial options
789df8bae1dSRodney W. Grimes 	 * unless TCP set not to do any options.
790df8bae1dSRodney W. Grimes 	 * NOTE: we assume that the IP/TCP header plus TCP options
791df8bae1dSRodney W. Grimes 	 * always fit in a single mbuf, leaving room for a maximum
792df8bae1dSRodney W. Grimes 	 * link header, i.e.
79333841545SHajimu UMEMOTO 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
794df8bae1dSRodney W. Grimes 	 */
795df8bae1dSRodney W. Grimes 	optlen = 0;
796fb59c426SYoshinobu Inoue #ifdef INET6
797fb59c426SYoshinobu Inoue 	if (isipv6)
798fb59c426SYoshinobu Inoue 		hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
799fb59c426SYoshinobu Inoue 	else
800fb59c426SYoshinobu Inoue #endif
801df8bae1dSRodney W. Grimes 		hdrlen = sizeof (struct tcpiphdr);
80202a1a643SAndre Oppermann 
80302a1a643SAndre Oppermann 	/*
80402a1a643SAndre Oppermann 	 * Compute options for segment.
80502a1a643SAndre Oppermann 	 * We only have to care about SYN and established connection
80602a1a643SAndre Oppermann 	 * segments.  Options for SYN-ACK segments are handled in TCP
80702a1a643SAndre Oppermann 	 * syncache.
80802a1a643SAndre Oppermann 	 */
80902a1a643SAndre Oppermann 	to.to_flags = 0;
810f73d9fd2SGleb Smirnoff 	if ((tp->t_flags & TF_NOOPT) == 0) {
81102a1a643SAndre Oppermann 		/* Maximum segment size. */
812df8bae1dSRodney W. Grimes 		if (flags & TH_SYN) {
813df8bae1dSRodney W. Grimes 			tp->snd_nxt = tp->iss;
81402a1a643SAndre Oppermann 			to.to_mss = tcp_mssopt(&tp->t_inpcb->inp_inc);
81502a1a643SAndre Oppermann 			to.to_flags |= TOF_MSS;
816281a0fd4SPatrick Kelsey #ifdef TCP_RFC7413
817281a0fd4SPatrick Kelsey 			/*
818281a0fd4SPatrick Kelsey 			 * Only include the TFO option on the first
819281a0fd4SPatrick Kelsey 			 * transmission of the SYN|ACK on a
820281a0fd4SPatrick Kelsey 			 * passively-created TFO socket, as the presence of
821281a0fd4SPatrick Kelsey 			 * the TFO option may have caused the original
822281a0fd4SPatrick Kelsey 			 * SYN|ACK to have been dropped by a middlebox.
823281a0fd4SPatrick Kelsey 			 */
82468bd7ed1SJonathan T. Looney 			if (IS_FASTOPEN(tp->t_flags) &&
825281a0fd4SPatrick Kelsey 			    (tp->t_state == TCPS_SYN_RECEIVED) &&
826281a0fd4SPatrick Kelsey 			    (tp->t_rxtshift == 0)) {
827281a0fd4SPatrick Kelsey 				to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
828281a0fd4SPatrick Kelsey 				to.to_tfo_cookie = (u_char *)&tp->t_tfo_cookie;
829281a0fd4SPatrick Kelsey 				to.to_flags |= TOF_FASTOPEN;
830281a0fd4SPatrick Kelsey 			}
831281a0fd4SPatrick Kelsey #endif
832df8bae1dSRodney W. Grimes 		}
83302a1a643SAndre Oppermann 		/* Window scaling. */
83402a1a643SAndre Oppermann 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
83502a1a643SAndre Oppermann 			to.to_wscale = tp->request_r_scale;
83602a1a643SAndre Oppermann 			to.to_flags |= TOF_SCALE;
837df8bae1dSRodney W. Grimes 		}
83802a1a643SAndre Oppermann 		/* Timestamps. */
83902a1a643SAndre Oppermann 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
84002a1a643SAndre Oppermann 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
841d8951c8aSBjoern A. Zeeb 			to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
84202a1a643SAndre Oppermann 			to.to_tsecr = tp->ts_recent;
84302a1a643SAndre Oppermann 			to.to_flags |= TOF_TS;
844e44c1887SSteven Hartland 		}
845e44c1887SSteven Hartland 
8466741ecf5SAndre Oppermann 		/* Set receive buffer autosizing timestamp. */
84702a1a643SAndre Oppermann 		if (tp->rfbuf_ts == 0 &&
84802a1a643SAndre Oppermann 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
849d8951c8aSBjoern A. Zeeb 			tp->rfbuf_ts = tcp_ts_getticks();
850e44c1887SSteven Hartland 
85102a1a643SAndre Oppermann 		/* Selective ACK's. */
8523529149eSAndre Oppermann 		if (tp->t_flags & TF_SACK_PERMIT) {
85302a1a643SAndre Oppermann 			if (flags & TH_SYN)
85402a1a643SAndre Oppermann 				to.to_flags |= TOF_SACKPERM;
85502a1a643SAndre Oppermann 			else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
85602a1a643SAndre Oppermann 			    (tp->t_flags & TF_SACK_PERMIT) &&
85702a1a643SAndre Oppermann 			    tp->rcv_numsacks > 0) {
85802a1a643SAndre Oppermann 				to.to_flags |= TOF_SACK;
85902a1a643SAndre Oppermann 				to.to_nsacks = tp->rcv_numsacks;
86002a1a643SAndre Oppermann 				to.to_sacks = (u_char *)tp->sackblks;
86102a1a643SAndre Oppermann 			}
86202a1a643SAndre Oppermann 		}
863fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
86402a1a643SAndre Oppermann 		/* TCP-MD5 (RFC2385). */
865fcf59617SAndrey V. Elsukov 		/*
866fcf59617SAndrey V. Elsukov 		 * Check that TCP_MD5SIG is enabled in tcpcb to
867fcf59617SAndrey V. Elsukov 		 * account the size needed to set this TCP option.
868fcf59617SAndrey V. Elsukov 		 */
86902a1a643SAndre Oppermann 		if (tp->t_flags & TF_SIGNATURE)
87002a1a643SAndre Oppermann 			to.to_flags |= TOF_SIGNATURE;
8711cfd4b53SBruce M Simpson #endif /* TCP_SIGNATURE */
8721cfd4b53SBruce M Simpson 
87302a1a643SAndre Oppermann 		/* Processing the options. */
8744a411b9fSBjoern A. Zeeb 		hdrlen += optlen = tcp_addoptions(&to, opt);
875be3f3b5eSPaul Saab 	}
876be3f3b5eSPaul Saab 
877df8bae1dSRodney W. Grimes 	/*
878df8bae1dSRodney W. Grimes 	 * Adjust data length if insertion of options will
8790c39d38dSGleb Smirnoff 	 * bump the packet length beyond the t_maxseg length.
880a0292f23SGarrett Wollman 	 * Clear the FIN bit because we cut off the tail of
881a0292f23SGarrett Wollman 	 * the segment.
882df8bae1dSRodney W. Grimes 	 */
8830c39d38dSGleb Smirnoff 	if (len + optlen + ipoptlen > tp->t_maxseg) {
884297a37f3SDavid Greenman 		flags &= ~TH_FIN;
885ed420311SAndre Oppermann 
886b3c0f300SAndre Oppermann 		if (tso) {
8879fd573c3SHans Petter Selasky 			u_int if_hw_tsomax;
8889fd573c3SHans Petter Selasky 			u_int if_hw_tsomaxsegcount;
8899fd573c3SHans Petter Selasky 			u_int if_hw_tsomaxsegsize;
8909fd573c3SHans Petter Selasky 			struct mbuf *mb;
8919fd573c3SHans Petter Selasky 			u_int moff;
8929fd573c3SHans Petter Selasky 			int max_len;
8939fd573c3SHans Petter Selasky 
8949fd573c3SHans Petter Selasky 			/* extract TSO information */
8959fd573c3SHans Petter Selasky 			if_hw_tsomax = tp->t_tsomax;
8969fd573c3SHans Petter Selasky 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
8979fd573c3SHans Petter Selasky 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
8989fd573c3SHans Petter Selasky 
8999fd573c3SHans Petter Selasky 			/*
9009fd573c3SHans Petter Selasky 			 * Limit a TSO burst to prevent it from
9019fd573c3SHans Petter Selasky 			 * overflowing or exceeding the maximum length
9029fd573c3SHans Petter Selasky 			 * allowed by the network interface:
9039fd573c3SHans Petter Selasky 			 */
904ed420311SAndre Oppermann 			KASSERT(ipoptlen == 0,
905ed420311SAndre Oppermann 			    ("%s: TSO can't do IP options", __func__));
906ed420311SAndre Oppermann 
907ed420311SAndre Oppermann 			/*
9089fd573c3SHans Petter Selasky 			 * Check if we should limit by maximum payload
9099fd573c3SHans Petter Selasky 			 * length:
910ed420311SAndre Oppermann 			 */
9119fd573c3SHans Petter Selasky 			if (if_hw_tsomax != 0) {
9129fd573c3SHans Petter Selasky 				/* compute maximum TSO length */
913d76d4012SHans Petter Selasky 				max_len = (if_hw_tsomax - hdrlen -
914d76d4012SHans Petter Selasky 				    max_linkhdr);
9159fd573c3SHans Petter Selasky 				if (max_len <= 0) {
9169fd573c3SHans Petter Selasky 					len = 0;
9173c7c188cSHans Petter Selasky 				} else if (len > max_len) {
918b3c0f300SAndre Oppermann 					sendalot = 1;
9193c7c188cSHans Petter Selasky 					len = max_len;
9209fd573c3SHans Petter Selasky 				}
9219fd573c3SHans Petter Selasky 			}
9229fd573c3SHans Petter Selasky 
9239fd573c3SHans Petter Selasky 			/*
9249fd573c3SHans Petter Selasky 			 * Check if we should limit by maximum segment
9259fd573c3SHans Petter Selasky 			 * size and count:
9269fd573c3SHans Petter Selasky 			 */
927b228e6bfSHans Petter Selasky 			if (if_hw_tsomaxsegcount != 0 &&
928b228e6bfSHans Petter Selasky 			    if_hw_tsomaxsegsize != 0) {
929d76d4012SHans Petter Selasky 				/*
930d76d4012SHans Petter Selasky 				 * Subtract one segment for the LINK
931d76d4012SHans Petter Selasky 				 * and TCP/IP headers mbuf that will
932d76d4012SHans Petter Selasky 				 * be prepended to this mbuf chain
933d76d4012SHans Petter Selasky 				 * after the code in this section
934d76d4012SHans Petter Selasky 				 * limits the number of mbufs in the
935d76d4012SHans Petter Selasky 				 * chain to if_hw_tsomaxsegcount.
936d76d4012SHans Petter Selasky 				 */
937d76d4012SHans Petter Selasky 				if_hw_tsomaxsegcount -= 1;
9389fd573c3SHans Petter Selasky 				max_len = 0;
9399fd573c3SHans Petter Selasky 				mb = sbsndmbuf(&so->so_snd, off, &moff);
9409fd573c3SHans Petter Selasky 
9413c7c188cSHans Petter Selasky 				while (mb != NULL && max_len < len) {
942b228e6bfSHans Petter Selasky 					u_int mlen;
943b228e6bfSHans Petter Selasky 					u_int frags;
9449fd573c3SHans Petter Selasky 
9459fd573c3SHans Petter Selasky 					/*
9469fd573c3SHans Petter Selasky 					 * Get length of mbuf fragment
947b228e6bfSHans Petter Selasky 					 * and how many hardware frags,
948b228e6bfSHans Petter Selasky 					 * rounded up, it would use:
9499fd573c3SHans Petter Selasky 					 */
950b228e6bfSHans Petter Selasky 					mlen = (mb->m_len - moff);
951b228e6bfSHans Petter Selasky 					frags = howmany(mlen,
952b228e6bfSHans Petter Selasky 					    if_hw_tsomaxsegsize);
9539fd573c3SHans Petter Selasky 
9549fd573c3SHans Petter Selasky 					/* Handle special case: Zero Length Mbuf */
955b228e6bfSHans Petter Selasky 					if (frags == 0)
956b228e6bfSHans Petter Selasky 						frags = 1;
9579fd573c3SHans Petter Selasky 
9589fd573c3SHans Petter Selasky 					/*
9599fd573c3SHans Petter Selasky 					 * Check if the fragment limit
960b228e6bfSHans Petter Selasky 					 * will be reached or exceeded:
9619fd573c3SHans Petter Selasky 					 */
962b228e6bfSHans Petter Selasky 					if (frags >= if_hw_tsomaxsegcount) {
963b228e6bfSHans Petter Selasky 						max_len += min(mlen,
9649fd573c3SHans Petter Selasky 						    if_hw_tsomaxsegcount *
9659fd573c3SHans Petter Selasky 						    if_hw_tsomaxsegsize);
9669fd573c3SHans Petter Selasky 						break;
9679fd573c3SHans Petter Selasky 					}
968b228e6bfSHans Petter Selasky 					max_len += mlen;
969b228e6bfSHans Petter Selasky 					if_hw_tsomaxsegcount -= frags;
9709fd573c3SHans Petter Selasky 					moff = 0;
9719fd573c3SHans Petter Selasky 					mb = mb->m_next;
9729fd573c3SHans Petter Selasky 				}
9739fd573c3SHans Petter Selasky 				if (max_len <= 0) {
9749fd573c3SHans Petter Selasky 					len = 0;
9753c7c188cSHans Petter Selasky 				} else if (len > max_len) {
9769fd573c3SHans Petter Selasky 					sendalot = 1;
9773c7c188cSHans Petter Selasky 					len = max_len;
9789fd573c3SHans Petter Selasky 				}
979ed420311SAndre Oppermann 			}
980ed420311SAndre Oppermann 
981ed420311SAndre Oppermann 			/*
982ed420311SAndre Oppermann 			 * Prevent the last segment from being
9839fd573c3SHans Petter Selasky 			 * fractional unless the send sockbuf can be
9849fd573c3SHans Petter Selasky 			 * emptied:
985ed420311SAndre Oppermann 			 */
9860c39d38dSGleb Smirnoff 			max_len = (tp->t_maxseg - optlen);
9873ac12506SJonathan T. Looney 			if (((uint32_t)off + (uint32_t)len) <
9883ac12506SJonathan T. Looney 			    sbavail(&so->so_snd)) {
9893c7c188cSHans Petter Selasky 				moff = len % max_len;
9909fd573c3SHans Petter Selasky 				if (moff != 0) {
9919fd573c3SHans Petter Selasky 					len -= moff;
992b3c0f300SAndre Oppermann 					sendalot = 1;
993ed420311SAndre Oppermann 				}
9949fd573c3SHans Petter Selasky 			}
9959fd573c3SHans Petter Selasky 
9969fd573c3SHans Petter Selasky 			/*
9979fd573c3SHans Petter Selasky 			 * In case there are too many small fragments
9989fd573c3SHans Petter Selasky 			 * don't use TSO:
9999fd573c3SHans Petter Selasky 			 */
10003c7c188cSHans Petter Selasky 			if (len <= max_len) {
10013c7c188cSHans Petter Selasky 				len = max_len;
10029fd573c3SHans Petter Selasky 				sendalot = 1;
10039fd573c3SHans Petter Selasky 				tso = 0;
10049fd573c3SHans Petter Selasky 			}
1005ed420311SAndre Oppermann 
1006ed420311SAndre Oppermann 			/*
1007ed420311SAndre Oppermann 			 * Send the FIN in a separate segment
1008ed420311SAndre Oppermann 			 * after the bulk sending is done.
1009ed420311SAndre Oppermann 			 * We don't trust the TSO implementations
1010ed420311SAndre Oppermann 			 * to clear the FIN flag on all but the
1011ed420311SAndre Oppermann 			 * last segment.
1012ed420311SAndre Oppermann 			 */
1013ed420311SAndre Oppermann 			if (tp->t_flags & TF_NEEDFIN)
1014ed420311SAndre Oppermann 				sendalot = 1;
1015ed420311SAndre Oppermann 
1016b3c0f300SAndre Oppermann 		} else {
10170c39d38dSGleb Smirnoff 			len = tp->t_maxseg - optlen - ipoptlen;
1018df8bae1dSRodney W. Grimes 			sendalot = 1;
1019df8bae1dSRodney W. Grimes 		}
1020ed420311SAndre Oppermann 	} else
1021ed420311SAndre Oppermann 		tso = 0;
1022ed420311SAndre Oppermann 
1023ed420311SAndre Oppermann 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
1024ed420311SAndre Oppermann 	    ("%s: len > IP_MAXPACKET", __func__));
1025df8bae1dSRodney W. Grimes 
1026a0292f23SGarrett Wollman /*#ifdef DIAGNOSTIC*/
1027a683a7ddSYoshinobu Inoue #ifdef INET6
1028a683a7ddSYoshinobu Inoue 	if (max_linkhdr + hdrlen > MCLBYTES)
1029a683a7ddSYoshinobu Inoue #else
1030df8bae1dSRodney W. Grimes 	if (max_linkhdr + hdrlen > MHLEN)
1031a683a7ddSYoshinobu Inoue #endif
1032f10e85d7SLuigi Rizzo 		panic("tcphdr too big");
1033a0292f23SGarrett Wollman /*#endif*/
1034df8bae1dSRodney W. Grimes 
1035df8bae1dSRodney W. Grimes 	/*
1036c4982faeSBjoern A. Zeeb 	 * This KASSERT is here to catch edge cases at a well defined place.
1037c4982faeSBjoern A. Zeeb 	 * Before, those had triggered (random) panic conditions further down.
1038c4982faeSBjoern A. Zeeb 	 */
1039c4982faeSBjoern A. Zeeb 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
1040c4982faeSBjoern A. Zeeb 
1041c4982faeSBjoern A. Zeeb 	/*
1042df8bae1dSRodney W. Grimes 	 * Grab a header mbuf, attaching a copy of data to
1043df8bae1dSRodney W. Grimes 	 * be transmitted, and initialize the header from
1044df8bae1dSRodney W. Grimes 	 * the template for sends on this connection.
1045df8bae1dSRodney W. Grimes 	 */
1046df8bae1dSRodney W. Grimes 	if (len) {
10474e023759SAndre Oppermann 		struct mbuf *mb;
10484e023759SAndre Oppermann 		u_int moff;
10494e023759SAndre Oppermann 
10502cdbfa66SPaul Saab 		if ((tp->t_flags & TF_FORCEDATA) && len == 1)
105178b50714SRobert Watson 			TCPSTAT_INC(tcps_sndprobe);
10520ba5d2eeSJohn Baldwin 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
1053f5d34df5SGeorge V. Neville-Neil 			tp->t_sndrexmitpack++;
105478b50714SRobert Watson 			TCPSTAT_INC(tcps_sndrexmitpack);
105578b50714SRobert Watson 			TCPSTAT_ADD(tcps_sndrexmitbyte, len);
1056df8bae1dSRodney W. Grimes 		} else {
105778b50714SRobert Watson 			TCPSTAT_INC(tcps_sndpack);
105878b50714SRobert Watson 			TCPSTAT_ADD(tcps_sndbyte, len);
1059df8bae1dSRodney W. Grimes 		}
106039f6074eSGleb Smirnoff #ifdef INET6
106139f6074eSGleb Smirnoff 		if (MHLEN < hdrlen + max_linkhdr)
106239f6074eSGleb Smirnoff 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
106339f6074eSGleb Smirnoff 		else
106439f6074eSGleb Smirnoff #endif
106539f6074eSGleb Smirnoff 			m = m_gethdr(M_NOWAIT, MT_DATA);
106639f6074eSGleb Smirnoff 
1067df8bae1dSRodney W. Grimes 		if (m == NULL) {
1068cf2942b6SRobert Watson 			SOCKBUF_UNLOCK(&so->so_snd);
1069df8bae1dSRodney W. Grimes 			error = ENOBUFS;
10700e2bc05cSGleb Smirnoff 			sack_rxmit = 0;
1071df8bae1dSRodney W. Grimes 			goto out;
1072df8bae1dSRodney W. Grimes 		}
107339f6074eSGleb Smirnoff 
1074df8bae1dSRodney W. Grimes 		m->m_data += max_linkhdr;
1075df8bae1dSRodney W. Grimes 		m->m_len = hdrlen;
10764e023759SAndre Oppermann 
10774e023759SAndre Oppermann 		/*
10784e023759SAndre Oppermann 		 * Start the m_copy functions from the closest mbuf
10794e023759SAndre Oppermann 		 * to the offset in the socket buffer chain.
10804e023759SAndre Oppermann 		 */
10814e023759SAndre Oppermann 		mb = sbsndptr(&so->so_snd, off, len, &moff);
10824e023759SAndre Oppermann 
1083df8bae1dSRodney W. Grimes 		if (len <= MHLEN - hdrlen - max_linkhdr) {
10843ac12506SJonathan T. Looney 			m_copydata(mb, moff, len,
1085df8bae1dSRodney W. Grimes 			    mtod(m, caddr_t) + hdrlen);
1086df8bae1dSRodney W. Grimes 			m->m_len += len;
1087df8bae1dSRodney W. Grimes 		} else {
1088c3bef61eSKevin Lo 			m->m_next = m_copym(mb, moff, len, M_NOWAIT);
10894e023759SAndre Oppermann 			if (m->m_next == NULL) {
1090cf2942b6SRobert Watson 				SOCKBUF_UNLOCK(&so->so_snd);
1091d7f570e6SGarrett Wollman 				(void) m_free(m);
109251823c3aSGarrett Wollman 				error = ENOBUFS;
10930e2bc05cSGleb Smirnoff 				sack_rxmit = 0;
109451823c3aSGarrett Wollman 				goto out;
109551823c3aSGarrett Wollman 			}
1096df8bae1dSRodney W. Grimes 		}
1097472ea5beSColin Percival 
1098df8bae1dSRodney W. Grimes 		/*
1099df8bae1dSRodney W. Grimes 		 * If we're sending everything we've got, set PUSH.
1100df8bae1dSRodney W. Grimes 		 * (This will keep happy those implementations which only
1101df8bae1dSRodney W. Grimes 		 * give data to the user when a buffer fills or
1102df8bae1dSRodney W. Grimes 		 * a PUSH comes in.)
1103df8bae1dSRodney W. Grimes 		 */
11043ac12506SJonathan T. Looney 		if (((uint32_t)off + (uint32_t)len == sbused(&so->so_snd)) &&
11053ac12506SJonathan T. Looney 		    !(flags & TH_SYN))
1106df8bae1dSRodney W. Grimes 			flags |= TH_PUSH;
1107cf2942b6SRobert Watson 		SOCKBUF_UNLOCK(&so->so_snd);
1108df8bae1dSRodney W. Grimes 	} else {
1109cf2942b6SRobert Watson 		SOCKBUF_UNLOCK(&so->so_snd);
1110df8bae1dSRodney W. Grimes 		if (tp->t_flags & TF_ACKNOW)
111178b50714SRobert Watson 			TCPSTAT_INC(tcps_sndacks);
1112df8bae1dSRodney W. Grimes 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
111378b50714SRobert Watson 			TCPSTAT_INC(tcps_sndctrl);
1114df8bae1dSRodney W. Grimes 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
111578b50714SRobert Watson 			TCPSTAT_INC(tcps_sndurg);
1116df8bae1dSRodney W. Grimes 		else
111778b50714SRobert Watson 			TCPSTAT_INC(tcps_sndwinup);
1118df8bae1dSRodney W. Grimes 
1119aa8bd99dSGleb Smirnoff 		m = m_gethdr(M_NOWAIT, MT_DATA);
1120df8bae1dSRodney W. Grimes 		if (m == NULL) {
1121df8bae1dSRodney W. Grimes 			error = ENOBUFS;
11220e2bc05cSGleb Smirnoff 			sack_rxmit = 0;
1123df8bae1dSRodney W. Grimes 			goto out;
1124df8bae1dSRodney W. Grimes 		}
1125fb59c426SYoshinobu Inoue #ifdef INET6
1126fb59c426SYoshinobu Inoue 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
1127fb59c426SYoshinobu Inoue 		    MHLEN >= hdrlen) {
1128ed6a66caSRobert Watson 			M_ALIGN(m, hdrlen);
1129fb59c426SYoshinobu Inoue 		} else
1130fb59c426SYoshinobu Inoue #endif
1131df8bae1dSRodney W. Grimes 		m->m_data += max_linkhdr;
1132df8bae1dSRodney W. Grimes 		m->m_len = hdrlen;
1133df8bae1dSRodney W. Grimes 	}
1134cf2942b6SRobert Watson 	SOCKBUF_UNLOCK_ASSERT(&so->so_snd);
1135df8bae1dSRodney W. Grimes 	m->m_pkthdr.rcvif = (struct ifnet *)0;
1136c488362eSRobert Watson #ifdef MAC
113730d239bcSRobert Watson 	mac_inpcb_create_mbuf(tp->t_inpcb, m);
1138c488362eSRobert Watson #endif
1139fb59c426SYoshinobu Inoue #ifdef INET6
1140fb59c426SYoshinobu Inoue 	if (isipv6) {
1141fb59c426SYoshinobu Inoue 		ip6 = mtod(m, struct ip6_hdr *);
1142fb59c426SYoshinobu Inoue 		th = (struct tcphdr *)(ip6 + 1);
114379909384SJonathan Lemon 		tcpip_fillheaders(tp->t_inpcb, ip6, th);
1144fb59c426SYoshinobu Inoue 	} else
1145fb59c426SYoshinobu Inoue #endif /* INET6 */
1146fb59c426SYoshinobu Inoue 	{
1147fb59c426SYoshinobu Inoue 		ip = mtod(m, struct ip *);
1148fb59c426SYoshinobu Inoue 		ipov = (struct ipovly *)ip;
1149fb59c426SYoshinobu Inoue 		th = (struct tcphdr *)(ip + 1);
115079909384SJonathan Lemon 		tcpip_fillheaders(tp->t_inpcb, ip, th);
1151fb59c426SYoshinobu Inoue 	}
1152df8bae1dSRodney W. Grimes 
1153df8bae1dSRodney W. Grimes 	/*
1154df8bae1dSRodney W. Grimes 	 * Fill in fields, remembering maximum advertised
1155df8bae1dSRodney W. Grimes 	 * window for use in delaying messages about window sizes.
1156df8bae1dSRodney W. Grimes 	 * If resending a FIN, be sure not to use a new sequence number.
1157df8bae1dSRodney W. Grimes 	 */
1158df8bae1dSRodney W. Grimes 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
1159df8bae1dSRodney W. Grimes 	    tp->snd_nxt == tp->snd_max)
1160df8bae1dSRodney W. Grimes 		tp->snd_nxt--;
1161df8bae1dSRodney W. Grimes 	/*
1162f2512ba1SRui Paulo 	 * If we are starting a connection, send ECN setup
1163f2512ba1SRui Paulo 	 * SYN packet. If we are on a retransmit, we may
1164f2512ba1SRui Paulo 	 * resend those bits a number of times as per
1165f2512ba1SRui Paulo 	 * RFC 3168.
1166f2512ba1SRui Paulo 	 */
1167883054b4SDon Lewis 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
1168f2512ba1SRui Paulo 		if (tp->t_rxtshift >= 1) {
1169603724d3SBjoern A. Zeeb 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
1170f2512ba1SRui Paulo 				flags |= TH_ECE|TH_CWR;
1171f2512ba1SRui Paulo 		} else
1172f2512ba1SRui Paulo 			flags |= TH_ECE|TH_CWR;
1173f2512ba1SRui Paulo 	}
1174f2512ba1SRui Paulo 
1175f2512ba1SRui Paulo 	if (tp->t_state == TCPS_ESTABLISHED &&
1176f2512ba1SRui Paulo 	    (tp->t_flags & TF_ECN_PERMIT)) {
1177f2512ba1SRui Paulo 		/*
1178f2512ba1SRui Paulo 		 * If the peer has ECN, mark data packets with
1179f2512ba1SRui Paulo 		 * ECN capable transmission (ECT).
1180f2512ba1SRui Paulo 		 * Ignore pure ack packets, retransmissions and window probes.
1181f2512ba1SRui Paulo 		 */
1182f2512ba1SRui Paulo 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
1183f2512ba1SRui Paulo 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
1184f2512ba1SRui Paulo #ifdef INET6
1185f2512ba1SRui Paulo 			if (isipv6)
1186f2512ba1SRui Paulo 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
1187f2512ba1SRui Paulo 			else
1188f2512ba1SRui Paulo #endif
1189f2512ba1SRui Paulo 				ip->ip_tos |= IPTOS_ECN_ECT0;
119078b50714SRobert Watson 			TCPSTAT_INC(tcps_ecn_ect0);
1191f2512ba1SRui Paulo 		}
1192f2512ba1SRui Paulo 
1193f2512ba1SRui Paulo 		/*
1194f2512ba1SRui Paulo 		 * Reply with proper ECN notifications.
1195f2512ba1SRui Paulo 		 */
1196f2512ba1SRui Paulo 		if (tp->t_flags & TF_ECN_SND_CWR) {
1197f2512ba1SRui Paulo 			flags |= TH_CWR;
1198f2512ba1SRui Paulo 			tp->t_flags &= ~TF_ECN_SND_CWR;
1199f2512ba1SRui Paulo 		}
1200f2512ba1SRui Paulo 		if (tp->t_flags & TF_ECN_SND_ECE)
1201f2512ba1SRui Paulo 			flags |= TH_ECE;
1202f2512ba1SRui Paulo 	}
1203f2512ba1SRui Paulo 
1204f2512ba1SRui Paulo 	/*
1205df8bae1dSRodney W. Grimes 	 * If we are doing retransmissions, then snd_nxt will
1206df8bae1dSRodney W. Grimes 	 * not reflect the first unsent octet.  For ACK only
1207df8bae1dSRodney W. Grimes 	 * packets, we do not want the sequence number of the
1208df8bae1dSRodney W. Grimes 	 * retransmitted packet, we want the sequence number
1209df8bae1dSRodney W. Grimes 	 * of the next unsent octet.  So, if there is no data
1210df8bae1dSRodney W. Grimes 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
1211df8bae1dSRodney W. Grimes 	 * when filling in ti_seq.  But if we are in persist
1212df8bae1dSRodney W. Grimes 	 * state, snd_max might reflect one byte beyond the
1213df8bae1dSRodney W. Grimes 	 * right edge of the window, so use snd_nxt in that
1214df8bae1dSRodney W. Grimes 	 * case, since we know we aren't doing a retransmission.
1215df8bae1dSRodney W. Grimes 	 * (retransmit and persist are mutually exclusive...)
1216df8bae1dSRodney W. Grimes 	 */
1217a55db2b6SPaul Saab 	if (sack_rxmit == 0) {
1218b8152ba7SAndre Oppermann 		if (len || (flags & (TH_SYN|TH_FIN)) ||
1219b8152ba7SAndre Oppermann 		    tcp_timer_active(tp, TT_PERSIST))
1220fb59c426SYoshinobu Inoue 			th->th_seq = htonl(tp->snd_nxt);
1221df8bae1dSRodney W. Grimes 		else
1222fb59c426SYoshinobu Inoue 			th->th_seq = htonl(tp->snd_max);
1223a55db2b6SPaul Saab 	} else {
12246d90faf3SPaul Saab 		th->th_seq = htonl(p->rxmit);
12256d90faf3SPaul Saab 		p->rxmit += len;
12260077b016SPaul Saab 		tp->sackhint.sack_bytes_rexmit += len;
12276d90faf3SPaul Saab 	}
1228fb59c426SYoshinobu Inoue 	th->th_ack = htonl(tp->rcv_nxt);
1229df8bae1dSRodney W. Grimes 	if (optlen) {
1230fb59c426SYoshinobu Inoue 		bcopy(opt, th + 1, optlen);
1231fb59c426SYoshinobu Inoue 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
1232df8bae1dSRodney W. Grimes 	}
1233fb59c426SYoshinobu Inoue 	th->th_flags = flags;
1234df8bae1dSRodney W. Grimes 	/*
1235df8bae1dSRodney W. Grimes 	 * Calculate receive window.  Don't shrink window,
1236df8bae1dSRodney W. Grimes 	 * but avoid silly window syndrome.
1237df8bae1dSRodney W. Grimes 	 */
12383ac12506SJonathan T. Looney 	if (recwin < (so->so_rcv.sb_hiwat / 4) &&
12393ac12506SJonathan T. Looney 	    recwin < tp->t_maxseg)
1240201d185bSAndre Oppermann 		recwin = 0;
1241f701e30dSJohn Baldwin 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
12423ac12506SJonathan T. Looney 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
12433ac12506SJonathan T. Looney 		recwin = (tp->rcv_adv - tp->rcv_nxt);
1244262c1c1aSMatthew Dillon 
1245104ebb2aSAndre Oppermann 	/*
1246104ebb2aSAndre Oppermann 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1247104ebb2aSAndre Oppermann 	 * or <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK>
1248104ebb2aSAndre Oppermann 	 * case is handled in syncache.
1249104ebb2aSAndre Oppermann 	 */
1250104ebb2aSAndre Oppermann 	if (flags & TH_SYN)
1251104ebb2aSAndre Oppermann 		th->th_win = htons((u_short)
1252104ebb2aSAndre Oppermann 				(min(sbspace(&so->so_rcv), TCP_MAXWIN)));
1253104ebb2aSAndre Oppermann 	else
1254104ebb2aSAndre Oppermann 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
1255262c1c1aSMatthew Dillon 
1256262c1c1aSMatthew Dillon 	/*
1257262c1c1aSMatthew Dillon 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
1258262c1c1aSMatthew Dillon 	 * a 0 window.  This may cause the remote transmitter to stall.  This
1259262c1c1aSMatthew Dillon 	 * flag tells soreceive() to disable delayed acknowledgements when
1260262c1c1aSMatthew Dillon 	 * draining the buffer.  This can occur if the receiver is attempting
1261b2722702SRui Paulo 	 * to read more data than can be buffered prior to transmitting on
1262262c1c1aSMatthew Dillon 	 * the connection.
1263262c1c1aSMatthew Dillon 	 */
1264f5d34df5SGeorge V. Neville-Neil 	if (th->th_win == 0) {
1265f5d34df5SGeorge V. Neville-Neil 		tp->t_sndzerowin++;
1266262c1c1aSMatthew Dillon 		tp->t_flags |= TF_RXWIN0SENT;
1267f5d34df5SGeorge V. Neville-Neil 	} else
1268262c1c1aSMatthew Dillon 		tp->t_flags &= ~TF_RXWIN0SENT;
1269df8bae1dSRodney W. Grimes 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1270fb59c426SYoshinobu Inoue 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
1271fb59c426SYoshinobu Inoue 		th->th_flags |= TH_URG;
1272df8bae1dSRodney W. Grimes 	} else
1273df8bae1dSRodney W. Grimes 		/*
1274df8bae1dSRodney W. Grimes 		 * If no urgent pointer to send, then we pull
1275df8bae1dSRodney W. Grimes 		 * the urgent pointer to the left edge of the send window
1276df8bae1dSRodney W. Grimes 		 * so that it doesn't drift into the send window on sequence
1277df8bae1dSRodney W. Grimes 		 * number wraparound.
1278df8bae1dSRodney W. Grimes 		 */
1279df8bae1dSRodney W. Grimes 		tp->snd_up = tp->snd_una;		/* drag it along */
1280df8bae1dSRodney W. Grimes 
1281df8bae1dSRodney W. Grimes 	/*
1282df8bae1dSRodney W. Grimes 	 * Put TCP length in extended header, and then
1283df8bae1dSRodney W. Grimes 	 * checksum extended header and data.
1284df8bae1dSRodney W. Grimes 	 */
1285fb59c426SYoshinobu Inoue 	m->m_pkthdr.len = hdrlen + len; /* in6_cksum() need this */
128645747ba5SBjoern A. Zeeb 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1287fcf59617SAndrey V. Elsukov 
1288fcf59617SAndrey V. Elsukov #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1289fcf59617SAndrey V. Elsukov 	if (to.to_flags & TOF_SIGNATURE) {
1290fcf59617SAndrey V. Elsukov 		/*
1291fcf59617SAndrey V. Elsukov 		 * Calculate MD5 signature and put it into the place
1292fcf59617SAndrey V. Elsukov 		 * determined before.
1293fcf59617SAndrey V. Elsukov 		 * NOTE: since TCP options buffer doesn't point into
1294fcf59617SAndrey V. Elsukov 		 * mbuf's data, calculate offset and use it.
1295fcf59617SAndrey V. Elsukov 		 */
1296fcf59617SAndrey V. Elsukov 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
1297fcf59617SAndrey V. Elsukov 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
1298fcf59617SAndrey V. Elsukov 			/*
1299fcf59617SAndrey V. Elsukov 			 * Do not send segment if the calculation of MD5
1300fcf59617SAndrey V. Elsukov 			 * digest has failed.
1301fcf59617SAndrey V. Elsukov 			 */
1302fcf59617SAndrey V. Elsukov 			goto out;
1303fcf59617SAndrey V. Elsukov 		}
1304fcf59617SAndrey V. Elsukov 	}
1305fcf59617SAndrey V. Elsukov #endif
1306fb59c426SYoshinobu Inoue #ifdef INET6
130745747ba5SBjoern A. Zeeb 	if (isipv6) {
1308fb59c426SYoshinobu Inoue 		/*
13093df96ee6SCy Schubert 		 * There is no need to fill in ip6_plen right now.
13103df96ee6SCy Schubert 		 * It will be filled later by ip6_output.
1311fb59c426SYoshinobu Inoue 		 */
1312356ab07eSBjoern A. Zeeb 		m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
131345747ba5SBjoern A. Zeeb 		th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
131445747ba5SBjoern A. Zeeb 		    optlen + len, IPPROTO_TCP, 0);
131545747ba5SBjoern A. Zeeb 	}
131645747ba5SBjoern A. Zeeb #endif
131745747ba5SBjoern A. Zeeb #if defined(INET6) && defined(INET)
1318fb59c426SYoshinobu Inoue 	else
131945747ba5SBjoern A. Zeeb #endif
132045747ba5SBjoern A. Zeeb #ifdef INET
1321fb59c426SYoshinobu Inoue 	{
1322356ab07eSBjoern A. Zeeb 		m->m_pkthdr.csum_flags = CSUM_TCP;
132379909384SJonathan Lemon 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
132479909384SJonathan Lemon 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP + len + optlen));
1325fb59c426SYoshinobu Inoue 
1326db4f9cc7SJonathan Lemon 		/* IP version must be set here for ipv4/ipv6 checking later */
1327db4f9cc7SJonathan Lemon 		KASSERT(ip->ip_v == IPVERSION,
13286e551fb6SDavid E. O'Brien 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
1329fb59c426SYoshinobu Inoue 	}
133045747ba5SBjoern A. Zeeb #endif
1331df8bae1dSRodney W. Grimes 
1332df8bae1dSRodney W. Grimes 	/*
1333b3c0f300SAndre Oppermann 	 * Enable TSO and specify the size of the segments.
1334b3c0f300SAndre Oppermann 	 * The TCP pseudo header checksum is always provided.
1335b3c0f300SAndre Oppermann 	 */
1336b3c0f300SAndre Oppermann 	if (tso) {
13370c39d38dSGleb Smirnoff 		KASSERT(len > tp->t_maxseg - optlen,
1338153e5b57SAndre Oppermann 		    ("%s: len <= tso_segsz", __func__));
13393579cf4cSKenneth D. Merry 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13400c39d38dSGleb Smirnoff 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
1341b3c0f300SAndre Oppermann 	}
1342b3c0f300SAndre Oppermann 
1343fcf59617SAndrey V. Elsukov #if defined(IPSEC) || defined(IPSEC_SUPPORT)
134475497cc5SBjoern A. Zeeb 	KASSERT(len + hdrlen + ipoptlen - ipsec_optlen == m_length(m, NULL),
13453ac12506SJonathan T. Looney 	    ("%s: mbuf chain shorter than expected: %d + %u + %u - %u != %u",
134675497cc5SBjoern A. Zeeb 	    __func__, len, hdrlen, ipoptlen, ipsec_optlen, m_length(m, NULL)));
134775497cc5SBjoern A. Zeeb #else
1348ed420311SAndre Oppermann 	KASSERT(len + hdrlen + ipoptlen == m_length(m, NULL),
13493ac12506SJonathan T. Looney 	    ("%s: mbuf chain shorter than expected: %d + %u + %u != %u",
135075497cc5SBjoern A. Zeeb 	    __func__, len, hdrlen, ipoptlen, m_length(m, NULL)));
135175497cc5SBjoern A. Zeeb #endif
1352ed420311SAndre Oppermann 
1353bd79708dSJonathan T. Looney #ifdef TCP_HHOOK
135439bc9de5SLawrence Stewart 	/* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
135539bc9de5SLawrence Stewart 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
1356bd79708dSJonathan T. Looney #endif
135739bc9de5SLawrence Stewart 
1358610ee2f9SDavid Greenman #ifdef TCPDEBUG
1359df8bae1dSRodney W. Grimes 	/*
1360df8bae1dSRodney W. Grimes 	 * Trace.
1361df8bae1dSRodney W. Grimes 	 */
136291f467d5SHartmut Brandt 	if (so->so_options & SO_DEBUG) {
1363f3e0b7efSBruce M Simpson 		u_short save = 0;
13645214cb3fSBruce M Simpson #ifdef INET6
13655214cb3fSBruce M Simpson 		if (!isipv6)
13665214cb3fSBruce M Simpson #endif
13675214cb3fSBruce M Simpson 		{
13685214cb3fSBruce M Simpson 			save = ipov->ih_len;
136991f467d5SHartmut Brandt 			ipov->ih_len = htons(m->m_pkthdr.len /* - hdrlen + (th->th_off << 2) */);
13705214cb3fSBruce M Simpson 		}
1371fb59c426SYoshinobu Inoue 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13725214cb3fSBruce M Simpson #ifdef INET6
13735214cb3fSBruce M Simpson 		if (!isipv6)
13745214cb3fSBruce M Simpson #endif
137591f467d5SHartmut Brandt 		ipov->ih_len = save;
137691f467d5SHartmut Brandt 	}
1377b287c6c7SBjoern A. Zeeb #endif /* TCPDEBUG */
13782b9c9984SGeorge V. Neville-Neil 	TCP_PROBE3(debug__output, tp, th, m);
1379df8bae1dSRodney W. Grimes 
1380df8bae1dSRodney W. Grimes 	/*
1381df8bae1dSRodney W. Grimes 	 * Fill in IP length and desired time to live and
1382df8bae1dSRodney W. Grimes 	 * send to IP level.  There should be a better way
1383df8bae1dSRodney W. Grimes 	 * to handle ttl and tos; we could keep them in
1384df8bae1dSRodney W. Grimes 	 * the template, but need a way to checksum without them.
1385df8bae1dSRodney W. Grimes 	 */
1386fb59c426SYoshinobu Inoue 	/*
138743630e62SHiren Panchasara 	 * m->m_pkthdr.len should have been set before checksum calculation,
1388fb59c426SYoshinobu Inoue 	 * because in6_cksum() need it.
1389fb59c426SYoshinobu Inoue 	 */
1390fb59c426SYoshinobu Inoue #ifdef INET6
1391fb59c426SYoshinobu Inoue 	if (isipv6) {
1392fb59c426SYoshinobu Inoue 		/*
1393fb59c426SYoshinobu Inoue 		 * we separately set hoplimit for every segment, since the
1394fb59c426SYoshinobu Inoue 		 * user might want to change the value via setsockopt.
1395fb59c426SYoshinobu Inoue 		 * Also, desired default hop limit might be changed via
1396fb59c426SYoshinobu Inoue 		 * Neighbor Discovery.
1397fb59c426SYoshinobu Inoue 		 */
139897d8d152SAndre Oppermann 		ip6->ip6_hlim = in6_selecthlim(tp->t_inpcb, NULL);
1399fb59c426SYoshinobu Inoue 
140057f60867SMark Johnston 		/*
140157f60867SMark Johnston 		 * Set the packet size here for the benefit of DTrace probes.
140257f60867SMark Johnston 		 * ip6_output() will set it properly; it's supposed to include
140357f60867SMark Johnston 		 * the option header lengths as well.
140457f60867SMark Johnston 		 */
140557f60867SMark Johnston 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
140657f60867SMark Johnston 
14070c39d38dSGleb Smirnoff 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
14080f3e3bc5SSean Bruno 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
14090f3e3bc5SSean Bruno 		else
14100f3e3bc5SSean Bruno 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
14110f3e3bc5SSean Bruno 
141257f60867SMark Johnston 		if (tp->t_state == TCPS_SYN_SENT)
1413d9fae5abSAndriy Gapon 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
141457f60867SMark Johnston 
141557f60867SMark Johnston 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
141657f60867SMark Johnston 
141786a996e6SHiren Panchasara #ifdef TCPPCAP
141886a996e6SHiren Panchasara 		/* Save packet, if requested. */
141986a996e6SHiren Panchasara 		tcp_pcap_add(th, m, &(tp->t_outpkts));
142086a996e6SHiren Panchasara #endif
142186a996e6SHiren Panchasara 
1422fb59c426SYoshinobu Inoue 		/* TODO: IPv6 IP6TOS_ECT bit on */
14234a5c6c6aSMike Karels 		error = ip6_output(m, tp->t_inpcb->in6p_outputopts,
14244a5c6c6aSMike Karels 		    &tp->t_inpcb->inp_route6,
1425df0633a1SGleb Smirnoff 		    ((so->so_options & SO_DONTROUTE) ?  IP_ROUTETOIF : 0),
1426df0633a1SGleb Smirnoff 		    NULL, NULL, tp->t_inpcb);
1427df0633a1SGleb Smirnoff 
14284a5c6c6aSMike Karels 		if (error == EMSGSIZE && tp->t_inpcb->inp_route6.ro_rt != NULL)
14294a5c6c6aSMike Karels 			mtu = tp->t_inpcb->inp_route6.ro_rt->rt_mtu;
1430b287c6c7SBjoern A. Zeeb 	}
1431fb59c426SYoshinobu Inoue #endif /* INET6 */
1432b287c6c7SBjoern A. Zeeb #if defined(INET) && defined(INET6)
1433b287c6c7SBjoern A. Zeeb 	else
1434b287c6c7SBjoern A. Zeeb #endif
1435b287c6c7SBjoern A. Zeeb #ifdef INET
1436df8bae1dSRodney W. Grimes     {
14378f134647SGleb Smirnoff 	ip->ip_len = htons(m->m_pkthdr.len);
1438686cdd19SJun-ichiro itojun Hagino #ifdef INET6
14395cd54324SBjoern A. Zeeb 	if (tp->t_inpcb->inp_vflag & INP_IPV6PROTO)
144097d8d152SAndre Oppermann 		ip->ip_ttl = in6_selecthlim(tp->t_inpcb, NULL);
1441686cdd19SJun-ichiro itojun Hagino #endif /* INET6 */
1442f138387aSGarrett Wollman 	/*
144397d8d152SAndre Oppermann 	 * If we do path MTU discovery, then we set DF on every packet.
144497d8d152SAndre Oppermann 	 * This might not be the best thing to do according to RFC3390
144597d8d152SAndre Oppermann 	 * Section 2. However the tcp hostcache migitates the problem
144697d8d152SAndre Oppermann 	 * so it affects only the first tcp connection with a host.
1447e4e92660SAndre Oppermann 	 *
1448e4e92660SAndre Oppermann 	 * NB: Don't set DF on small MTU/MSS to have a safe fallback.
1449f138387aSGarrett Wollman 	 */
14500c39d38dSGleb Smirnoff 	if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
14518f134647SGleb Smirnoff 		ip->ip_off |= htons(IP_DF);
1452f6f6703fSSean Bruno 		tp->t_flags2 |= TF2_PLPMTU_PMTUD;
1453f6f6703fSSean Bruno 	} else {
1454f6f6703fSSean Bruno 		tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
1455f6f6703fSSean Bruno 	}
145697d8d152SAndre Oppermann 
145757f60867SMark Johnston 	if (tp->t_state == TCPS_SYN_SENT)
1458d9fae5abSAndriy Gapon 		TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
145957f60867SMark Johnston 
146057f60867SMark Johnston 	TCP_PROBE5(send, NULL, tp, ip, tp, th);
146157f60867SMark Johnston 
146286a996e6SHiren Panchasara #ifdef TCPPCAP
146386a996e6SHiren Panchasara 	/* Save packet, if requested. */
146486a996e6SHiren Panchasara 	tcp_pcap_add(th, m, &(tp->t_outpkts));
146586a996e6SHiren Panchasara #endif
146686a996e6SHiren Panchasara 
146784cc0778SGeorge V. Neville-Neil 	error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
1468b5d47ff5SJohn-Mark Gurney 	    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
1469b5d47ff5SJohn-Mark Gurney 	    tp->t_inpcb);
1470df0633a1SGleb Smirnoff 
147184cc0778SGeorge V. Neville-Neil 	if (error == EMSGSIZE && tp->t_inpcb->inp_route.ro_rt != NULL)
147284cc0778SGeorge V. Neville-Neil 		mtu = tp->t_inpcb->inp_route.ro_rt->rt_mtu;
1473df8bae1dSRodney W. Grimes     }
1474b287c6c7SBjoern A. Zeeb #endif /* INET */
14750e2bc05cSGleb Smirnoff 
14760e2bc05cSGleb Smirnoff out:
14770e2bc05cSGleb Smirnoff 	/*
14780e2bc05cSGleb Smirnoff 	 * In transmit state, time the transmission and arrange for
14790e2bc05cSGleb Smirnoff 	 * the retransmit.  In persist state, just set snd_max.
14800e2bc05cSGleb Smirnoff 	 */
14810e2bc05cSGleb Smirnoff 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
14820e2bc05cSGleb Smirnoff 	    !tcp_timer_active(tp, TT_PERSIST)) {
14830e2bc05cSGleb Smirnoff 		tcp_seq startseq = tp->snd_nxt;
14840e2bc05cSGleb Smirnoff 
14850e2bc05cSGleb Smirnoff 		/*
14860e2bc05cSGleb Smirnoff 		 * Advance snd_nxt over sequence space of this segment.
14870e2bc05cSGleb Smirnoff 		 */
14880e2bc05cSGleb Smirnoff 		if (flags & (TH_SYN|TH_FIN)) {
14890e2bc05cSGleb Smirnoff 			if (flags & TH_SYN)
14900e2bc05cSGleb Smirnoff 				tp->snd_nxt++;
14910e2bc05cSGleb Smirnoff 			if (flags & TH_FIN) {
14920e2bc05cSGleb Smirnoff 				tp->snd_nxt++;
14930e2bc05cSGleb Smirnoff 				tp->t_flags |= TF_SENTFIN;
14940e2bc05cSGleb Smirnoff 			}
14950e2bc05cSGleb Smirnoff 		}
14960e2bc05cSGleb Smirnoff 		if (sack_rxmit)
14970e2bc05cSGleb Smirnoff 			goto timer;
14980e2bc05cSGleb Smirnoff 		tp->snd_nxt += len;
14990e2bc05cSGleb Smirnoff 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
15000e2bc05cSGleb Smirnoff 			tp->snd_max = tp->snd_nxt;
15010e2bc05cSGleb Smirnoff 			/*
15020e2bc05cSGleb Smirnoff 			 * Time this transmission if not a retransmission and
15030e2bc05cSGleb Smirnoff 			 * not currently timing anything.
15040e2bc05cSGleb Smirnoff 			 */
15050e2bc05cSGleb Smirnoff 			if (tp->t_rtttime == 0) {
15060e2bc05cSGleb Smirnoff 				tp->t_rtttime = ticks;
15070e2bc05cSGleb Smirnoff 				tp->t_rtseq = startseq;
15080e2bc05cSGleb Smirnoff 				TCPSTAT_INC(tcps_segstimed);
15090e2bc05cSGleb Smirnoff 			}
15100e2bc05cSGleb Smirnoff 		}
15110e2bc05cSGleb Smirnoff 
15120e2bc05cSGleb Smirnoff 		/*
15130e2bc05cSGleb Smirnoff 		 * Set retransmit timer if not currently set,
15140e2bc05cSGleb Smirnoff 		 * and not doing a pure ack or a keep-alive probe.
15150e2bc05cSGleb Smirnoff 		 * Initial value for retransmit timer is smoothed
15160e2bc05cSGleb Smirnoff 		 * round-trip time + 2 * round-trip time variance.
15170e2bc05cSGleb Smirnoff 		 * Initialize shift counter which is used for backoff
15180e2bc05cSGleb Smirnoff 		 * of retransmit time.
15190e2bc05cSGleb Smirnoff 		 */
15200e2bc05cSGleb Smirnoff timer:
15210e2bc05cSGleb Smirnoff 		if (!tcp_timer_active(tp, TT_REXMT) &&
15220e2bc05cSGleb Smirnoff 		    ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
15230e2bc05cSGleb Smirnoff 		     (tp->snd_nxt != tp->snd_una))) {
15240e2bc05cSGleb Smirnoff 			if (tcp_timer_active(tp, TT_PERSIST)) {
15250e2bc05cSGleb Smirnoff 				tcp_timer_activate(tp, TT_PERSIST, 0);
15260e2bc05cSGleb Smirnoff 				tp->t_rxtshift = 0;
15270e2bc05cSGleb Smirnoff 			}
15280e2bc05cSGleb Smirnoff 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1529f8568079SHiren Panchasara 		} else if (len == 0 && sbavail(&so->so_snd) &&
1530f8568079SHiren Panchasara 		    !tcp_timer_active(tp, TT_REXMT) &&
1531f8568079SHiren Panchasara 		    !tcp_timer_active(tp, TT_PERSIST)) {
1532f8568079SHiren Panchasara 			/*
1533f8568079SHiren Panchasara 			 * Avoid a situation where we do not set persist timer
1534f8568079SHiren Panchasara 			 * after a zero window condition. For example:
1535f8568079SHiren Panchasara 			 * 1) A -> B: packet with enough data to fill the window
1536f8568079SHiren Panchasara 			 * 2) B -> A: ACK for #1 + new data (0 window
1537f8568079SHiren Panchasara 			 *    advertisement)
1538f8568079SHiren Panchasara 			 * 3) A -> B: ACK for #2, 0 len packet
1539f8568079SHiren Panchasara 			 *
1540f8568079SHiren Panchasara 			 * In this case, A will not activate the persist timer,
1541f8568079SHiren Panchasara 			 * because it chose to send a packet. Unless tcp_output
1542f8568079SHiren Panchasara 			 * is called for some other reason (delayed ack timer,
1543f8568079SHiren Panchasara 			 * another input packet from B, socket syscall), A will
1544f8568079SHiren Panchasara 			 * not send zero window probes.
1545f8568079SHiren Panchasara 			 *
1546f8568079SHiren Panchasara 			 * So, if you send a 0-length packet, but there is data
1547f8568079SHiren Panchasara 			 * in the socket buffer, and neither the rexmt or
1548f8568079SHiren Panchasara 			 * persist timer is already set, then activate the
1549f8568079SHiren Panchasara 			 * persist timer.
1550f8568079SHiren Panchasara 			 */
1551f8568079SHiren Panchasara 			tp->t_rxtshift = 0;
1552f8568079SHiren Panchasara 			tcp_setpersist(tp);
15530e2bc05cSGleb Smirnoff 		}
15540e2bc05cSGleb Smirnoff 	} else {
15550e2bc05cSGleb Smirnoff 		/*
15560e2bc05cSGleb Smirnoff 		 * Persist case, update snd_max but since we are in
15570e2bc05cSGleb Smirnoff 		 * persist mode (no window) we do not update snd_nxt.
15580e2bc05cSGleb Smirnoff 		 */
15590e2bc05cSGleb Smirnoff 		int xlen = len;
15600e2bc05cSGleb Smirnoff 		if (flags & TH_SYN)
15610e2bc05cSGleb Smirnoff 			++xlen;
15620e2bc05cSGleb Smirnoff 		if (flags & TH_FIN) {
15630e2bc05cSGleb Smirnoff 			++xlen;
15640e2bc05cSGleb Smirnoff 			tp->t_flags |= TF_SENTFIN;
15650e2bc05cSGleb Smirnoff 		}
15660e2bc05cSGleb Smirnoff 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
156715c82571SJonathan T. Looney 			tp->snd_max = tp->snd_nxt + xlen;
15680e2bc05cSGleb Smirnoff 	}
15690e2bc05cSGleb Smirnoff 
1570df8bae1dSRodney W. Grimes 	if (error) {
15717734ea06SArchie Cobbs 
15727734ea06SArchie Cobbs 		/*
15737734ea06SArchie Cobbs 		 * We know that the packet was lost, so back out the
15747734ea06SArchie Cobbs 		 * sequence number advance, if any.
15752c30ec0aSAndre Oppermann 		 *
15762c30ec0aSAndre Oppermann 		 * If the error is EPERM the packet got blocked by the
15772c30ec0aSAndre Oppermann 		 * local firewall.  Normally we should terminate the
15782c30ec0aSAndre Oppermann 		 * connection but the blocking may have been spurious
15792c30ec0aSAndre Oppermann 		 * due to a firewall reconfiguration cycle.  So we treat
15802c30ec0aSAndre Oppermann 		 * it like a packet loss and let the retransmit timer and
15812c30ec0aSAndre Oppermann 		 * timeouts do their work over time.
15822c30ec0aSAndre Oppermann 		 * XXX: It is a POLA question whether calling tcp_drop right
15832c30ec0aSAndre Oppermann 		 * away would be the really correct behavior instead.
15847734ea06SArchie Cobbs 		 */
158572757d9aSGleb Smirnoff 		if (((tp->t_flags & TF_FORCEDATA) == 0 ||
1586b8152ba7SAndre Oppermann 		    !tcp_timer_active(tp, TT_PERSIST)) &&
158772757d9aSGleb Smirnoff 		    ((flags & TH_SYN) == 0) &&
158872757d9aSGleb Smirnoff 		    (error != EPERM)) {
15890077b016SPaul Saab 			if (sack_rxmit) {
15905d3b1b75SJayanth Vijayaraghavan 				p->rxmit -= len;
15910077b016SPaul Saab 				tp->sackhint.sack_bytes_rexmit -= len;
159272757d9aSGleb Smirnoff 				KASSERT(tp->sackhint.sack_bytes_rexmit >= 0,
15930077b016SPaul Saab 				    ("sackhint bytes rtx >= 0"));
15940077b016SPaul Saab 			} else
15957734ea06SArchie Cobbs 				tp->snd_nxt -= len;
15967734ea06SArchie Cobbs 		}
1597cf2942b6SRobert Watson 		SOCKBUF_UNLOCK_ASSERT(&so->so_snd);	/* Check gotos. */
159872757d9aSGleb Smirnoff 		switch (error) {
1599fcf59617SAndrey V. Elsukov 		case EACCES:
1600fcf59617SAndrey V. Elsukov 			tp->t_softerror = error;
1601fcf59617SAndrey V. Elsukov 			return (0);
160272757d9aSGleb Smirnoff 		case EPERM:
160372757d9aSGleb Smirnoff 			tp->t_softerror = error;
160472757d9aSGleb Smirnoff 			return (error);
160572757d9aSGleb Smirnoff 		case ENOBUFS:
1606425b7639SSepherosa Ziehau 			TCP_XMIT_TIMER_ASSERT(tp, len, flags);
16071600372bSAndre Oppermann 			tp->snd_cwnd = tp->t_maxseg;
1608df8bae1dSRodney W. Grimes 			return (0);
160972757d9aSGleb Smirnoff 		case EMSGSIZE:
16103d1f141bSGarrett Wollman 			/*
1611b3c0f300SAndre Oppermann 			 * For some reason the interface we used initially
1612b3c0f300SAndre Oppermann 			 * to send segments changed to another or lowered
1613b3c0f300SAndre Oppermann 			 * its MTU.
1614b3c0f300SAndre Oppermann 			 * If TSO was active we either got an interface
1615b3c0f300SAndre Oppermann 			 * without TSO capabilits or TSO was turned off.
1616df0633a1SGleb Smirnoff 			 * If we obtained mtu from ip_output() then update
1617df0633a1SGleb Smirnoff 			 * it and try again.
16183d1f141bSGarrett Wollman 			 */
1619b3c0f300SAndre Oppermann 			if (tso)
1620b3c0f300SAndre Oppermann 				tp->t_flags &= ~TF_TSO;
1621df0633a1SGleb Smirnoff 			if (mtu != 0) {
1622df0633a1SGleb Smirnoff 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
1623df0633a1SGleb Smirnoff 				goto again;
1624df0633a1SGleb Smirnoff 			}
1625df0633a1SGleb Smirnoff 			return (error);
16268bec3467SGleb Smirnoff 		case EHOSTDOWN:
162772757d9aSGleb Smirnoff 		case EHOSTUNREACH:
162872757d9aSGleb Smirnoff 		case ENETDOWN:
16298bec3467SGleb Smirnoff 		case ENETUNREACH:
163072757d9aSGleb Smirnoff 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
1631df8bae1dSRodney W. Grimes 				tp->t_softerror = error;
1632df8bae1dSRodney W. Grimes 				return (0);
1633df8bae1dSRodney W. Grimes 			}
163472757d9aSGleb Smirnoff 			/* FALLTHROUGH */
163572757d9aSGleb Smirnoff 		default:
1636df8bae1dSRodney W. Grimes 			return (error);
1637df8bae1dSRodney W. Grimes 		}
163872757d9aSGleb Smirnoff 	}
163978b50714SRobert Watson 	TCPSTAT_INC(tcps_sndtotal);
1640df8bae1dSRodney W. Grimes 
1641df8bae1dSRodney W. Grimes 	/*
1642df8bae1dSRodney W. Grimes 	 * Data sent (as far as we can tell).
1643df8bae1dSRodney W. Grimes 	 * If this advertises a larger window than any other segment,
1644df8bae1dSRodney W. Grimes 	 * then remember the size of the advertised window.
1645df8bae1dSRodney W. Grimes 	 * Any pending ACK has now been sent.
1646df8bae1dSRodney W. Grimes 	 */
16473ac12506SJonathan T. Looney 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
1648201d185bSAndre Oppermann 		tp->rcv_adv = tp->rcv_nxt + recwin;
1649df8bae1dSRodney W. Grimes 	tp->last_ack_sent = tp->rcv_nxt;
16503bfd6421SJonathan Lemon 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
1651b8152ba7SAndre Oppermann 	if (tcp_timer_active(tp, TT_DELACK))
1652b8152ba7SAndre Oppermann 		tcp_timer_activate(tp, TT_DELACK, 0);
1653d912c694SMatthew Dillon #if 0
1654d912c694SMatthew Dillon 	/*
1655d912c694SMatthew Dillon 	 * This completely breaks TCP if newreno is turned on.  What happens
1656d912c694SMatthew Dillon 	 * is that if delayed-acks are turned on on the receiver, this code
1657d912c694SMatthew Dillon 	 * on the transmitter effectively destroys the TCP window, forcing
1658d912c694SMatthew Dillon 	 * it to four packets (1.5Kx4 = 6K window).
1659d912c694SMatthew Dillon 	 */
1660dbc42409SLawrence Stewart 	if (sendalot && --maxburst)
1661df8bae1dSRodney W. Grimes 		goto again;
1662d912c694SMatthew Dillon #endif
1663d912c694SMatthew Dillon 	if (sendalot)
1664d912c694SMatthew Dillon 		goto again;
1665df8bae1dSRodney W. Grimes 	return (0);
1666df8bae1dSRodney W. Grimes }
1667df8bae1dSRodney W. Grimes 
1668df8bae1dSRodney W. Grimes void
1669ad3f9ab3SAndre Oppermann tcp_setpersist(struct tcpcb *tp)
1670df8bae1dSRodney W. Grimes {
16719b8b58e0SJonathan Lemon 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
16729b8b58e0SJonathan Lemon 	int tt;
1673df8bae1dSRodney W. Grimes 
1674672dc4aeSJohn Baldwin 	tp->t_flags &= ~TF_PREVVALID;
1675b8152ba7SAndre Oppermann 	if (tcp_timer_active(tp, TT_REXMT))
16769b8b58e0SJonathan Lemon 		panic("tcp_setpersist: retransmit pending");
1677df8bae1dSRodney W. Grimes 	/*
1678a4641f4eSPedro F. Giffuni 	 * Start/restart persistence timer.
1679df8bae1dSRodney W. Grimes 	 */
16809b8b58e0SJonathan Lemon 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
16810645c604SHiren Panchasara 		      tcp_persmin, tcp_persmax);
1682b8152ba7SAndre Oppermann 	tcp_timer_activate(tp, TT_PERSIST, tt);
1683df8bae1dSRodney W. Grimes 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
1684df8bae1dSRodney W. Grimes 		tp->t_rxtshift++;
1685df8bae1dSRodney W. Grimes }
168602a1a643SAndre Oppermann 
168702a1a643SAndre Oppermann /*
168802a1a643SAndre Oppermann  * Insert TCP options according to the supplied parameters to the place
168902a1a643SAndre Oppermann  * optp in a consistent way.  Can handle unaligned destinations.
169002a1a643SAndre Oppermann  *
169102a1a643SAndre Oppermann  * The order of the option processing is crucial for optimal packing and
169202a1a643SAndre Oppermann  * alignment for the scarce option space.
169302a1a643SAndre Oppermann  *
169402a1a643SAndre Oppermann  * The optimal order for a SYN/SYN-ACK segment is:
169502a1a643SAndre Oppermann  *   MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) +
169602a1a643SAndre Oppermann  *   Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40.
169702a1a643SAndre Oppermann  *
169802a1a643SAndre Oppermann  * The SACK options should be last.  SACK blocks consume 8*n+2 bytes.
169902a1a643SAndre Oppermann  * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks).
170002a1a643SAndre Oppermann  * At minimum we need 10 bytes (to generate 1 SACK block).  If both
170102a1a643SAndre Oppermann  * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present,
170202a1a643SAndre Oppermann  * we only have 10 bytes for SACK options (40 - (12 + 18)).
170302a1a643SAndre Oppermann  */
170402a1a643SAndre Oppermann int
170502a1a643SAndre Oppermann tcp_addoptions(struct tcpopt *to, u_char *optp)
170602a1a643SAndre Oppermann {
17075d20f974SJonathan T. Looney 	u_int32_t mask, optlen = 0;
170802a1a643SAndre Oppermann 
170902a1a643SAndre Oppermann 	for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) {
171002a1a643SAndre Oppermann 		if ((to->to_flags & mask) != mask)
171102a1a643SAndre Oppermann 			continue;
17123a4018c4SAndre Oppermann 		if (optlen == TCP_MAXOLEN)
17133a4018c4SAndre Oppermann 			break;
171402a1a643SAndre Oppermann 		switch (to->to_flags & mask) {
171502a1a643SAndre Oppermann 		case TOF_MSS:
171602a1a643SAndre Oppermann 			while (optlen % 4) {
171702a1a643SAndre Oppermann 				optlen += TCPOLEN_NOP;
171802a1a643SAndre Oppermann 				*optp++ = TCPOPT_NOP;
171902a1a643SAndre Oppermann 			}
17203a4018c4SAndre Oppermann 			if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG)
17213a4018c4SAndre Oppermann 				continue;
172202a1a643SAndre Oppermann 			optlen += TCPOLEN_MAXSEG;
172302a1a643SAndre Oppermann 			*optp++ = TCPOPT_MAXSEG;
172402a1a643SAndre Oppermann 			*optp++ = TCPOLEN_MAXSEG;
172502a1a643SAndre Oppermann 			to->to_mss = htons(to->to_mss);
172602a1a643SAndre Oppermann 			bcopy((u_char *)&to->to_mss, optp, sizeof(to->to_mss));
172702a1a643SAndre Oppermann 			optp += sizeof(to->to_mss);
172802a1a643SAndre Oppermann 			break;
172902a1a643SAndre Oppermann 		case TOF_SCALE:
173002a1a643SAndre Oppermann 			while (!optlen || optlen % 2 != 1) {
173102a1a643SAndre Oppermann 				optlen += TCPOLEN_NOP;
173202a1a643SAndre Oppermann 				*optp++ = TCPOPT_NOP;
173302a1a643SAndre Oppermann 			}
17343a4018c4SAndre Oppermann 			if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW)
17353a4018c4SAndre Oppermann 				continue;
173602a1a643SAndre Oppermann 			optlen += TCPOLEN_WINDOW;
173702a1a643SAndre Oppermann 			*optp++ = TCPOPT_WINDOW;
173802a1a643SAndre Oppermann 			*optp++ = TCPOLEN_WINDOW;
173902a1a643SAndre Oppermann 			*optp++ = to->to_wscale;
174002a1a643SAndre Oppermann 			break;
174102a1a643SAndre Oppermann 		case TOF_SACKPERM:
174202a1a643SAndre Oppermann 			while (optlen % 2) {
174302a1a643SAndre Oppermann 				optlen += TCPOLEN_NOP;
174402a1a643SAndre Oppermann 				*optp++ = TCPOPT_NOP;
174502a1a643SAndre Oppermann 			}
17463a4018c4SAndre Oppermann 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED)
17473a4018c4SAndre Oppermann 				continue;
174802a1a643SAndre Oppermann 			optlen += TCPOLEN_SACK_PERMITTED;
174902a1a643SAndre Oppermann 			*optp++ = TCPOPT_SACK_PERMITTED;
175002a1a643SAndre Oppermann 			*optp++ = TCPOLEN_SACK_PERMITTED;
175102a1a643SAndre Oppermann 			break;
175202a1a643SAndre Oppermann 		case TOF_TS:
175302a1a643SAndre Oppermann 			while (!optlen || optlen % 4 != 2) {
175402a1a643SAndre Oppermann 				optlen += TCPOLEN_NOP;
175502a1a643SAndre Oppermann 				*optp++ = TCPOPT_NOP;
175602a1a643SAndre Oppermann 			}
17573a4018c4SAndre Oppermann 			if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP)
17583a4018c4SAndre Oppermann 				continue;
175902a1a643SAndre Oppermann 			optlen += TCPOLEN_TIMESTAMP;
176002a1a643SAndre Oppermann 			*optp++ = TCPOPT_TIMESTAMP;
176102a1a643SAndre Oppermann 			*optp++ = TCPOLEN_TIMESTAMP;
176202a1a643SAndre Oppermann 			to->to_tsval = htonl(to->to_tsval);
176302a1a643SAndre Oppermann 			to->to_tsecr = htonl(to->to_tsecr);
176402a1a643SAndre Oppermann 			bcopy((u_char *)&to->to_tsval, optp, sizeof(to->to_tsval));
176502a1a643SAndre Oppermann 			optp += sizeof(to->to_tsval);
176602a1a643SAndre Oppermann 			bcopy((u_char *)&to->to_tsecr, optp, sizeof(to->to_tsecr));
176702a1a643SAndre Oppermann 			optp += sizeof(to->to_tsecr);
176802a1a643SAndre Oppermann 			break;
176902a1a643SAndre Oppermann 		case TOF_SIGNATURE:
177002a1a643SAndre Oppermann 			{
177102a1a643SAndre Oppermann 			int siglen = TCPOLEN_SIGNATURE - 2;
177202a1a643SAndre Oppermann 
177302a1a643SAndre Oppermann 			while (!optlen || optlen % 4 != 2) {
177402a1a643SAndre Oppermann 				optlen += TCPOLEN_NOP;
177502a1a643SAndre Oppermann 				*optp++ = TCPOPT_NOP;
177602a1a643SAndre Oppermann 			}
1777fcf59617SAndrey V. Elsukov 			if (TCP_MAXOLEN - optlen < TCPOLEN_SIGNATURE) {
1778fcf59617SAndrey V. Elsukov 				to->to_flags &= ~TOF_SIGNATURE;
177902a1a643SAndre Oppermann 				continue;
1780fcf59617SAndrey V. Elsukov 			}
178102a1a643SAndre Oppermann 			optlen += TCPOLEN_SIGNATURE;
178202a1a643SAndre Oppermann 			*optp++ = TCPOPT_SIGNATURE;
178302a1a643SAndre Oppermann 			*optp++ = TCPOLEN_SIGNATURE;
178402a1a643SAndre Oppermann 			to->to_signature = optp;
178502a1a643SAndre Oppermann 			while (siglen--)
178602a1a643SAndre Oppermann 				 *optp++ = 0;
178702a1a643SAndre Oppermann 			break;
178802a1a643SAndre Oppermann 			}
178902a1a643SAndre Oppermann 		case TOF_SACK:
179002a1a643SAndre Oppermann 			{
179102a1a643SAndre Oppermann 			int sackblks = 0;
179202a1a643SAndre Oppermann 			struct sackblk *sack = (struct sackblk *)to->to_sacks;
179302a1a643SAndre Oppermann 			tcp_seq sack_seq;
179402a1a643SAndre Oppermann 
179502a1a643SAndre Oppermann 			while (!optlen || optlen % 4 != 2) {
179602a1a643SAndre Oppermann 				optlen += TCPOLEN_NOP;
179702a1a643SAndre Oppermann 				*optp++ = TCPOPT_NOP;
179802a1a643SAndre Oppermann 			}
17993a4018c4SAndre Oppermann 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK)
180002a1a643SAndre Oppermann 				continue;
180102a1a643SAndre Oppermann 			optlen += TCPOLEN_SACKHDR;
180202a1a643SAndre Oppermann 			*optp++ = TCPOPT_SACK;
180302a1a643SAndre Oppermann 			sackblks = min(to->to_nsacks,
18040d957bbaSAndre Oppermann 					(TCP_MAXOLEN - optlen) / TCPOLEN_SACK);
180502a1a643SAndre Oppermann 			*optp++ = TCPOLEN_SACKHDR + sackblks * TCPOLEN_SACK;
180602a1a643SAndre Oppermann 			while (sackblks--) {
180702a1a643SAndre Oppermann 				sack_seq = htonl(sack->start);
180802a1a643SAndre Oppermann 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
180902a1a643SAndre Oppermann 				optp += sizeof(sack_seq);
181002a1a643SAndre Oppermann 				sack_seq = htonl(sack->end);
181102a1a643SAndre Oppermann 				bcopy((u_char *)&sack_seq, optp, sizeof(sack_seq));
181202a1a643SAndre Oppermann 				optp += sizeof(sack_seq);
181302a1a643SAndre Oppermann 				optlen += TCPOLEN_SACK;
181402a1a643SAndre Oppermann 				sack++;
181502a1a643SAndre Oppermann 			}
181678b50714SRobert Watson 			TCPSTAT_INC(tcps_sack_send_blocks);
181702a1a643SAndre Oppermann 			break;
181802a1a643SAndre Oppermann 			}
1819281a0fd4SPatrick Kelsey #ifdef TCP_RFC7413
1820281a0fd4SPatrick Kelsey 		case TOF_FASTOPEN:
1821281a0fd4SPatrick Kelsey 			{
1822281a0fd4SPatrick Kelsey 			int total_len;
1823281a0fd4SPatrick Kelsey 
1824281a0fd4SPatrick Kelsey 			/* XXX is there any point to aligning this option? */
1825281a0fd4SPatrick Kelsey 			total_len = TCPOLEN_FAST_OPEN_EMPTY + to->to_tfo_len;
1826281a0fd4SPatrick Kelsey 			if (TCP_MAXOLEN - optlen < total_len)
1827281a0fd4SPatrick Kelsey 				continue;
1828281a0fd4SPatrick Kelsey 			*optp++ = TCPOPT_FAST_OPEN;
1829281a0fd4SPatrick Kelsey 			*optp++ = total_len;
1830281a0fd4SPatrick Kelsey 			if (to->to_tfo_len > 0) {
1831281a0fd4SPatrick Kelsey 				bcopy(to->to_tfo_cookie, optp, to->to_tfo_len);
1832281a0fd4SPatrick Kelsey 				optp += to->to_tfo_len;
1833281a0fd4SPatrick Kelsey 			}
1834281a0fd4SPatrick Kelsey 			optlen += total_len;
1835281a0fd4SPatrick Kelsey 			break;
1836281a0fd4SPatrick Kelsey 			}
1837281a0fd4SPatrick Kelsey #endif
183802a1a643SAndre Oppermann 		default:
183902a1a643SAndre Oppermann 			panic("%s: unknown TCP option type", __func__);
184002a1a643SAndre Oppermann 			break;
184102a1a643SAndre Oppermann 		}
184202a1a643SAndre Oppermann 	}
184302a1a643SAndre Oppermann 
184402a1a643SAndre Oppermann 	/* Terminate and pad TCP options to a 4 byte boundary. */
184502a1a643SAndre Oppermann 	if (optlen % 4) {
184602a1a643SAndre Oppermann 		optlen += TCPOLEN_EOL;
184702a1a643SAndre Oppermann 		*optp++ = TCPOPT_EOL;
184802a1a643SAndre Oppermann 	}
1849413deb12SBjoern A. Zeeb 	/*
1850413deb12SBjoern A. Zeeb 	 * According to RFC 793 (STD0007):
1851413deb12SBjoern A. Zeeb 	 *   "The content of the header beyond the End-of-Option option
1852413deb12SBjoern A. Zeeb 	 *    must be header padding (i.e., zero)."
1853413deb12SBjoern A. Zeeb 	 *   and later: "The padding is composed of zeros."
1854413deb12SBjoern A. Zeeb 	 */
185502a1a643SAndre Oppermann 	while (optlen % 4) {
1856c343c524SAndre Oppermann 		optlen += TCPOLEN_PAD;
1857c343c524SAndre Oppermann 		*optp++ = TCPOPT_PAD;
185802a1a643SAndre Oppermann 	}
185902a1a643SAndre Oppermann 
18600d957bbaSAndre Oppermann 	KASSERT(optlen <= TCP_MAXOLEN, ("%s: TCP options too long", __func__));
186102a1a643SAndre Oppermann 	return (optlen);
186202a1a643SAndre Oppermann }
1863