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