Home | History | Annotate | Line # | Download | only in netinet
tcp_output.c revision 1.201
      1 /*	$NetBSD: tcp_output.c,v 1.201 2018/03/30 08:53:51 maxv Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  *      @(#)COPYRIGHT   1.1 (NRL) 17 January 1995
     34  *
     35  * NRL grants permission for redistribution and use in source and binary
     36  * forms, with or without modification, of the software and documentation
     37  * created at NRL provided that the following conditions are met:
     38  *
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. All advertising materials mentioning features or use of this software
     45  *    must display the following acknowledgements:
     46  *      This product includes software developed by the University of
     47  *      California, Berkeley and its contributors.
     48  *      This product includes software developed at the Information
     49  *      Technology Division, US Naval Research Laboratory.
     50  * 4. Neither the name of the NRL nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
     55  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     56  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
     57  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
     58  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     59  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     60  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     61  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
     62  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
     63  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     64  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     65  *
     66  * The views and conclusions contained in the software and documentation
     67  * are those of the authors and should not be interpreted as representing
     68  * official policies, either expressed or implied, of the US Naval
     69  * Research Laboratory (NRL).
     70  */
     71 
     72 /*-
     73  * Copyright (c) 1997, 1998, 2001, 2005, 2006 The NetBSD Foundation, Inc.
     74  * All rights reserved.
     75  *
     76  * This code is derived from software contributed to The NetBSD Foundation
     77  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
     78  * Facility, NASA Ames Research Center.
     79  * This code is derived from software contributed to The NetBSD Foundation
     80  * by Charles M. Hannum.
     81  * This code is derived from software contributed to The NetBSD Foundation
     82  * by Rui Paulo.
     83  *
     84  * Redistribution and use in source and binary forms, with or without
     85  * modification, are permitted provided that the following conditions
     86  * are met:
     87  * 1. Redistributions of source code must retain the above copyright
     88  *    notice, this list of conditions and the following disclaimer.
     89  * 2. Redistributions in binary form must reproduce the above copyright
     90  *    notice, this list of conditions and the following disclaimer in the
     91  *    documentation and/or other materials provided with the distribution.
     92  *
     93  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     94  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     95  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     96  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     97  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     98  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     99  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    100  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    101  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    103  * POSSIBILITY OF SUCH DAMAGE.
    104  */
    105 
    106 /*
    107  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
    108  *	The Regents of the University of California.  All rights reserved.
    109  *
    110  * Redistribution and use in source and binary forms, with or without
    111  * modification, are permitted provided that the following conditions
    112  * are met:
    113  * 1. Redistributions of source code must retain the above copyright
    114  *    notice, this list of conditions and the following disclaimer.
    115  * 2. Redistributions in binary form must reproduce the above copyright
    116  *    notice, this list of conditions and the following disclaimer in the
    117  *    documentation and/or other materials provided with the distribution.
    118  * 3. Neither the name of the University nor the names of its contributors
    119  *    may be used to endorse or promote products derived from this software
    120  *    without specific prior written permission.
    121  *
    122  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
    123  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    124  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    125  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
    126  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    127  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    128  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    129  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    130  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    131  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    132  * SUCH DAMAGE.
    133  *
    134  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
    135  */
    136 
    137 #include <sys/cdefs.h>
    138 __KERNEL_RCSID(0, "$NetBSD: tcp_output.c,v 1.201 2018/03/30 08:53:51 maxv Exp $");
    139 
    140 #ifdef _KERNEL_OPT
    141 #include "opt_inet.h"
    142 #include "opt_ipsec.h"
    143 #include "opt_tcp_debug.h"
    144 #endif
    145 
    146 #include <sys/param.h>
    147 #include <sys/systm.h>
    148 #include <sys/mbuf.h>
    149 #include <sys/protosw.h>
    150 #include <sys/socket.h>
    151 #include <sys/socketvar.h>
    152 #include <sys/errno.h>
    153 #include <sys/domain.h>
    154 #include <sys/kernel.h>
    155 #ifdef TCP_SIGNATURE
    156 #include <sys/md5.h>
    157 #endif
    158 
    159 #include <net/if.h>
    160 #include <net/route.h>
    161 
    162 #include <netinet/in.h>
    163 #include <netinet/in_systm.h>
    164 #include <netinet/ip.h>
    165 #include <netinet/in_pcb.h>
    166 #include <netinet/ip_var.h>
    167 
    168 #ifdef INET6
    169 #include <netinet/ip6.h>
    170 #include <netinet6/in6_var.h>
    171 #include <netinet6/ip6_var.h>
    172 #include <netinet6/in6_pcb.h>
    173 #include <netinet6/nd6.h>
    174 #endif
    175 
    176 #ifdef IPSEC
    177 #include <netipsec/ipsec.h>
    178 #include <netipsec/key.h>
    179 #ifdef INET6
    180 #include <netipsec/ipsec6.h>
    181 #endif
    182 #endif
    183 
    184 #include <netinet/tcp.h>
    185 #define	TCPOUTFLAGS
    186 #include <netinet/tcp_fsm.h>
    187 #include <netinet/tcp_seq.h>
    188 #include <netinet/tcp_timer.h>
    189 #include <netinet/tcp_var.h>
    190 #include <netinet/tcp_private.h>
    191 #include <netinet/tcp_congctl.h>
    192 #include <netinet/tcpip.h>
    193 #include <netinet/tcp_debug.h>
    194 #include <netinet/in_offload.h>
    195 #include <netinet6/in6_offload.h>
    196 
    197 #ifdef notyet
    198 extern struct mbuf *m_copypack();
    199 #endif
    200 
    201 /*
    202  * Knob to enable Congestion Window Monitoring, and control
    203  * the burst size it allows.  Default burst is 4 packets, per
    204  * the Internet draft.
    205  */
    206 int	tcp_cwm = 0;
    207 int	tcp_cwm_burstsize = 4;
    208 
    209 int	tcp_do_autosndbuf = 1;
    210 int	tcp_autosndbuf_inc = 8 * 1024;
    211 int	tcp_autosndbuf_max = 256 * 1024;
    212 
    213 #ifdef TCP_OUTPUT_COUNTERS
    214 #include <sys/device.h>
    215 
    216 extern struct evcnt tcp_output_bigheader;
    217 extern struct evcnt tcp_output_predict_hit;
    218 extern struct evcnt tcp_output_predict_miss;
    219 extern struct evcnt tcp_output_copysmall;
    220 extern struct evcnt tcp_output_copybig;
    221 extern struct evcnt tcp_output_refbig;
    222 
    223 #define	TCP_OUTPUT_COUNTER_INCR(ev)	(ev)->ev_count++
    224 #else
    225 
    226 #define	TCP_OUTPUT_COUNTER_INCR(ev)	/* nothing */
    227 
    228 #endif /* TCP_OUTPUT_COUNTERS */
    229 
    230 static int
    231 tcp_segsize(struct tcpcb *tp, int *txsegsizep, int *rxsegsizep,
    232     bool *alwaysfragp)
    233 {
    234 	struct inpcb *inp = tp->t_inpcb;
    235 #ifdef INET6
    236 	struct in6pcb *in6p = tp->t_in6pcb;
    237 #endif
    238 	struct socket *so = NULL;
    239 	struct rtentry *rt;
    240 	struct ifnet *ifp;
    241 	int size;
    242 	int hdrlen;
    243 	int optlen;
    244 
    245 	*alwaysfragp = false;
    246 
    247 	KASSERT(!(tp->t_inpcb && tp->t_in6pcb));
    248 
    249 	switch (tp->t_family) {
    250 	case AF_INET:
    251 		hdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
    252 		break;
    253 #ifdef INET6
    254 	case AF_INET6:
    255 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    256 		break;
    257 #endif
    258 	default:
    259 		size = tcp_mssdflt;
    260 		goto out;
    261 	}
    262 
    263 	rt = NULL;
    264 	if (inp) {
    265 		rt = in_pcbrtentry(inp);
    266 		so = inp->inp_socket;
    267 	}
    268 #ifdef INET6
    269 	if (in6p) {
    270 		rt = in6_pcbrtentry(in6p);
    271 		so = in6p->in6p_socket;
    272 	}
    273 #endif
    274 	if (rt == NULL) {
    275 		size = tcp_mssdflt;
    276 		goto out;
    277 	}
    278 
    279 	ifp = rt->rt_ifp;
    280 
    281 	size = tcp_mssdflt;
    282 	if (tp->t_mtudisc && rt->rt_rmx.rmx_mtu != 0) {
    283 #ifdef INET6
    284 		if (in6p && rt->rt_rmx.rmx_mtu < IPV6_MMTU) {
    285 			/*
    286 			 * RFC2460 section 5, last paragraph: if path MTU is
    287 			 * smaller than 1280, use 1280 as packet size and
    288 			 * attach fragment header.
    289 			 */
    290 			size = IPV6_MMTU - hdrlen - sizeof(struct ip6_frag);
    291 			*alwaysfragp = true;
    292 		} else
    293 			size = rt->rt_rmx.rmx_mtu - hdrlen;
    294 #else
    295 		size = rt->rt_rmx.rmx_mtu - hdrlen;
    296 #endif
    297 	} else if (ifp->if_flags & IFF_LOOPBACK)
    298 		size = ifp->if_mtu - hdrlen;
    299 	else if (inp && tp->t_mtudisc)
    300 		size = ifp->if_mtu - hdrlen;
    301 	else if (inp && in_localaddr(inp->inp_faddr))
    302 		size = ifp->if_mtu - hdrlen;
    303 #ifdef INET6
    304 	else if (in6p) {
    305 		if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr)) {
    306 			/* mapped addr case */
    307 			struct in_addr d;
    308 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &d, sizeof(d));
    309 			if (tp->t_mtudisc || in_localaddr(d))
    310 				size = ifp->if_mtu - hdrlen;
    311 		} else {
    312 			/*
    313 			 * for IPv6, path MTU discovery is always turned on,
    314 			 * or the node must use packet size <= 1280.
    315 			 */
    316 			size = tp->t_mtudisc ? IN6_LINKMTU(ifp) : IPV6_MMTU;
    317 			size -= hdrlen;
    318 		}
    319 	}
    320 #endif
    321 	if (inp)
    322 		in_pcbrtentry_unref(rt, inp);
    323 #ifdef INET6
    324 	if (in6p)
    325 		in6_pcbrtentry_unref(rt, in6p);
    326 #endif
    327  out:
    328 	/*
    329 	 * Now we must make room for whatever extra TCP/IP options are in
    330 	 * the packet.
    331 	 */
    332 	optlen = tcp_optlen(tp);
    333 
    334 	/*
    335 	 * XXX tp->t_ourmss should have the right size, but without this code
    336 	 * fragmentation will occur... need more investigation
    337 	 */
    338 
    339 	if (inp) {
    340 #if defined(IPSEC)
    341 		if (ipsec_used &&
    342 		    !ipsec_pcb_skip_ipsec(inp->inp_sp, IPSEC_DIR_OUTBOUND))
    343 			optlen += ipsec4_hdrsiz_tcp(tp);
    344 #endif
    345 		optlen += ip_optlen(inp);
    346 	}
    347 
    348 #ifdef INET6
    349 	if (in6p && tp->t_family == AF_INET) {
    350 #if defined(IPSEC)
    351 		if (ipsec_used &&
    352 		    !ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND))
    353 			optlen += ipsec4_hdrsiz_tcp(tp);
    354 #endif
    355 		/* XXX size -= ip_optlen(in6p); */
    356 	} else if (in6p && tp->t_family == AF_INET6) {
    357 #if defined(IPSEC)
    358 		if (ipsec_used &&
    359 		    !ipsec_pcb_skip_ipsec(in6p->in6p_sp, IPSEC_DIR_OUTBOUND))
    360 			optlen += ipsec6_hdrsiz_tcp(tp);
    361 #endif
    362 		optlen += ip6_optlen(in6p);
    363 	}
    364 #endif
    365 	size -= optlen;
    366 
    367 	/* there may not be any room for data if mtu is too small */
    368 	if (size < 0)
    369 		return EMSGSIZE;
    370 
    371 	/*
    372 	 * *rxsegsizep holds *estimated* inbound segment size (estimation
    373 	 * assumes that path MTU is the same for both ways).  this is only
    374 	 * for silly window avoidance, do not use the value for other purposes.
    375 	 *
    376 	 * ipseclen is subtracted from both sides, this may not be right.
    377 	 * I'm not quite sure about this (could someone comment).
    378 	 */
    379 	*txsegsizep = min(tp->t_peermss - optlen, size);
    380 	/*
    381 	 * Never send more than half a buffer full.  This insures that we can
    382 	 * always keep 2 packets on the wire, no matter what SO_SNDBUF is, and
    383 	 * therefore acks will never be delayed unless we run out of data to
    384 	 * transmit.
    385 	 */
    386 	if (so)
    387 		*txsegsizep = min(so->so_snd.sb_hiwat >> 1, *txsegsizep);
    388 	*rxsegsizep = min(tp->t_ourmss - optlen, size);
    389 
    390 	if (*txsegsizep != tp->t_segsz) {
    391 		/*
    392 		 * If the new segment size is larger, we don't want to
    393 		 * mess up the congestion window, but if it is smaller
    394 		 * we'll have to reduce the congestion window to ensure
    395 		 * that we don't get into trouble with initial windows
    396 		 * and the rest.  In any case, if the segment size
    397 		 * has changed, chances are the path has, too, and
    398 		 * our congestion window will be different.
    399 		 */
    400 		if (*txsegsizep < tp->t_segsz) {
    401 			tp->snd_cwnd = max((tp->snd_cwnd / tp->t_segsz)
    402 					   * *txsegsizep, *txsegsizep);
    403 			tp->snd_ssthresh = max((tp->snd_ssthresh / tp->t_segsz)
    404 						* *txsegsizep, *txsegsizep);
    405 		}
    406 		tp->t_segsz = *txsegsizep;
    407 	}
    408 
    409 	return 0;
    410 }
    411 
    412 static int
    413 tcp_build_datapkt(struct tcpcb *tp, struct socket *so, int off,
    414     long len, int hdrlen, struct mbuf **mp)
    415 {
    416 	struct mbuf *m, *m0;
    417 	uint64_t *tcps;
    418 
    419 	tcps = TCP_STAT_GETREF();
    420 	if (tp->t_force && len == 1)
    421 		tcps[TCP_STAT_SNDPROBE]++;
    422 	else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
    423 		tp->t_sndrexmitpack++;
    424 		tcps[TCP_STAT_SNDREXMITPACK]++;
    425 		tcps[TCP_STAT_SNDREXMITBYTE] += len;
    426 	} else {
    427 		tcps[TCP_STAT_SNDPACK]++;
    428 		tcps[TCP_STAT_SNDBYTE] += len;
    429 	}
    430 	TCP_STAT_PUTREF();
    431 #ifdef notyet
    432 	if ((m = m_copypack(so->so_snd.sb_mb, off,
    433 	    (int)len, max_linkhdr + hdrlen)) == 0)
    434 		return ENOBUFS;
    435 	/*
    436 	 * m_copypack left space for our hdr; use it.
    437 	 */
    438 	m->m_len += hdrlen;
    439 	m->m_data -= hdrlen;
    440 #else
    441 	MGETHDR(m, M_DONTWAIT, MT_HEADER);
    442 	if (__predict_false(m == NULL))
    443 		return ENOBUFS;
    444 	MCLAIM(m, &tcp_tx_mowner);
    445 
    446 	/*
    447 	 * XXX Because other code assumes headers will fit in
    448 	 * XXX one header mbuf.
    449 	 *
    450 	 * (This code should almost *never* be run.)
    451 	 */
    452 	if (__predict_false((max_linkhdr + hdrlen) > MHLEN)) {
    453 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_bigheader);
    454 		MCLGET(m, M_DONTWAIT);
    455 		if ((m->m_flags & M_EXT) == 0) {
    456 			m_freem(m);
    457 			return ENOBUFS;
    458 		}
    459 	}
    460 
    461 	m->m_data += max_linkhdr;
    462 	m->m_len = hdrlen;
    463 
    464 	/*
    465 	 * To avoid traversing the whole sb_mb chain for correct
    466 	 * data to send, remember last sent mbuf, its offset and
    467 	 * the sent size.  When called the next time, see if the
    468 	 * data to send is directly following the previous transfer.
    469 	 * This is important for large TCP windows.
    470 	 */
    471 	if (off == 0 || tp->t_lastm == NULL ||
    472 	    (tp->t_lastoff + tp->t_lastlen) != off) {
    473 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_predict_miss);
    474 		/*
    475 		 * Either a new packet or a retransmit.
    476 		 * Start from the beginning.
    477 		 */
    478 		tp->t_lastm = so->so_snd.sb_mb;
    479 		tp->t_inoff = off;
    480 	} else {
    481 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_predict_hit);
    482 		tp->t_inoff += tp->t_lastlen;
    483 	}
    484 
    485 	/* Traverse forward to next packet */
    486 	while (tp->t_inoff > 0) {
    487 		if (tp->t_lastm == NULL)
    488 			panic("tp->t_lastm == NULL");
    489 		if (tp->t_inoff < tp->t_lastm->m_len)
    490 			break;
    491 		tp->t_inoff -= tp->t_lastm->m_len;
    492 		tp->t_lastm = tp->t_lastm->m_next;
    493 	}
    494 
    495 	tp->t_lastoff = off;
    496 	tp->t_lastlen = len;
    497 	m0 = tp->t_lastm;
    498 	off = tp->t_inoff;
    499 
    500 	if (len <= M_TRAILINGSPACE(m)) {
    501 		m_copydata(m0, off, (int)len, mtod(m, char *) + hdrlen);
    502 		m->m_len += len;
    503 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_copysmall);
    504 	} else {
    505 		m->m_next = m_copym(m0, off, (int)len, M_DONTWAIT);
    506 		if (m->m_next == NULL) {
    507 			m_freem(m);
    508 			return ENOBUFS;
    509 		}
    510 #ifdef TCP_OUTPUT_COUNTERS
    511 		if (m->m_next->m_flags & M_EXT)
    512 			TCP_OUTPUT_COUNTER_INCR(&tcp_output_refbig);
    513 		else
    514 			TCP_OUTPUT_COUNTER_INCR(&tcp_output_copybig);
    515 #endif
    516 	}
    517 #endif
    518 
    519 	*mp = m;
    520 	return 0;
    521 }
    522 
    523 /*
    524  * Tcp output routine: figure out what should be sent and send it.
    525  */
    526 int
    527 tcp_output(struct tcpcb *tp)
    528 {
    529 	struct rtentry *rt = NULL;
    530 	struct socket *so;
    531 	struct route *ro;
    532 	long len, win;
    533 	int off, flags, error;
    534 	struct mbuf *m;
    535 	struct ip *ip;
    536 #ifdef INET6
    537 	struct ip6_hdr *ip6;
    538 #endif
    539 	struct tcphdr *th;
    540 	u_char opt[MAX_TCPOPTLEN], *optp;
    541 #define OPT_FITS(more)	((optlen + (more)) <= sizeof(opt))
    542 	unsigned optlen, hdrlen, packetlen;
    543 	unsigned int sack_numblks;
    544 	int idle, sendalot, txsegsize, rxsegsize;
    545 	int txsegsize_nosack;
    546 	int maxburst = TCP_MAXBURST;
    547 	int af;		/* address family on the wire */
    548 	int iphdrlen;
    549 	int has_tso4, has_tso6;
    550 	int has_tso, use_tso;
    551 	bool alwaysfrag;
    552 	int sack_rxmit;
    553 	int sack_bytes_rxmt;
    554 	int ecn_tos;
    555 	struct sackhole *p;
    556 #ifdef TCP_SIGNATURE
    557 	int sigoff = 0;
    558 #endif
    559 	uint64_t *tcps;
    560 
    561 	KASSERT(!(tp->t_inpcb && tp->t_in6pcb));
    562 
    563 	so = NULL;
    564 	ro = NULL;
    565 	if (tp->t_inpcb) {
    566 		so = tp->t_inpcb->inp_socket;
    567 		ro = &tp->t_inpcb->inp_route;
    568 	}
    569 #ifdef INET6
    570 	else if (tp->t_in6pcb) {
    571 		so = tp->t_in6pcb->in6p_socket;
    572 		ro = &tp->t_in6pcb->in6p_route;
    573 	}
    574 #endif
    575 
    576 	switch (af = tp->t_family) {
    577 	case AF_INET:
    578 		if (tp->t_inpcb)
    579 			break;
    580 #ifdef INET6
    581 		/* mapped addr case */
    582 		if (tp->t_in6pcb)
    583 			break;
    584 #endif
    585 		return EINVAL;
    586 #ifdef INET6
    587 	case AF_INET6:
    588 		if (tp->t_in6pcb)
    589 			break;
    590 		return EINVAL;
    591 #endif
    592 	default:
    593 		return EAFNOSUPPORT;
    594 	}
    595 
    596 	if (tcp_segsize(tp, &txsegsize, &rxsegsize, &alwaysfrag))
    597 		return EMSGSIZE;
    598 
    599 	idle = (tp->snd_max == tp->snd_una);
    600 
    601 	/*
    602 	 * Determine if we can use TCP segmentation offload:
    603 	 * - If we're using IPv4
    604 	 * - If there is not an IPsec policy that prevents it
    605 	 * - If the interface can do it
    606 	 */
    607 	has_tso4 = has_tso6 = false;
    608 
    609 	has_tso4 = tp->t_inpcb != NULL &&
    610 #if defined(IPSEC)
    611 	    (!ipsec_used || ipsec_pcb_skip_ipsec(tp->t_inpcb->inp_sp,
    612 	    IPSEC_DIR_OUTBOUND)) &&
    613 #endif
    614 	    (rt = rtcache_validate(&tp->t_inpcb->inp_route)) != NULL &&
    615 	    (rt->rt_ifp->if_capenable & IFCAP_TSOv4) != 0;
    616 	if (rt != NULL) {
    617 		rtcache_unref(rt, &tp->t_inpcb->inp_route);
    618 		rt = NULL;
    619 	}
    620 
    621 #if defined(INET6)
    622 	has_tso6 = tp->t_in6pcb != NULL &&
    623 #if defined(IPSEC)
    624 	    (!ipsec_used || ipsec_pcb_skip_ipsec(tp->t_in6pcb->in6p_sp,
    625 	    IPSEC_DIR_OUTBOUND)) &&
    626 #endif
    627 	    (rt = rtcache_validate(&tp->t_in6pcb->in6p_route)) != NULL &&
    628 	    (rt->rt_ifp->if_capenable & IFCAP_TSOv6) != 0;
    629 	if (rt != NULL)
    630 		rtcache_unref(rt, &tp->t_in6pcb->in6p_route);
    631 #endif /* defined(INET6) */
    632 	has_tso = (has_tso4 || has_tso6) && !alwaysfrag;
    633 
    634 	/*
    635 	 * Restart Window computation.  From draft-floyd-incr-init-win-03:
    636 	 *
    637 	 *	Optionally, a TCP MAY set the restart window to the
    638 	 *	minimum of the value used for the initial window and
    639 	 *	the current value of cwnd (in other words, using a
    640 	 *	larger value for the restart window should never increase
    641 	 *	the size of cwnd).
    642 	 */
    643 	if (tcp_cwm) {
    644 		/*
    645 		 * Hughes/Touch/Heidemann Congestion Window Monitoring.
    646 		 * Count the number of packets currently pending
    647 		 * acknowledgement, and limit our congestion window
    648 		 * to a pre-determined allowed burst size plus that count.
    649 		 * This prevents bursting once all pending packets have
    650 		 * been acknowledged (i.e. transmission is idle).
    651 		 *
    652 		 * XXX Link this to Initial Window?
    653 		 */
    654 		tp->snd_cwnd = min(tp->snd_cwnd,
    655 		    (tcp_cwm_burstsize * txsegsize) +
    656 		    (tp->snd_nxt - tp->snd_una));
    657 	} else {
    658 		if (idle && (tcp_now - tp->t_rcvtime) >= tp->t_rxtcur) {
    659 			/*
    660 			 * We have been idle for "a while" and no acks are
    661 			 * expected to clock out any data we send --
    662 			 * slow start to get ack "clock" running again.
    663 			 */
    664 			int ss = tcp_init_win;
    665 			if (tp->t_inpcb &&
    666 			    in_localaddr(tp->t_inpcb->inp_faddr))
    667 				ss = tcp_init_win_local;
    668 #ifdef INET6
    669 			if (tp->t_in6pcb &&
    670 			    in6_localaddr(&tp->t_in6pcb->in6p_faddr))
    671 				ss = tcp_init_win_local;
    672 #endif
    673 			tp->snd_cwnd = min(tp->snd_cwnd,
    674 			    TCP_INITIAL_WINDOW(ss, txsegsize));
    675 		}
    676 	}
    677 
    678 	txsegsize_nosack = txsegsize;
    679 again:
    680 	ecn_tos = 0;
    681 	use_tso = has_tso;
    682 	if ((tp->t_flags & (TF_ECN_SND_CWR|TF_ECN_SND_ECE)) != 0) {
    683 		/* don't duplicate CWR/ECE. */
    684 		use_tso = 0;
    685 	}
    686 	TCP_REASS_LOCK(tp);
    687 	sack_numblks = tcp_sack_numblks(tp);
    688 	if (sack_numblks) {
    689 		int sackoptlen;
    690 
    691 		sackoptlen = TCP_SACK_OPTLEN(sack_numblks);
    692 		if (sackoptlen > txsegsize_nosack) {
    693 			sack_numblks = 0; /* give up SACK */
    694 			txsegsize = txsegsize_nosack;
    695 		} else {
    696 			if ((tp->rcv_sack_flags & TCPSACK_HAVED) != 0) {
    697 				/* don't duplicate D-SACK. */
    698 				use_tso = 0;
    699 			}
    700 			txsegsize = txsegsize_nosack - sackoptlen;
    701 		}
    702 	} else {
    703 		txsegsize = txsegsize_nosack;
    704 	}
    705 
    706 	/*
    707 	 * Determine length of data that should be transmitted, and
    708 	 * flags that should be used.  If there is some data or critical
    709 	 * controls (SYN, RST) to send, then transmit; otherwise,
    710 	 * investigate further.
    711 	 *
    712 	 * Readjust SACK information to avoid resending duplicate data.
    713 	 */
    714 	if (TCP_SACK_ENABLED(tp) && SEQ_LT(tp->snd_nxt, tp->snd_max))
    715 		tcp_sack_adjust(tp);
    716 	sendalot = 0;
    717 	off = tp->snd_nxt - tp->snd_una;
    718 	win = min(tp->snd_wnd, tp->snd_cwnd);
    719 
    720 	flags = tcp_outflags[tp->t_state];
    721 
    722 	/*
    723 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
    724 	 * to send out new data (when sendalot is 1), bypass this function.
    725 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
    726 	 * we're replacing a (future) new transmission with a retransmission
    727 	 * now, and we previously incremented snd_cwnd in tcp_input().
    728 	 */
    729 	/*
    730 	 * Still in sack recovery, reset rxmit flag to zero.
    731 	 */
    732 	sack_rxmit = 0;
    733 	sack_bytes_rxmt = 0;
    734 	len = 0;
    735 	p = NULL;
    736 	do {
    737 		long cwin;
    738 		if (!TCP_SACK_ENABLED(tp))
    739 			break;
    740 		if (tp->t_partialacks < 0)
    741 			break;
    742 		p = tcp_sack_output(tp, &sack_bytes_rxmt);
    743 		if (p == NULL)
    744 			break;
    745 
    746 		cwin = min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
    747 		if (cwin < 0)
    748 			cwin = 0;
    749 		/* Do not retransmit SACK segments beyond snd_recover */
    750 		if (SEQ_GT(p->end, tp->snd_recover)) {
    751 			/*
    752 			 * (At least) part of sack hole extends beyond
    753 			 * snd_recover. Check to see if we can rexmit data
    754 			 * for this hole.
    755 			 */
    756 			if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
    757 				/*
    758 				 * Can't rexmit any more data for this hole.
    759 				 * That data will be rexmitted in the next
    760 				 * sack recovery episode, when snd_recover
    761 				 * moves past p->rxmit.
    762 				 */
    763 				p = NULL;
    764 				break;
    765 			}
    766 			/* Can rexmit part of the current hole */
    767 			len = ((long)ulmin(cwin, tp->snd_recover - p->rxmit));
    768 		} else
    769 			len = ((long)ulmin(cwin, p->end - p->rxmit));
    770 		off = p->rxmit - tp->snd_una;
    771 		if (off + len > so->so_snd.sb_cc) {
    772 			/* 1 for TH_FIN */
    773 			KASSERT(off + len == so->so_snd.sb_cc + 1);
    774 			KASSERT(p->rxmit + len == tp->snd_max);
    775 			len = so->so_snd.sb_cc - off;
    776 		}
    777 		if (len > 0) {
    778 			sack_rxmit = 1;
    779 			sendalot = 1;
    780 		}
    781 	} while (/*CONSTCOND*/0);
    782 
    783 	/*
    784 	 * If in persist timeout with window of 0, send 1 byte.
    785 	 * Otherwise, if window is small but nonzero
    786 	 * and timer expired, we will send what we can
    787 	 * and go to transmit state.
    788 	 */
    789 	if (tp->t_force) {
    790 		if (win == 0) {
    791 			/*
    792 			 * If we still have some data to send, then
    793 			 * clear the FIN bit.  Usually this would
    794 			 * happen below when it realizes that we
    795 			 * aren't sending all the data.  However,
    796 			 * if we have exactly 1 byte of unset data,
    797 			 * then it won't clear the FIN bit below,
    798 			 * and if we are in persist state, we wind
    799 			 * up sending the packet without recording
    800 			 * that we sent the FIN bit.
    801 			 *
    802 			 * We can't just blindly clear the FIN bit,
    803 			 * because if we don't have any more data
    804 			 * to send then the probe will be the FIN
    805 			 * itself.
    806 			 */
    807 			if (off < so->so_snd.sb_cc)
    808 				flags &= ~TH_FIN;
    809 			win = 1;
    810 		} else {
    811 			TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    812 			tp->t_rxtshift = 0;
    813 		}
    814 	}
    815 
    816 	if (sack_rxmit == 0) {
    817 		if (TCP_SACK_ENABLED(tp) && tp->t_partialacks >= 0) {
    818 			long cwin;
    819 
    820 			/*
    821 			 * We are inside of a SACK recovery episode and are
    822 			 * sending new data, having retransmitted all the
    823 			 * data possible in the scoreboard.
    824 			 */
    825 			if (tp->snd_wnd < so->so_snd.sb_cc) {
    826 				len = tp->snd_wnd - off;
    827 				flags &= ~TH_FIN;
    828 			} else {
    829 				len = so->so_snd.sb_cc - off;
    830 			}
    831 
    832 			/*
    833 			 * From FreeBSD:
    834 			 *  Don't remove this (len > 0) check !
    835 			 *  We explicitly check for len > 0 here (although it
    836 			 *  isn't really necessary), to work around a gcc
    837 			 *  optimization issue - to force gcc to compute
    838 			 *  len above. Without this check, the computation
    839 			 *  of len is bungled by the optimizer.
    840 			 */
    841 			if (len > 0) {
    842 				cwin = tp->snd_cwnd -
    843 				    (tp->snd_nxt - tp->sack_newdata) -
    844 				    sack_bytes_rxmt;
    845 				if (cwin < 0)
    846 					cwin = 0;
    847 				if (cwin < len) {
    848 					len = cwin;
    849 					flags &= ~TH_FIN;
    850 				}
    851 			}
    852 		} else if (win < so->so_snd.sb_cc) {
    853 			len = win - off;
    854 			flags &= ~TH_FIN;
    855 		} else {
    856 			len = so->so_snd.sb_cc - off;
    857 		}
    858 	}
    859 
    860 	if (len < 0) {
    861 		/*
    862 		 * If FIN has been sent but not acked,
    863 		 * but we haven't been called to retransmit,
    864 		 * len will be -1.  Otherwise, window shrank
    865 		 * after we sent into it.  If window shrank to 0,
    866 		 * cancel pending retransmit, pull snd_nxt back
    867 		 * to (closed) window, and set the persist timer
    868 		 * if it isn't already going.  If the window didn't
    869 		 * close completely, just wait for an ACK.
    870 		 *
    871 		 * If we have a pending FIN, either it has already been
    872 		 * transmitted or it is outside the window, so drop it.
    873 		 * If the FIN has been transmitted, but this is not a
    874 		 * retransmission, then len must be -1.  Therefore we also
    875 		 * prevent here the sending of `gratuitous FINs'.  This
    876 		 * eliminates the need to check for that case below (e.g.
    877 		 * to back up snd_nxt before the FIN so that the sequence
    878 		 * number is correct).
    879 		 */
    880 		len = 0;
    881 		flags &= ~TH_FIN;
    882 		if (win == 0) {
    883 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
    884 			tp->t_rxtshift = 0;
    885 			tp->snd_nxt = tp->snd_una;
    886 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
    887 				tcp_setpersist(tp);
    888 		}
    889 	}
    890 
    891 	/*
    892 	 * Automatic sizing enables the performance of large buffers
    893 	 * and most of the efficiency of small ones by only allocating
    894 	 * space when it is needed.
    895 	 *
    896 	 * The criteria to step up the send buffer one notch are:
    897 	 *  1. receive window of remote host is larger than send buffer
    898 	 *     (with a fudge factor of 5/4th);
    899 	 *  2. send buffer is filled to 7/8th with data (so we actually
    900 	 *     have data to make use of it);
    901 	 *  3. send buffer fill has not hit maximal automatic size;
    902 	 *  4. our send window (slow start and cogestion controlled) is
    903 	 *     larger than sent but unacknowledged data in send buffer.
    904 	 *
    905 	 * The remote host receive window scaling factor may limit the
    906 	 * growing of the send buffer before it reaches its allowed
    907 	 * maximum.
    908 	 *
    909 	 * It scales directly with slow start or congestion window
    910 	 * and does at most one step per received ACK.  This fast
    911 	 * scaling has the drawback of growing the send buffer beyond
    912 	 * what is strictly necessary to make full use of a given
    913 	 * delay*bandwith product.  However testing has shown this not
    914 	 * to be much of an problem.  At worst we are trading wasting
    915 	 * of available bandwith (the non-use of it) for wasting some
    916 	 * socket buffer memory.
    917 	 *
    918 	 * TODO: Shrink send buffer during idle periods together
    919 	 * with congestion window.  Requires another timer.
    920 	 */
    921 	if (tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
    922 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
    923 		    so->so_snd.sb_cc >= (so->so_snd.sb_hiwat / 8 * 7) &&
    924 		    so->so_snd.sb_cc < tcp_autosndbuf_max &&
    925 		    win >= (so->so_snd.sb_cc - (tp->snd_nxt - tp->snd_una))) {
    926 			if (!sbreserve(&so->so_snd,
    927 			    min(so->so_snd.sb_hiwat + tcp_autosndbuf_inc,
    928 			     tcp_autosndbuf_max), so))
    929 				so->so_snd.sb_flags &= ~SB_AUTOSIZE;
    930 		}
    931 	}
    932 
    933 	if (len > txsegsize) {
    934 		if (use_tso) {
    935 			/*
    936 			 * Truncate TSO transfers to IP_MAXPACKET, and make
    937 			 * sure that we send equal size transfers down the
    938 			 * stack (rather than big-small-big-small-...).
    939 			 */
    940 #ifdef INET6
    941 			CTASSERT(IPV6_MAXPACKET == IP_MAXPACKET);
    942 #endif
    943 			len = (min(len, IP_MAXPACKET) / txsegsize) * txsegsize;
    944 			if (len <= txsegsize) {
    945 				use_tso = 0;
    946 			}
    947 		} else
    948 			len = txsegsize;
    949 		flags &= ~TH_FIN;
    950 		sendalot = 1;
    951 	} else
    952 		use_tso = 0;
    953 	if (sack_rxmit) {
    954 		if (SEQ_LT(p->rxmit + len, tp->snd_una + so->so_snd.sb_cc))
    955 			flags &= ~TH_FIN;
    956 	}
    957 
    958 	win = sbspace(&so->so_rcv);
    959 
    960 	/*
    961 	 * Sender silly window avoidance.  If connection is idle
    962 	 * and can send all data, a maximum segment,
    963 	 * at least a maximum default-size segment do it,
    964 	 * or are forced, do it; otherwise don't bother.
    965 	 * If peer's buffer is tiny, then send
    966 	 * when window is at least half open.
    967 	 * If retransmitting (possibly after persist timer forced us
    968 	 * to send into a small window), then must resend.
    969 	 */
    970 	if (len) {
    971 		if (len >= txsegsize)
    972 			goto send;
    973 		if ((so->so_state & SS_MORETOCOME) == 0 &&
    974 		    ((idle || tp->t_flags & TF_NODELAY) &&
    975 		     len + off >= so->so_snd.sb_cc))
    976 			goto send;
    977 		if (tp->t_force)
    978 			goto send;
    979 		if (len >= tp->max_sndwnd / 2)
    980 			goto send;
    981 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
    982 			goto send;
    983 		if (sack_rxmit)
    984 			goto send;
    985 	}
    986 
    987 	/*
    988 	 * Compare available window to amount of window known to peer
    989 	 * (as advertised window less next expected input).  If the
    990 	 * difference is at least twice the size of the largest segment
    991 	 * we expect to receive (i.e. two segments) or at least 50% of
    992 	 * the maximum possible window, then want to send a window update
    993 	 * to peer.
    994 	 */
    995 	if (win > 0) {
    996 		/*
    997 		 * "adv" is the amount we can increase the window,
    998 		 * taking into account that we are limited by
    999 		 * TCP_MAXWIN << tp->rcv_scale.
   1000 		 */
   1001 		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
   1002 			(tp->rcv_adv - tp->rcv_nxt);
   1003 
   1004 		/*
   1005 		 * If the new window size ends up being the same as the old
   1006 		 * size when it is scaled, then don't force a window update.
   1007 		 */
   1008 		if ((tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale ==
   1009 		    (adv + tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale)
   1010 			goto dontupdate;
   1011 		if (adv >= (long) (2 * rxsegsize))
   1012 			goto send;
   1013 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
   1014 			goto send;
   1015 	}
   1016 dontupdate:
   1017 
   1018 	/*
   1019 	 * Send if we owe peer an ACK.
   1020 	 */
   1021 	if (tp->t_flags & TF_ACKNOW)
   1022 		goto send;
   1023 	if (flags & (TH_SYN|TH_FIN|TH_RST))
   1024 		goto send;
   1025 	if (SEQ_GT(tp->snd_up, tp->snd_una))
   1026 		goto send;
   1027 	/*
   1028 	 * In SACK, it is possible for tcp_output to fail to send a segment
   1029 	 * after the retransmission timer has been turned off.  Make sure
   1030 	 * that the retransmission timer is set.
   1031 	 */
   1032 	if (TCP_SACK_ENABLED(tp) && SEQ_GT(tp->snd_max, tp->snd_una) &&
   1033 	    !TCP_TIMER_ISARMED(tp, TCPT_REXMT) &&
   1034 	    !TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
   1035 		TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   1036 		goto just_return;
   1037 	}
   1038 
   1039 	/*
   1040 	 * TCP window updates are not reliable, rather a polling protocol
   1041 	 * using ``persist'' packets is used to insure receipt of window
   1042 	 * updates.  The three ``states'' for the output side are:
   1043 	 *	idle			not doing retransmits or persists
   1044 	 *	persisting		to move a small or zero window
   1045 	 *	(re)transmitting	and thereby not persisting
   1046 	 *
   1047 	 * tp->t_timer[TCPT_PERSIST]
   1048 	 *	is set when we are in persist state.
   1049 	 * tp->t_force
   1050 	 *	is set when we are called to send a persist packet.
   1051 	 * tp->t_timer[TCPT_REXMT]
   1052 	 *	is set when we are retransmitting
   1053 	 * The output side is idle when both timers are zero.
   1054 	 *
   1055 	 * If send window is too small, there is data to transmit, and no
   1056 	 * retransmit or persist is pending, then go to persist state.
   1057 	 * If nothing happens soon, send when timer expires:
   1058 	 * if window is nonzero, transmit what we can,
   1059 	 * otherwise force out a byte.
   1060 	 */
   1061 	if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
   1062 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
   1063 		tp->t_rxtshift = 0;
   1064 		tcp_setpersist(tp);
   1065 	}
   1066 
   1067 	/*
   1068 	 * No reason to send a segment, just return.
   1069 	 */
   1070 just_return:
   1071 	TCP_REASS_UNLOCK(tp);
   1072 	return 0;
   1073 
   1074 send:
   1075 	/*
   1076 	 * Before ESTABLISHED, force sending of initial options
   1077 	 * unless TCP set not to do any options.
   1078 	 * NOTE: we assume that the IP/TCP header plus TCP options
   1079 	 * always fit in a single mbuf, leaving room for a maximum
   1080 	 * link header, i.e.
   1081 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
   1082 	 */
   1083 	optlen = 0;
   1084 	optp = opt;
   1085 	switch (af) {
   1086 	case AF_INET:
   1087 		iphdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
   1088 		break;
   1089 #ifdef INET6
   1090 	case AF_INET6:
   1091 		iphdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
   1092 		break;
   1093 #endif
   1094 	default:	/*pacify gcc*/
   1095 		iphdrlen = 0;
   1096 		break;
   1097 	}
   1098 	hdrlen = iphdrlen;
   1099 	if (flags & TH_SYN) {
   1100 		struct rtentry *synrt;
   1101 
   1102 		synrt = NULL;
   1103 		if (tp->t_inpcb)
   1104 			synrt = in_pcbrtentry(tp->t_inpcb);
   1105 #ifdef INET6
   1106 		if (tp->t_in6pcb)
   1107 			synrt = in6_pcbrtentry(tp->t_in6pcb);
   1108 #endif
   1109 
   1110 		tp->snd_nxt = tp->iss;
   1111 		tp->t_ourmss = tcp_mss_to_advertise(synrt != NULL ?
   1112 						    synrt->rt_ifp : NULL, af);
   1113 		if (tp->t_inpcb)
   1114 			in_pcbrtentry_unref(synrt, tp->t_inpcb);
   1115 #ifdef INET6
   1116 		if (tp->t_in6pcb)
   1117 			in6_pcbrtentry_unref(synrt, tp->t_in6pcb);
   1118 #endif
   1119 		if ((tp->t_flags & TF_NOOPT) == 0 && OPT_FITS(TCPOLEN_MAXSEG)) {
   1120 			*optp++ = TCPOPT_MAXSEG;
   1121 			*optp++ = TCPOLEN_MAXSEG;
   1122 			*optp++ = (tp->t_ourmss >> 8) & 0xff;
   1123 			*optp++ = tp->t_ourmss & 0xff;
   1124 			optlen += TCPOLEN_MAXSEG;
   1125 
   1126 			if ((tp->t_flags & TF_REQ_SCALE) &&
   1127 			    ((flags & TH_ACK) == 0 ||
   1128 			    (tp->t_flags & TF_RCVD_SCALE)) &&
   1129 			    OPT_FITS(TCPOLEN_WINDOW + TCPOLEN_NOP)) {
   1130 				*((uint32_t *)optp) = htonl(
   1131 					TCPOPT_NOP << 24 |
   1132 					TCPOPT_WINDOW << 16 |
   1133 					TCPOLEN_WINDOW << 8 |
   1134 					tp->request_r_scale);
   1135 				optp += TCPOLEN_WINDOW + TCPOLEN_NOP;
   1136 				optlen += TCPOLEN_WINDOW + TCPOLEN_NOP;
   1137 			}
   1138 			if (tcp_do_sack && OPT_FITS(TCPOLEN_SACK_PERMITTED)) {
   1139 				*optp++ = TCPOPT_SACK_PERMITTED;
   1140 				*optp++ = TCPOLEN_SACK_PERMITTED;
   1141 				optlen += TCPOLEN_SACK_PERMITTED;
   1142 			}
   1143 		}
   1144 	}
   1145 
   1146 	/*
   1147 	 * Send a timestamp and echo-reply if this is a SYN and our side
   1148 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
   1149 	 * and our peer have sent timestamps in our SYN's.
   1150 	 */
   1151 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
   1152 	     (flags & TH_RST) == 0 &&
   1153 	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
   1154 	     (tp->t_flags & TF_RCVD_TSTMP))) {
   1155 		int alen = 0;
   1156 		while (optlen % 4 != 2) {
   1157 			optlen += TCPOLEN_NOP;
   1158 			*optp++ = TCPOPT_NOP;
   1159 			alen++;
   1160 		}
   1161 		if (OPT_FITS(TCPOLEN_TIMESTAMP)) {
   1162 			*optp++ = TCPOPT_TIMESTAMP;
   1163 			*optp++ = TCPOLEN_TIMESTAMP;
   1164 			uint32_t *lp = (uint32_t *)optp;
   1165 			/* Form timestamp option (appendix A of RFC 1323) */
   1166 			*lp++ = htonl(TCP_TIMESTAMP(tp));
   1167 			*lp   = htonl(tp->ts_recent);
   1168 			optp += TCPOLEN_TIMESTAMP - 2;
   1169 			optlen += TCPOLEN_TIMESTAMP;
   1170 
   1171 			/* Set receive buffer autosizing timestamp. */
   1172 			if (tp->rfbuf_ts == 0 &&
   1173 			    (so->so_rcv.sb_flags & SB_AUTOSIZE))
   1174 				tp->rfbuf_ts = TCP_TIMESTAMP(tp);
   1175 		} else {
   1176 			optp -= alen;
   1177 			optlen -= alen;
   1178 		}
   1179 	}
   1180 
   1181 #ifdef TCP_SIGNATURE
   1182 	if (tp->t_flags & TF_SIGNATURE) {
   1183 		/*
   1184 		 * Initialize TCP-MD5 option (RFC2385)
   1185 		 */
   1186 		if (!OPT_FITS(TCPOLEN_SIGNATURE))
   1187 			goto reset;
   1188 
   1189 		*optp++ = TCPOPT_SIGNATURE;
   1190 		*optp++ = TCPOLEN_SIGNATURE;
   1191 		sigoff = optlen + 2;
   1192 		memset(optp, 0, TCP_SIGLEN);
   1193 		optlen += TCPOLEN_SIGNATURE;
   1194 		optp += TCP_SIGLEN;
   1195 	}
   1196 #endif
   1197 
   1198 	/*
   1199 	 * Tack on the SACK block if it is necessary.
   1200 	 */
   1201 	if (sack_numblks) {
   1202 		int alen = 0;
   1203 		int sack_len = sack_numblks * 8;
   1204 		while (optlen % 4 != 2) {
   1205 			optlen += TCPOLEN_NOP;
   1206 			*optp++ = TCPOPT_NOP;
   1207 			alen++;
   1208 		}
   1209 		if (OPT_FITS(sack_len + 2)) {
   1210 			struct ipqent *tiqe;
   1211 			*optp++ = TCPOPT_SACK;
   1212 			*optp++ = sack_len + 2;
   1213 			uint32_t *lp = (uint32_t *)optp;
   1214 			if ((tp->rcv_sack_flags & TCPSACK_HAVED) != 0) {
   1215 				sack_numblks--;
   1216 				*lp++ = htonl(tp->rcv_dsack_block.left);
   1217 				*lp++ = htonl(tp->rcv_dsack_block.right);
   1218 				tp->rcv_sack_flags &= ~TCPSACK_HAVED;
   1219 			}
   1220 			for (tiqe = TAILQ_FIRST(&tp->timeq);
   1221 			    sack_numblks > 0;
   1222 			    tiqe = TAILQ_NEXT(tiqe, ipqe_timeq)) {
   1223 				KASSERT(tiqe != NULL);
   1224 				sack_numblks--;
   1225 				*lp++ = htonl(tiqe->ipqe_seq);
   1226 				*lp++ = htonl(tiqe->ipqe_seq + tiqe->ipqe_len +
   1227 				    ((tiqe->ipqe_flags & TH_FIN) != 0 ? 1 : 0));
   1228 			}
   1229 			optlen += sack_len + 2;
   1230 			optp += sack_len;
   1231 		} else {
   1232 			optp -= alen;
   1233 			optlen -= alen;
   1234 		}
   1235 	}
   1236 
   1237 	/* Terminate and pad TCP options to a 4 byte boundary. */
   1238 	if (optlen % 4) {
   1239 		if (!OPT_FITS(TCPOLEN_EOL)) {
   1240 reset:			TCP_REASS_UNLOCK(tp);
   1241 			error = ECONNABORTED;
   1242 			goto out;
   1243 		}
   1244 		optlen += TCPOLEN_EOL;
   1245 		*optp++ = TCPOPT_EOL;
   1246 	}
   1247 	/*
   1248 	 * According to RFC 793 (STD0007):
   1249 	 *   "The content of the header beyond the End-of-Option option
   1250 	 *    must be header padding (i.e., zero)."
   1251 	 *   and later: "The padding is composed of zeros."
   1252 	 */
   1253 	while (optlen % 4) {
   1254 		if (!OPT_FITS(TCPOLEN_PAD))
   1255 			goto reset;
   1256 		optlen += TCPOLEN_PAD;
   1257 		*optp++ = TCPOPT_PAD;
   1258 	}
   1259 
   1260 	TCP_REASS_UNLOCK(tp);
   1261 
   1262 	hdrlen += optlen;
   1263 
   1264 #ifdef DIAGNOSTIC
   1265 	if (!use_tso && len > txsegsize)
   1266 		panic("tcp data to be sent is larger than segment");
   1267 	else if (use_tso && len > IP_MAXPACKET)
   1268 		panic("tcp data to be sent is larger than max TSO size");
   1269 	if (max_linkhdr + hdrlen > MCLBYTES)
   1270 		panic("tcphdr too big");
   1271 #endif
   1272 
   1273 	/*
   1274 	 * Grab a header mbuf, attaching a copy of data to
   1275 	 * be transmitted, and initialize the header from
   1276 	 * the template for sends on this connection.
   1277 	 */
   1278 	if (len) {
   1279 		error = tcp_build_datapkt(tp, so, off, len, hdrlen, &m);
   1280 		if (error)
   1281 			goto out;
   1282 		/*
   1283 		 * If we're sending everything we've got, set PUSH.
   1284 		 * (This will keep happy those implementations which only
   1285 		 * give data to the user when a buffer fills or
   1286 		 * a PUSH comes in.)
   1287 		 */
   1288 		if (off + len == so->so_snd.sb_cc)
   1289 			flags |= TH_PUSH;
   1290 	} else {
   1291 		tcps = TCP_STAT_GETREF();
   1292 		if (tp->t_flags & TF_ACKNOW)
   1293 			tcps[TCP_STAT_SNDACKS]++;
   1294 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
   1295 			tcps[TCP_STAT_SNDCTRL]++;
   1296 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
   1297 			tcps[TCP_STAT_SNDURG]++;
   1298 		else
   1299 			tcps[TCP_STAT_SNDWINUP]++;
   1300 		TCP_STAT_PUTREF();
   1301 
   1302 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
   1303 		if (m != NULL && max_linkhdr + hdrlen > MHLEN) {
   1304 			MCLGET(m, M_DONTWAIT);
   1305 			if ((m->m_flags & M_EXT) == 0) {
   1306 				m_freem(m);
   1307 				m = NULL;
   1308 			}
   1309 		}
   1310 		if (m == NULL) {
   1311 			error = ENOBUFS;
   1312 			goto out;
   1313 		}
   1314 		MCLAIM(m, &tcp_tx_mowner);
   1315 		m->m_data += max_linkhdr;
   1316 		m->m_len = hdrlen;
   1317 	}
   1318 	m_reset_rcvif(m);
   1319 	switch (af) {
   1320 	case AF_INET:
   1321 		ip = mtod(m, struct ip *);
   1322 #ifdef INET6
   1323 		ip6 = NULL;
   1324 #endif
   1325 		th = (struct tcphdr *)(ip + 1);
   1326 		break;
   1327 #ifdef INET6
   1328 	case AF_INET6:
   1329 		ip = NULL;
   1330 		ip6 = mtod(m, struct ip6_hdr *);
   1331 		th = (struct tcphdr *)(ip6 + 1);
   1332 		break;
   1333 #endif
   1334 	default:	/*pacify gcc*/
   1335 		ip = NULL;
   1336 #ifdef INET6
   1337 		ip6 = NULL;
   1338 #endif
   1339 		th = NULL;
   1340 		break;
   1341 	}
   1342 	if (tp->t_template == NULL)
   1343 		panic("tcp_output");
   1344 	if (tp->t_template->m_len < iphdrlen)
   1345 		panic("tcp_output");
   1346 	bcopy(mtod(tp->t_template, void *), mtod(m, void *), iphdrlen);
   1347 
   1348 	/*
   1349 	 * If we are starting a connection, send ECN setup
   1350 	 * SYN packet. If we are on a retransmit, we may
   1351 	 * resend those bits a number of times as per
   1352 	 * RFC 3168.
   1353 	 */
   1354 	if (tp->t_state == TCPS_SYN_SENT && tcp_do_ecn) {
   1355 		if (tp->t_flags & TF_SYN_REXMT) {
   1356 			if (tp->t_ecn_retries--)
   1357 				flags |= TH_ECE|TH_CWR;
   1358 		} else {
   1359 			flags |= TH_ECE|TH_CWR;
   1360 			tp->t_ecn_retries = tcp_ecn_maxretries;
   1361 		}
   1362 	}
   1363 
   1364 	if (TCP_ECN_ALLOWED(tp)) {
   1365 		/*
   1366 		 * If the peer has ECN, mark data packets
   1367 		 * ECN capable. Ignore pure ack packets, retransmissions
   1368 		 * and window probes.
   1369 		 */
   1370 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
   1371 		    !(tp->t_force && len == 1)) {
   1372 			ecn_tos = IPTOS_ECN_ECT0;
   1373 			TCP_STATINC(TCP_STAT_ECN_ECT);
   1374 		}
   1375 
   1376 		/*
   1377 		 * Reply with proper ECN notifications.
   1378 		 */
   1379 		if (tp->t_flags & TF_ECN_SND_CWR) {
   1380 			flags |= TH_CWR;
   1381 			tp->t_flags &= ~TF_ECN_SND_CWR;
   1382 		}
   1383 		if (tp->t_flags & TF_ECN_SND_ECE) {
   1384 			flags |= TH_ECE;
   1385 		}
   1386 	}
   1387 
   1388 	/*
   1389 	 * If we are doing retransmissions, then snd_nxt will
   1390 	 * not reflect the first unsent octet.  For ACK only
   1391 	 * packets, we do not want the sequence number of the
   1392 	 * retransmitted packet, we want the sequence number
   1393 	 * of the next unsent octet.  So, if there is no data
   1394 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
   1395 	 * when filling in ti_seq.  But if we are in persist
   1396 	 * state, snd_max might reflect one byte beyond the
   1397 	 * right edge of the window, so use snd_nxt in that
   1398 	 * case, since we know we aren't doing a retransmission.
   1399 	 * (retransmit and persist are mutually exclusive...)
   1400 	 */
   1401 	if (TCP_SACK_ENABLED(tp) && sack_rxmit) {
   1402 		th->th_seq = htonl(p->rxmit);
   1403 		p->rxmit += len;
   1404 	} else {
   1405 		if (len || (flags & (TH_SYN|TH_FIN)) ||
   1406 		    TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
   1407 			th->th_seq = htonl(tp->snd_nxt);
   1408 		else
   1409 			th->th_seq = htonl(tp->snd_max);
   1410 	}
   1411 	th->th_ack = htonl(tp->rcv_nxt);
   1412 	if (optlen) {
   1413 		bcopy((void *)opt, (void *)(th + 1), optlen);
   1414 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
   1415 	}
   1416 	th->th_flags = flags;
   1417 	/*
   1418 	 * Calculate receive window.  Don't shrink window,
   1419 	 * but avoid silly window syndrome.
   1420 	 */
   1421 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)rxsegsize)
   1422 		win = 0;
   1423 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
   1424 		win = (long)TCP_MAXWIN << tp->rcv_scale;
   1425 	if (win < (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt))
   1426 		win = (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt);
   1427 	th->th_win = htons((u_int16_t) (win>>tp->rcv_scale));
   1428 	if (th->th_win == 0) {
   1429 		tp->t_sndzerowin++;
   1430 	}
   1431 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
   1432 		u_int32_t urp = tp->snd_up - tp->snd_nxt;
   1433 		if (urp > IP_MAXPACKET)
   1434 			urp = IP_MAXPACKET;
   1435 		th->th_urp = htons((u_int16_t)urp);
   1436 		th->th_flags |= TH_URG;
   1437 	} else
   1438 		/*
   1439 		 * If no urgent pointer to send, then we pull
   1440 		 * the urgent pointer to the left edge of the send window
   1441 		 * so that it doesn't drift into the send window on sequence
   1442 		 * number wraparound.
   1443 		 */
   1444 		tp->snd_up = tp->snd_una;		/* drag it along */
   1445 
   1446 #ifdef TCP_SIGNATURE
   1447 	if (sigoff && (tp->t_flags & TF_SIGNATURE)) {
   1448 		struct secasvar *sav;
   1449 		u_int8_t *sigp;
   1450 
   1451 		sav = tcp_signature_getsav(m);
   1452 		if (sav == NULL) {
   1453 			if (m)
   1454 				m_freem(m);
   1455 			return EPERM;
   1456 		}
   1457 
   1458 		m->m_pkthdr.len = hdrlen + len;
   1459 		sigp = (char *)th + sizeof(*th) + sigoff;
   1460 		tcp_signature(m, th, (char *)th - mtod(m, char *), sav, sigp);
   1461 
   1462 		key_sa_recordxfer(sav, m);
   1463 		KEY_SA_UNREF(&sav);
   1464 	}
   1465 #endif
   1466 
   1467 	/*
   1468 	 * Set ourselves up to be checksummed just before the packet
   1469 	 * hits the wire.
   1470 	 */
   1471 	switch (af) {
   1472 	case AF_INET:
   1473 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
   1474 		if (use_tso) {
   1475 			m->m_pkthdr.segsz = txsegsize;
   1476 			m->m_pkthdr.csum_flags = M_CSUM_TSOv4;
   1477 		} else {
   1478 			m->m_pkthdr.csum_flags = M_CSUM_TCPv4;
   1479 			if (len + optlen) {
   1480 				/* Fixup the pseudo-header checksum. */
   1481 				/* XXXJRT Not IP Jumbogram safe. */
   1482 				th->th_sum = in_cksum_addword(th->th_sum,
   1483 				    htons((u_int16_t) (len + optlen)));
   1484 			}
   1485 		}
   1486 		break;
   1487 #ifdef INET6
   1488 	case AF_INET6:
   1489 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
   1490 		if (use_tso) {
   1491 			m->m_pkthdr.segsz = txsegsize;
   1492 			m->m_pkthdr.csum_flags = M_CSUM_TSOv6;
   1493 		} else {
   1494 			m->m_pkthdr.csum_flags = M_CSUM_TCPv6;
   1495 			if (len + optlen) {
   1496 				/* Fixup the pseudo-header checksum. */
   1497 				/* XXXJRT: Not IPv6 Jumbogram safe. */
   1498 				th->th_sum = in_cksum_addword(th->th_sum,
   1499 				    htons((u_int16_t) (len + optlen)));
   1500 			}
   1501 		}
   1502 		break;
   1503 #endif
   1504 	}
   1505 
   1506 	/*
   1507 	 * In transmit state, time the transmission and arrange for
   1508 	 * the retransmit.  In persist state, just set snd_max.
   1509 	 */
   1510 	if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
   1511 		tcp_seq startseq = tp->snd_nxt;
   1512 
   1513 		/*
   1514 		 * Advance snd_nxt over sequence space of this segment.
   1515 		 * There are no states in which we send both a SYN and a FIN,
   1516 		 * so we collapse the tests for these flags.
   1517 		 */
   1518 		if (flags & (TH_SYN|TH_FIN))
   1519 			tp->snd_nxt++;
   1520 		if (sack_rxmit)
   1521 			goto timer;
   1522 		tp->snd_nxt += len;
   1523 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
   1524 			tp->snd_max = tp->snd_nxt;
   1525 			/*
   1526 			 * Time this transmission if not a retransmission and
   1527 			 * not currently timing anything.
   1528 			 */
   1529 			if (tp->t_rtttime == 0) {
   1530 				tp->t_rtttime = tcp_now;
   1531 				tp->t_rtseq = startseq;
   1532 				TCP_STATINC(TCP_STAT_SEGSTIMED);
   1533 			}
   1534 		}
   1535 
   1536 		/*
   1537 		 * Set retransmit timer if not currently set,
   1538 		 * and not doing an ack or a keep-alive probe.
   1539 		 * Initial value for retransmit timer is smoothed
   1540 		 * round-trip time + 2 * round-trip time variance.
   1541 		 * Initialize shift counter which is used for backoff
   1542 		 * of retransmit time.
   1543 		 */
   1544 timer:
   1545 		if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0) {
   1546 			if ((sack_rxmit && tp->snd_nxt != tp->snd_max)
   1547 			    || tp->snd_nxt != tp->snd_una) {
   1548 				if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
   1549 					TCP_TIMER_DISARM(tp, TCPT_PERSIST);
   1550 					tp->t_rxtshift = 0;
   1551 				}
   1552 				TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   1553 			} else if (len == 0 && so->so_snd.sb_cc > 0
   1554 			    && TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
   1555 				/*
   1556 				 * If we are sending a window probe and there's
   1557 				 * unacked data in the socket, make sure at
   1558 				 * least the persist timer is running.
   1559 				 */
   1560 				tp->t_rxtshift = 0;
   1561 				tcp_setpersist(tp);
   1562 			}
   1563 		}
   1564 	} else
   1565 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
   1566 			tp->snd_max = tp->snd_nxt + len;
   1567 
   1568 #ifdef TCP_DEBUG
   1569 	/*
   1570 	 * Trace.
   1571 	 */
   1572 	if (so->so_options & SO_DEBUG)
   1573 		tcp_trace(TA_OUTPUT, tp->t_state, tp, m, 0);
   1574 #endif
   1575 
   1576 	/*
   1577 	 * Fill in IP length and desired time to live and
   1578 	 * send to IP level.  There should be a better way
   1579 	 * to handle ttl and tos; we could keep them in
   1580 	 * the template, but need a way to checksum without them.
   1581 	 */
   1582 	m->m_pkthdr.len = hdrlen + len;
   1583 
   1584 	switch (af) {
   1585 	case AF_INET:
   1586 		ip->ip_len = htons(m->m_pkthdr.len);
   1587 		packetlen = m->m_pkthdr.len;
   1588 		if (tp->t_inpcb) {
   1589 			ip->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;
   1590 			ip->ip_tos = tp->t_inpcb->inp_ip.ip_tos | ecn_tos;
   1591 		}
   1592 #ifdef INET6
   1593 		else if (tp->t_in6pcb) {
   1594 			ip->ip_ttl = in6_selecthlim(tp->t_in6pcb, NULL); /*XXX*/
   1595 			ip->ip_tos = ecn_tos;	/*XXX*/
   1596 		}
   1597 #endif
   1598 		break;
   1599 #ifdef INET6
   1600 	case AF_INET6:
   1601 		packetlen = m->m_pkthdr.len;
   1602 		ip6->ip6_nxt = IPPROTO_TCP;
   1603 		if (tp->t_in6pcb) {
   1604 			/*
   1605 			 * we separately set hoplimit for every segment, since
   1606 			 * the user might want to change the value via
   1607 			 * setsockopt. Also, desired default hop limit might
   1608 			 * be changed via Neighbor Discovery.
   1609 			 */
   1610 			ip6->ip6_hlim = in6_selecthlim_rt(tp->t_in6pcb);
   1611 		}
   1612 		ip6->ip6_flow |= htonl(ecn_tos << 20);
   1613 		/* ip6->ip6_flow = ??? (from template) */
   1614 		/* ip6_plen will be filled in ip6_output(). */
   1615 		break;
   1616 #endif
   1617 	default:	/*pacify gcc*/
   1618 		packetlen = 0;
   1619 		break;
   1620 	}
   1621 
   1622 	switch (af) {
   1623 	case AF_INET:
   1624 	    {
   1625 		struct mbuf *opts;
   1626 
   1627 		if (tp->t_inpcb)
   1628 			opts = tp->t_inpcb->inp_options;
   1629 		else
   1630 			opts = NULL;
   1631 		error = ip_output(m, opts, ro,
   1632 			(tp->t_mtudisc ? IP_MTUDISC : 0) |
   1633 			(so->so_options & SO_DONTROUTE), NULL, tp->t_inpcb);
   1634 		break;
   1635 	    }
   1636 #ifdef INET6
   1637 	case AF_INET6:
   1638 	    {
   1639 		struct ip6_pktopts *opts;
   1640 
   1641 		if (tp->t_in6pcb)
   1642 			opts = tp->t_in6pcb->in6p_outputopts;
   1643 		else
   1644 			opts = NULL;
   1645 		error = ip6_output(m, opts, ro, so->so_options & SO_DONTROUTE,
   1646 			NULL, tp->t_in6pcb, NULL);
   1647 		break;
   1648 	    }
   1649 #endif
   1650 	default:
   1651 		error = EAFNOSUPPORT;
   1652 		break;
   1653 	}
   1654 	if (error) {
   1655 out:
   1656 		if (error == ENOBUFS) {
   1657 			TCP_STATINC(TCP_STAT_SELFQUENCH);
   1658 			if (tp->t_inpcb)
   1659 				tcp_quench(tp->t_inpcb, 0);
   1660 #ifdef INET6
   1661 			if (tp->t_in6pcb)
   1662 				tcp6_quench(tp->t_in6pcb, 0);
   1663 #endif
   1664 			error = 0;
   1665 		} else if ((error == EHOSTUNREACH || error == ENETDOWN) &&
   1666 		    TCPS_HAVERCVDSYN(tp->t_state)) {
   1667 			tp->t_softerror = error;
   1668 			error = 0;
   1669 		}
   1670 
   1671 		/* Back out the sequence number advance. */
   1672 		if (sack_rxmit)
   1673 			p->rxmit -= len;
   1674 
   1675 		/* Restart the delayed ACK timer, if necessary. */
   1676 		if (tp->t_flags & TF_DELACK)
   1677 			TCP_RESTART_DELACK(tp);
   1678 
   1679 		return error;
   1680 	}
   1681 
   1682 	if (packetlen > tp->t_pmtud_mtu_sent)
   1683 		tp->t_pmtud_mtu_sent = packetlen;
   1684 
   1685 	tcps = TCP_STAT_GETREF();
   1686 	tcps[TCP_STAT_SNDTOTAL]++;
   1687 	if (tp->t_flags & TF_DELACK)
   1688 		tcps[TCP_STAT_DELACK]++;
   1689 	TCP_STAT_PUTREF();
   1690 
   1691 	/*
   1692 	 * Data sent (as far as we can tell).
   1693 	 * If this advertises a larger window than any other segment,
   1694 	 * then remember the size of the advertised window.
   1695 	 * Any pending ACK has now been sent.
   1696 	 */
   1697 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
   1698 		tp->rcv_adv = tp->rcv_nxt + win;
   1699 	tp->last_ack_sent = tp->rcv_nxt;
   1700 	tp->t_flags &= ~TF_ACKNOW;
   1701 	TCP_CLEAR_DELACK(tp);
   1702 #ifdef DIAGNOSTIC
   1703 	if (maxburst < 0)
   1704 		printf("tcp_output: maxburst exceeded by %d\n", -maxburst);
   1705 #endif
   1706 	if (sendalot && (tp->t_congctl == &tcp_reno_ctl || --maxburst))
   1707 		goto again;
   1708 	return 0;
   1709 }
   1710 
   1711 void
   1712 tcp_setpersist(struct tcpcb *tp)
   1713 {
   1714 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2);
   1715 	int nticks;
   1716 
   1717 	if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
   1718 		panic("tcp_output REXMT");
   1719 	/*
   1720 	 * Start/restart persistance timer.
   1721 	 */
   1722 	if (t < tp->t_rttmin)
   1723 		t = tp->t_rttmin;
   1724 	TCPT_RANGESET(nticks, t * tcp_backoff[tp->t_rxtshift],
   1725 	    TCPTV_PERSMIN, TCPTV_PERSMAX);
   1726 	TCP_TIMER_ARM(tp, TCPT_PERSIST, nticks);
   1727 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
   1728 		tp->t_rxtshift++;
   1729 }
   1730