Home | History | Annotate | Line # | Download | only in netinet
tcp_output.c revision 1.115
      1 /*	$NetBSD: tcp_output.c,v 1.115 2004/12/15 04:25:19 thorpej 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 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  *
     80  * Redistribution and use in source and binary forms, with or without
     81  * modification, are permitted provided that the following conditions
     82  * are met:
     83  * 1. Redistributions of source code must retain the above copyright
     84  *    notice, this list of conditions and the following disclaimer.
     85  * 2. Redistributions in binary form must reproduce the above copyright
     86  *    notice, this list of conditions and the following disclaimer in the
     87  *    documentation and/or other materials provided with the distribution.
     88  * 3. All advertising materials mentioning features or use of this software
     89  *    must display the following acknowledgement:
     90  *	This product includes software developed by the NetBSD
     91  *	Foundation, Inc. and its contributors.
     92  * 4. Neither the name of The NetBSD Foundation nor the names of its
     93  *    contributors may be used to endorse or promote products derived
     94  *    from this software without specific prior written permission.
     95  *
     96  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     97  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     98  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     99  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
    100  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    101  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    102  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    103  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    104  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    105  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    106  * POSSIBILITY OF SUCH DAMAGE.
    107  */
    108 
    109 /*
    110  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
    111  *	The Regents of the University of California.  All rights reserved.
    112  *
    113  * Redistribution and use in source and binary forms, with or without
    114  * modification, are permitted provided that the following conditions
    115  * are met:
    116  * 1. Redistributions of source code must retain the above copyright
    117  *    notice, this list of conditions and the following disclaimer.
    118  * 2. Redistributions in binary form must reproduce the above copyright
    119  *    notice, this list of conditions and the following disclaimer in the
    120  *    documentation and/or other materials provided with the distribution.
    121  * 3. Neither the name of the University nor the names of its contributors
    122  *    may be used to endorse or promote products derived from this software
    123  *    without specific prior written permission.
    124  *
    125  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
    126  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    127  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    128  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
    129  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    130  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    131  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    132  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    133  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    134  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    135  * SUCH DAMAGE.
    136  *
    137  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
    138  */
    139 
    140 #include <sys/cdefs.h>
    141 __KERNEL_RCSID(0, "$NetBSD: tcp_output.c,v 1.115 2004/12/15 04:25:19 thorpej Exp $");
    142 
    143 #include "opt_inet.h"
    144 #include "opt_ipsec.h"
    145 #include "opt_tcp_debug.h"
    146 
    147 #include <sys/param.h>
    148 #include <sys/systm.h>
    149 #include <sys/malloc.h>
    150 #include <sys/mbuf.h>
    151 #include <sys/protosw.h>
    152 #include <sys/socket.h>
    153 #include <sys/socketvar.h>
    154 #include <sys/errno.h>
    155 #include <sys/domain.h>
    156 #include <sys/kernel.h>
    157 #ifdef TCP_SIGNATURE
    158 #include <sys/md5.h>
    159 #endif
    160 
    161 #include <net/if.h>
    162 #include <net/route.h>
    163 
    164 #include <netinet/in.h>
    165 #include <netinet/in_systm.h>
    166 #include <netinet/ip.h>
    167 #include <netinet/in_pcb.h>
    168 #include <netinet/ip_var.h>
    169 
    170 #ifdef INET6
    171 #ifndef INET
    172 #include <netinet/in.h>
    173 #endif
    174 #include <netinet/ip6.h>
    175 #include <netinet6/in6_var.h>
    176 #include <netinet6/ip6_var.h>
    177 #include <netinet6/in6_pcb.h>
    178 #include <netinet6/nd6.h>
    179 #endif
    180 
    181 #ifdef FAST_IPSEC
    182 #include <netipsec/ipsec.h>
    183 #include <netipsec/key.h>
    184 #endif	/* FAST_IPSEC*/
    185 #ifdef IPSEC
    186 #include <netinet6/ipsec.h>
    187 #endif
    188 
    189 #include <netinet/tcp.h>
    190 #define	TCPOUTFLAGS
    191 #include <netinet/tcp_fsm.h>
    192 #include <netinet/tcp_seq.h>
    193 #include <netinet/tcp_timer.h>
    194 #include <netinet/tcp_var.h>
    195 #include <netinet/tcpip.h>
    196 #include <netinet/tcp_debug.h>
    197 
    198 #ifdef IPSEC
    199 #include <netkey/key.h>
    200 #endif
    201 
    202 #ifdef notyet
    203 extern struct mbuf *m_copypack();
    204 #endif
    205 
    206 #define MAX_TCPOPTLEN	32	/* max # bytes that go in options */
    207 
    208 /*
    209  * Knob to enable Congestion Window Monitoring, and control the
    210  * the burst size it allows.  Default burst is 4 packets, per
    211  * the Internet draft.
    212  */
    213 int	tcp_cwm = 0;
    214 int	tcp_cwm_burstsize = 4;
    215 
    216 #ifdef TCP_OUTPUT_COUNTERS
    217 #include <sys/device.h>
    218 
    219 extern struct evcnt tcp_output_bigheader;
    220 extern struct evcnt tcp_output_predict_hit;
    221 extern struct evcnt tcp_output_predict_miss;
    222 extern struct evcnt tcp_output_copysmall;
    223 extern struct evcnt tcp_output_copybig;
    224 extern struct evcnt tcp_output_refbig;
    225 
    226 #define	TCP_OUTPUT_COUNTER_INCR(ev)	(ev)->ev_count++
    227 #else
    228 
    229 #define	TCP_OUTPUT_COUNTER_INCR(ev)	/* nothing */
    230 
    231 #endif /* TCP_OUTPUT_COUNTERS */
    232 
    233 static
    234 #ifndef GPROF
    235 __inline
    236 #endif
    237 int
    238 tcp_segsize(struct tcpcb *tp, int *txsegsizep, int *rxsegsizep)
    239 {
    240 #ifdef INET
    241 	struct inpcb *inp = tp->t_inpcb;
    242 #endif
    243 #ifdef INET6
    244 	struct in6pcb *in6p = tp->t_in6pcb;
    245 #endif
    246 	struct socket *so = NULL;
    247 	struct rtentry *rt;
    248 	struct ifnet *ifp;
    249 	int size;
    250 	int iphlen;
    251 	int optlen;
    252 
    253 #ifdef DIAGNOSTIC
    254 	if (tp->t_inpcb && tp->t_in6pcb)
    255 		panic("tcp_segsize: both t_inpcb and t_in6pcb are set");
    256 #endif
    257 	switch (tp->t_family) {
    258 #ifdef INET
    259 	case AF_INET:
    260 		iphlen = sizeof(struct ip);
    261 		break;
    262 #endif
    263 #ifdef INET6
    264 	case AF_INET6:
    265 		iphlen = sizeof(struct ip6_hdr);
    266 		break;
    267 #endif
    268 	default:
    269 		size = tcp_mssdflt;
    270 		goto out;
    271 	}
    272 
    273 	rt = NULL;
    274 #ifdef INET
    275 	if (inp) {
    276 		rt = in_pcbrtentry(inp);
    277 		so = inp->inp_socket;
    278 	}
    279 #endif
    280 #ifdef INET6
    281 	if (in6p) {
    282 		rt = in6_pcbrtentry(in6p);
    283 		so = in6p->in6p_socket;
    284 	}
    285 #endif
    286 	if (rt == NULL) {
    287 		size = tcp_mssdflt;
    288 		goto out;
    289 	}
    290 
    291 	ifp = rt->rt_ifp;
    292 
    293 	size = tcp_mssdflt;
    294 	if (tp->t_mtudisc && rt->rt_rmx.rmx_mtu != 0) {
    295 #ifdef INET6
    296 		if (in6p && rt->rt_rmx.rmx_mtu < IPV6_MMTU) {
    297 			/*
    298 			 * RFC2460 section 5, last paragraph: if path MTU is
    299 			 * smaller than 1280, use 1280 as packet size and
    300 			 * attach fragment header.
    301 			 */
    302 			size = IPV6_MMTU - iphlen - sizeof(struct ip6_frag) -
    303 			    sizeof(struct tcphdr);
    304 		} else
    305 			size = rt->rt_rmx.rmx_mtu - iphlen -
    306 			    sizeof(struct tcphdr);
    307 #else
    308 		size = rt->rt_rmx.rmx_mtu - iphlen - sizeof(struct tcphdr);
    309 #endif
    310 	} else if (ifp->if_flags & IFF_LOOPBACK)
    311 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    312 #ifdef INET
    313 	else if (inp && tp->t_mtudisc)
    314 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    315 	else if (inp && in_localaddr(inp->inp_faddr))
    316 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    317 #endif
    318 #ifdef INET6
    319 	else if (in6p) {
    320 #ifdef INET
    321 		if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr)) {
    322 			/* mapped addr case */
    323 			struct in_addr d;
    324 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &d, sizeof(d));
    325 			if (tp->t_mtudisc || in_localaddr(d))
    326 				size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    327 		} else
    328 #endif
    329 		{
    330 			/*
    331 			 * for IPv6, path MTU discovery is always turned on,
    332 			 * or the node must use packet size <= 1280.
    333 			 */
    334 			size = tp->t_mtudisc ? IN6_LINKMTU(ifp) : IPV6_MMTU;
    335 			size -= (iphlen + sizeof(struct tcphdr));
    336 		}
    337 	}
    338 #endif
    339  out:
    340 	/*
    341 	 * Now we must make room for whatever extra TCP/IP options are in
    342 	 * the packet.
    343 	 */
    344 	optlen = tcp_optlen(tp);
    345 
    346 	/*
    347 	 * XXX tp->t_ourmss should have the right size, but without this code
    348 	 * fragmentation will occur... need more investigation
    349 	 */
    350 #ifdef INET
    351 	if (inp) {
    352 #if defined(IPSEC) || defined(FAST_IPSEC)
    353 		if (! IPSEC_PCB_SKIP_IPSEC(inp->inp_sp, IPSEC_DIR_OUTBOUND))
    354 			optlen += ipsec4_hdrsiz_tcp(tp);
    355 #endif
    356 		optlen += ip_optlen(inp);
    357 	}
    358 #endif
    359 #ifdef INET6
    360 #ifdef INET
    361 	if (in6p && tp->t_family == AF_INET) {
    362 #if defined(IPSEC) || defined(FAST_IPSEC)
    363 		if (! IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND))
    364 			optlen += ipsec4_hdrsiz_tcp(tp);
    365 #endif
    366 		/* XXX size -= ip_optlen(in6p); */
    367 	} else
    368 #endif
    369 	if (in6p && tp->t_family == AF_INET6) {
    370 #ifdef IPSEC
    371 		if (! IPSEC_PCB_SKIP_IPSEC(in6p->in6p_sp, IPSEC_DIR_OUTBOUND))
    372 			optlen += ipsec6_hdrsiz_tcp(tp);
    373 #endif
    374 		optlen += ip6_optlen(in6p);
    375 	}
    376 #endif
    377 	size -= optlen;
    378 
    379 	/* there may not be any room for data if mtu is too small */
    380 	if (size < 0)
    381 		return (EMSGSIZE);
    382 
    383 	/*
    384 	 * *rxsegsizep holds *estimated* inbound segment size (estimation
    385 	 * assumes that path MTU is the same for both ways).  this is only
    386 	 * for silly window avoidance, do not use the value for other purposes.
    387 	 *
    388 	 * ipseclen is subtracted from both sides, this may not be right.
    389 	 * I'm not quite sure about this (could someone comment).
    390 	 */
    391 	*txsegsizep = min(tp->t_peermss - optlen, size);
    392 	/*
    393 	 * Never send more than half a buffer full.  This insures that we can
    394 	 * always keep 2 packets on the wire, no matter what SO_SNDBUF is, and
    395 	 * therefore acks will never be delayed unless we run out of data to
    396 	 * transmit.
    397 	 */
    398 	if (so)
    399 		*txsegsizep = min(so->so_snd.sb_hiwat >> 1, *txsegsizep);
    400 	*rxsegsizep = min(tp->t_ourmss - optlen, size);
    401 
    402 	if (*txsegsizep != tp->t_segsz) {
    403 		/*
    404 		 * If the new segment size is larger, we don't want to
    405 		 * mess up the congestion window, but if it is smaller
    406 		 * we'll have to reduce the congestion window to ensure
    407 		 * that we don't get into trouble with initial windows
    408 		 * and the rest.  In any case, if the segment size
    409 		 * has changed, chances are the path has, too, and
    410 		 * our congestion window will be different.
    411 		 */
    412 		if (*txsegsizep < tp->t_segsz) {
    413 			tp->snd_cwnd = max((tp->snd_cwnd / tp->t_segsz)
    414 					   * *txsegsizep, *txsegsizep);
    415 			tp->snd_ssthresh = max((tp->snd_ssthresh / tp->t_segsz)
    416 						* *txsegsizep, *txsegsizep);
    417 		}
    418 		tp->t_segsz = *txsegsizep;
    419 	}
    420 
    421 	return (0);
    422 }
    423 
    424 static
    425 #ifndef GPROF
    426 __inline
    427 #endif
    428 int
    429 tcp_build_datapkt(struct tcpcb *tp, struct socket *so, int off,
    430     long len, int hdrlen, struct mbuf **mp)
    431 {
    432 	struct mbuf *m, *m0;
    433 
    434 	if (tp->t_force && len == 1)
    435 		tcpstat.tcps_sndprobe++;
    436 	else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
    437 		tcpstat.tcps_sndrexmitpack++;
    438 		tcpstat.tcps_sndrexmitbyte += len;
    439 	} else {
    440 		tcpstat.tcps_sndpack++;
    441 		tcpstat.tcps_sndbyte += len;
    442 	}
    443 #ifdef notyet
    444 	if ((m = m_copypack(so->so_snd.sb_mb, off,
    445 	    (int)len, max_linkhdr + hdrlen)) == 0)
    446 		return (ENOBUFS);
    447 	/*
    448 	 * m_copypack left space for our hdr; use it.
    449 	 */
    450 	m->m_len += hdrlen;
    451 	m->m_data -= hdrlen;
    452 #else
    453 	MGETHDR(m, M_DONTWAIT, MT_HEADER);
    454 	if (__predict_false(m == NULL))
    455 		return (ENOBUFS);
    456 	MCLAIM(m, &tcp_tx_mowner);
    457 
    458 	/*
    459 	 * XXX Because other code assumes headers will fit in
    460 	 * XXX one header mbuf.
    461 	 *
    462 	 * (This code should almost *never* be run.)
    463 	 */
    464 	if (__predict_false((max_linkhdr + hdrlen) > MHLEN)) {
    465 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_bigheader);
    466 		MCLGET(m, M_DONTWAIT);
    467 		if ((m->m_flags & M_EXT) == 0) {
    468 			m_freem(m);
    469 			return (ENOBUFS);
    470 		}
    471 	}
    472 
    473 	m->m_data += max_linkhdr;
    474 	m->m_len = hdrlen;
    475 
    476 	/*
    477 	 * To avoid traversing the whole sb_mb chain for correct
    478 	 * data to send, remember last sent mbuf, its offset and
    479 	 * the sent size.  When called the next time, see if the
    480 	 * data to send is directly following the previous transfer.
    481 	 * This is important for large TCP windows.
    482 	 */
    483 	if (off == 0 || tp->t_lastm == NULL ||
    484 	    (tp->t_lastoff + tp->t_lastlen) != off) {
    485 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_predict_miss);
    486 		/*
    487 		 * Either a new packet or a retransmit.
    488 		 * Start from the beginning.
    489 		 */
    490 		tp->t_lastm = so->so_snd.sb_mb;
    491 		tp->t_inoff = off;
    492 	} else {
    493 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_predict_hit);
    494 		tp->t_inoff += tp->t_lastlen;
    495 	}
    496 
    497 	/* Traverse forward to next packet */
    498 	while (tp->t_inoff > 0) {
    499 		if (tp->t_lastm == NULL)
    500 			panic("tp->t_lastm == NULL");
    501 		if (tp->t_inoff < tp->t_lastm->m_len)
    502 			break;
    503 		tp->t_inoff -= tp->t_lastm->m_len;
    504 		tp->t_lastm = tp->t_lastm->m_next;
    505 	}
    506 
    507 	tp->t_lastoff = off;
    508 	tp->t_lastlen = len;
    509 	m0 = tp->t_lastm;
    510 	off = tp->t_inoff;
    511 
    512 	if (len <= M_TRAILINGSPACE(m)) {
    513 		m_copydata(m0, off, (int) len, mtod(m, caddr_t) + hdrlen);
    514 		m->m_len += len;
    515 		TCP_OUTPUT_COUNTER_INCR(&tcp_output_copysmall);
    516 	} else {
    517 		m->m_next = m_copy(m0, off, (int) len);
    518 		if (m->m_next == NULL) {
    519 			m_freem(m);
    520 			return (ENOBUFS);
    521 		}
    522 #ifdef TCP_OUTPUT_COUNTERS
    523 		if (m->m_next->m_flags & M_EXT)
    524 			TCP_OUTPUT_COUNTER_INCR(&tcp_output_refbig);
    525 		else
    526 			TCP_OUTPUT_COUNTER_INCR(&tcp_output_copybig);
    527 #endif /* TCP_OUTPUT_COUNTERS */
    528 	}
    529 #endif
    530 
    531 	*mp = m;
    532 	return (0);
    533 }
    534 
    535 /*
    536  * Tcp output routine: figure out what should be sent and send it.
    537  */
    538 int
    539 tcp_output(tp)
    540 	struct tcpcb *tp;
    541 {
    542 	struct socket *so;
    543 	struct route *ro;
    544 	long len, win;
    545 	int off, flags, error;
    546 	struct mbuf *m;
    547 	struct ip *ip;
    548 #ifdef INET6
    549 	struct ip6_hdr *ip6;
    550 #endif
    551 	struct tcphdr *th;
    552 	u_char opt[MAX_TCPOPTLEN];
    553 	unsigned optlen, hdrlen;
    554 	int idle, sendalot, txsegsize, rxsegsize;
    555 	int maxburst = TCP_MAXBURST;
    556 	int af;		/* address family on the wire */
    557 	int iphdrlen;
    558 #ifdef TCP_SIGNATURE
    559 	int sigoff = 0;
    560 #endif
    561 
    562 #ifdef DIAGNOSTIC
    563 	if (tp->t_inpcb && tp->t_in6pcb)
    564 		panic("tcp_output: both t_inpcb and t_in6pcb are set");
    565 #endif
    566 	so = NULL;
    567 	ro = NULL;
    568 	if (tp->t_inpcb) {
    569 		so = tp->t_inpcb->inp_socket;
    570 		ro = &tp->t_inpcb->inp_route;
    571 	}
    572 #ifdef INET6
    573 	else if (tp->t_in6pcb) {
    574 		so = tp->t_in6pcb->in6p_socket;
    575 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    576 	}
    577 #endif
    578 
    579 	switch (af = tp->t_family) {
    580 #ifdef INET
    581 	case AF_INET:
    582 		if (tp->t_inpcb)
    583 			break;
    584 #ifdef INET6
    585 		/* mapped addr case */
    586 		if (tp->t_in6pcb)
    587 			break;
    588 #endif
    589 		return (EINVAL);
    590 #endif
    591 #ifdef INET6
    592 	case AF_INET6:
    593 		if (tp->t_in6pcb)
    594 			break;
    595 		return (EINVAL);
    596 #endif
    597 	default:
    598 		return (EAFNOSUPPORT);
    599 	}
    600 
    601 	if (tcp_segsize(tp, &txsegsize, &rxsegsize))
    602 		return (EMSGSIZE);
    603 
    604 	idle = (tp->snd_max == tp->snd_una);
    605 
    606 	/*
    607 	 * Restart Window computation.  From draft-floyd-incr-init-win-03:
    608 	 *
    609 	 *	Optionally, a TCP MAY set the restart window to the
    610 	 *	minimum of the value used for the initial window and
    611 	 *	the current value of cwnd (in other words, using a
    612 	 *	larger value for the restart window should never increase
    613 	 *	the size of cwnd).
    614 	 */
    615 	if (tcp_cwm) {
    616 		/*
    617 		 * Hughes/Touch/Heidemann Congestion Window Monitoring.
    618 		 * Count the number of packets currently pending
    619 		 * acknowledgement, and limit our congestion window
    620 		 * to a pre-determined allowed burst size plus that count.
    621 		 * This prevents bursting once all pending packets have
    622 		 * been acknowledged (i.e. transmission is idle).
    623 		 *
    624 		 * XXX Link this to Initial Window?
    625 		 */
    626 		tp->snd_cwnd = min(tp->snd_cwnd,
    627 		    (tcp_cwm_burstsize * txsegsize) +
    628 		    (tp->snd_nxt - tp->snd_una));
    629 	} else {
    630 		if (idle && (tcp_now - tp->t_rcvtime) >= tp->t_rxtcur) {
    631 			/*
    632 			 * We have been idle for "a while" and no acks are
    633 			 * expected to clock out any data we send --
    634 			 * slow start to get ack "clock" running again.
    635 			 */
    636 			int ss = tcp_init_win;
    637 #ifdef INET
    638 			if (tp->t_inpcb &&
    639 			    in_localaddr(tp->t_inpcb->inp_faddr))
    640 				ss = tcp_init_win_local;
    641 #endif
    642 #ifdef INET6
    643 			if (tp->t_in6pcb &&
    644 			    in6_localaddr(&tp->t_in6pcb->in6p_faddr))
    645 				ss = tcp_init_win_local;
    646 #endif
    647 			tp->snd_cwnd = min(tp->snd_cwnd,
    648 			    TCP_INITIAL_WINDOW(ss, txsegsize));
    649 		}
    650 	}
    651 
    652 again:
    653 	/*
    654 	 * Determine length of data that should be transmitted, and
    655 	 * flags that should be used.  If there is some data or critical
    656 	 * controls (SYN, RST) to send, then transmit; otherwise,
    657 	 * investigate further.
    658 	 */
    659 	sendalot = 0;
    660 	off = tp->snd_nxt - tp->snd_una;
    661 	win = min(tp->snd_wnd, tp->snd_cwnd);
    662 
    663 	flags = tcp_outflags[tp->t_state];
    664 	/*
    665 	 * If in persist timeout with window of 0, send 1 byte.
    666 	 * Otherwise, if window is small but nonzero
    667 	 * and timer expired, we will send what we can
    668 	 * and go to transmit state.
    669 	 */
    670 	if (tp->t_force) {
    671 		if (win == 0) {
    672 			/*
    673 			 * If we still have some data to send, then
    674 			 * clear the FIN bit.  Usually this would
    675 			 * happen below when it realizes that we
    676 			 * aren't sending all the data.  However,
    677 			 * if we have exactly 1 byte of unset data,
    678 			 * then it won't clear the FIN bit below,
    679 			 * and if we are in persist state, we wind
    680 			 * up sending the packet without recording
    681 			 * that we sent the FIN bit.
    682 			 *
    683 			 * We can't just blindly clear the FIN bit,
    684 			 * because if we don't have any more data
    685 			 * to send then the probe will be the FIN
    686 			 * itself.
    687 			 */
    688 			if (off < so->so_snd.sb_cc)
    689 				flags &= ~TH_FIN;
    690 			win = 1;
    691 		} else {
    692 			TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    693 			tp->t_rxtshift = 0;
    694 		}
    695 	}
    696 
    697 	if (win < so->so_snd.sb_cc) {
    698 		len = win - off;
    699 		flags &= ~TH_FIN;
    700 	} else
    701 		len = so->so_snd.sb_cc - off;
    702 
    703 	if (len < 0) {
    704 		/*
    705 		 * If FIN has been sent but not acked,
    706 		 * but we haven't been called to retransmit,
    707 		 * len will be -1.  Otherwise, window shrank
    708 		 * after we sent into it.  If window shrank to 0,
    709 		 * cancel pending retransmit, pull snd_nxt back
    710 		 * to (closed) window, and set the persist timer
    711 		 * if it isn't already going.  If the window didn't
    712 		 * close completely, just wait for an ACK.
    713 		 *
    714 		 * If we have a pending FIN, either it has already been
    715 		 * transmitted or it is outside the window, so drop it.
    716 		 * If the FIN has been transmitted, but this is not a
    717 		 * retransmission, then len must be -1.  Therefore we also
    718 		 * prevent here the sending of `gratuitous FINs'.  This
    719 		 * eliminates the need to check for that case below (e.g.
    720 		 * to back up snd_nxt before the FIN so that the sequence
    721 		 * number is correct).
    722 		 */
    723 		len = 0;
    724 		flags &= ~TH_FIN;
    725 		if (win == 0) {
    726 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
    727 			tp->t_rxtshift = 0;
    728 			tp->snd_nxt = tp->snd_una;
    729 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
    730 				tcp_setpersist(tp);
    731 		}
    732 	}
    733 	if (len > txsegsize) {
    734 		len = txsegsize;
    735 		flags &= ~TH_FIN;
    736 		sendalot = 1;
    737 	}
    738 
    739 	win = sbspace(&so->so_rcv);
    740 
    741 	/*
    742 	 * Sender silly window avoidance.  If connection is idle
    743 	 * and can send all data, a maximum segment,
    744 	 * at least a maximum default-size segment do it,
    745 	 * or are forced, do it; otherwise don't bother.
    746 	 * If peer's buffer is tiny, then send
    747 	 * when window is at least half open.
    748 	 * If retransmitting (possibly after persist timer forced us
    749 	 * to send into a small window), then must resend.
    750 	 */
    751 	if (len) {
    752 		if (len == txsegsize)
    753 			goto send;
    754 		if ((so->so_state & SS_MORETOCOME) == 0 &&
    755 		    ((idle || tp->t_flags & TF_NODELAY) &&
    756 		     len + off >= so->so_snd.sb_cc))
    757 			goto send;
    758 		if (tp->t_force)
    759 			goto send;
    760 		if (len >= tp->max_sndwnd / 2)
    761 			goto send;
    762 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
    763 			goto send;
    764 	}
    765 
    766 	/*
    767 	 * Compare available window to amount of window known to peer
    768 	 * (as advertised window less next expected input).  If the
    769 	 * difference is at least twice the size of the largest segment
    770 	 * we expect to receive (i.e. two segments) or at least 50% of
    771 	 * the maximum possible window, then want to send a window update
    772 	 * to peer.
    773 	 */
    774 	if (win > 0) {
    775 		/*
    776 		 * "adv" is the amount we can increase the window,
    777 		 * taking into account that we are limited by
    778 		 * TCP_MAXWIN << tp->rcv_scale.
    779 		 */
    780 		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
    781 			(tp->rcv_adv - tp->rcv_nxt);
    782 
    783 		if (adv >= (long) (2 * rxsegsize))
    784 			goto send;
    785 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
    786 			goto send;
    787 	}
    788 
    789 	/*
    790 	 * Send if we owe peer an ACK.
    791 	 */
    792 	if (tp->t_flags & TF_ACKNOW)
    793 		goto send;
    794 	if (flags & (TH_SYN|TH_FIN|TH_RST))
    795 		goto send;
    796 	if (SEQ_GT(tp->snd_up, tp->snd_una))
    797 		goto send;
    798 
    799 	/*
    800 	 * TCP window updates are not reliable, rather a polling protocol
    801 	 * using ``persist'' packets is used to insure receipt of window
    802 	 * updates.  The three ``states'' for the output side are:
    803 	 *	idle			not doing retransmits or persists
    804 	 *	persisting		to move a small or zero window
    805 	 *	(re)transmitting	and thereby not persisting
    806 	 *
    807 	 * tp->t_timer[TCPT_PERSIST]
    808 	 *	is set when we are in persist state.
    809 	 * tp->t_force
    810 	 *	is set when we are called to send a persist packet.
    811 	 * tp->t_timer[TCPT_REXMT]
    812 	 *	is set when we are retransmitting
    813 	 * The output side is idle when both timers are zero.
    814 	 *
    815 	 * If send window is too small, there is data to transmit, and no
    816 	 * retransmit or persist is pending, then go to persist state.
    817 	 * If nothing happens soon, send when timer expires:
    818 	 * if window is nonzero, transmit what we can,
    819 	 * otherwise force out a byte.
    820 	 */
    821 	if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    822 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    823 		tp->t_rxtshift = 0;
    824 		tcp_setpersist(tp);
    825 	}
    826 
    827 	/*
    828 	 * No reason to send a segment, just return.
    829 	 */
    830 	return (0);
    831 
    832 send:
    833 	/*
    834 	 * Before ESTABLISHED, force sending of initial options
    835 	 * unless TCP set not to do any options.
    836 	 * NOTE: we assume that the IP/TCP header plus TCP options
    837 	 * always fit in a single mbuf, leaving room for a maximum
    838 	 * link header, i.e.
    839 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
    840 	 */
    841 	optlen = 0;
    842 	switch (af) {
    843 #ifdef INET
    844 	case AF_INET:
    845 		iphdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
    846 		break;
    847 #endif
    848 #ifdef INET6
    849 	case AF_INET6:
    850 		iphdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    851 		break;
    852 #endif
    853 	default:	/*pacify gcc*/
    854 		iphdrlen = 0;
    855 		break;
    856 	}
    857 	hdrlen = iphdrlen;
    858 	if (flags & TH_SYN) {
    859 		struct rtentry *rt;
    860 
    861 		rt = NULL;
    862 #ifdef INET
    863 		if (tp->t_inpcb)
    864 			rt = in_pcbrtentry(tp->t_inpcb);
    865 #endif
    866 #ifdef INET6
    867 		if (tp->t_in6pcb)
    868 			rt = in6_pcbrtentry(tp->t_in6pcb);
    869 #endif
    870 
    871 		tp->snd_nxt = tp->iss;
    872 		tp->t_ourmss = tcp_mss_to_advertise(rt != NULL ?
    873 						    rt->rt_ifp : NULL, af);
    874 		if ((tp->t_flags & TF_NOOPT) == 0) {
    875 			opt[0] = TCPOPT_MAXSEG;
    876 			opt[1] = 4;
    877 			opt[2] = (tp->t_ourmss >> 8) & 0xff;
    878 			opt[3] = tp->t_ourmss & 0xff;
    879 			optlen = 4;
    880 
    881 			if ((tp->t_flags & TF_REQ_SCALE) &&
    882 			    ((flags & TH_ACK) == 0 ||
    883 			    (tp->t_flags & TF_RCVD_SCALE))) {
    884 				*((u_int32_t *) (opt + optlen)) = htonl(
    885 					TCPOPT_NOP << 24 |
    886 					TCPOPT_WINDOW << 16 |
    887 					TCPOLEN_WINDOW << 8 |
    888 					tp->request_r_scale);
    889 				optlen += 4;
    890 			}
    891 		}
    892 	}
    893 
    894 	/*
    895 	 * Send a timestamp and echo-reply if this is a SYN and our side
    896 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
    897 	 * and our peer have sent timestamps in our SYN's.
    898 	 */
    899 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
    900 	     (flags & TH_RST) == 0 &&
    901 	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
    902 	     (tp->t_flags & TF_RCVD_TSTMP))) {
    903 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
    904 
    905 		/* Form timestamp option as shown in appendix A of RFC 1323. */
    906 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
    907 		*lp++ = htonl(TCP_TIMESTAMP(tp));
    908 		*lp   = htonl(tp->ts_recent);
    909 		optlen += TCPOLEN_TSTAMP_APPA;
    910 	}
    911 
    912 #ifdef TCP_SIGNATURE
    913 #if defined(INET6) && defined(FAST_IPSEC)
    914 	if (tp->t_family == AF_INET)
    915 #endif
    916 	if (tp->t_flags & TF_SIGNATURE) {
    917 		u_char *bp;
    918 		/*
    919 		 * Initialize TCP-MD5 option (RFC2385)
    920 		 */
    921 		bp = (u_char *)opt + optlen;
    922 		*bp++ = TCPOPT_SIGNATURE;
    923 		*bp++ = TCPOLEN_SIGNATURE;
    924 		sigoff = optlen + 2;
    925 		bzero(bp, TCP_SIGLEN);
    926 		bp += TCP_SIGLEN;
    927 		optlen += TCPOLEN_SIGNATURE;
    928 		/*
    929 		 * Terminate options list and maintain 32-bit alignment.
    930  		 */
    931 		*bp++ = TCPOPT_NOP;
    932 		*bp++ = TCPOPT_EOL;
    933  		optlen += 2;
    934  	}
    935 #endif /* TCP_SIGNATURE */
    936 
    937 	hdrlen += optlen;
    938 
    939 #ifdef DIAGNOSTIC
    940 	if (len > txsegsize)
    941 		panic("tcp data to be sent is larger than segment");
    942 	if (max_linkhdr + hdrlen > MCLBYTES)
    943 		panic("tcphdr too big");
    944 #endif
    945 
    946 	/*
    947 	 * Grab a header mbuf, attaching a copy of data to
    948 	 * be transmitted, and initialize the header from
    949 	 * the template for sends on this connection.
    950 	 */
    951 	if (len) {
    952 		error = tcp_build_datapkt(tp, so, off, len, hdrlen, &m);
    953 		if (error)
    954 			goto out;
    955 		/*
    956 		 * If we're sending everything we've got, set PUSH.
    957 		 * (This will keep happy those implementations which only
    958 		 * give data to the user when a buffer fills or
    959 		 * a PUSH comes in.)
    960 		 */
    961 		if (off + len == so->so_snd.sb_cc)
    962 			flags |= TH_PUSH;
    963 	} else {
    964 		if (tp->t_flags & TF_ACKNOW)
    965 			tcpstat.tcps_sndacks++;
    966 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
    967 			tcpstat.tcps_sndctrl++;
    968 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
    969 			tcpstat.tcps_sndurg++;
    970 		else
    971 			tcpstat.tcps_sndwinup++;
    972 
    973 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    974 		if (m != NULL && max_linkhdr + hdrlen > MHLEN) {
    975 			MCLGET(m, M_DONTWAIT);
    976 			if ((m->m_flags & M_EXT) == 0) {
    977 				m_freem(m);
    978 				m = NULL;
    979 			}
    980 		}
    981 		if (m == NULL) {
    982 			error = ENOBUFS;
    983 			goto out;
    984 		}
    985 		MCLAIM(m, &tcp_tx_mowner);
    986 		m->m_data += max_linkhdr;
    987 		m->m_len = hdrlen;
    988 	}
    989 	m->m_pkthdr.rcvif = (struct ifnet *)0;
    990 	switch (af) {
    991 #ifdef INET
    992 	case AF_INET:
    993 		ip = mtod(m, struct ip *);
    994 #ifdef INET6
    995 		ip6 = NULL;
    996 #endif
    997 		th = (struct tcphdr *)(ip + 1);
    998 		break;
    999 #endif
   1000 #ifdef INET6
   1001 	case AF_INET6:
   1002 		ip = NULL;
   1003 		ip6 = mtod(m, struct ip6_hdr *);
   1004 		th = (struct tcphdr *)(ip6 + 1);
   1005 		break;
   1006 #endif
   1007 	default:	/*pacify gcc*/
   1008 		ip = NULL;
   1009 #ifdef INET6
   1010 		ip6 = NULL;
   1011 #endif
   1012 		th = NULL;
   1013 		break;
   1014 	}
   1015 	if (tp->t_template == 0)
   1016 		panic("tcp_output");
   1017 	if (tp->t_template->m_len < iphdrlen)
   1018 		panic("tcp_output");
   1019 	bcopy(mtod(tp->t_template, caddr_t), mtod(m, caddr_t), iphdrlen);
   1020 
   1021 	/*
   1022 	 * If we are doing retransmissions, then snd_nxt will
   1023 	 * not reflect the first unsent octet.  For ACK only
   1024 	 * packets, we do not want the sequence number of the
   1025 	 * retransmitted packet, we want the sequence number
   1026 	 * of the next unsent octet.  So, if there is no data
   1027 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
   1028 	 * when filling in ti_seq.  But if we are in persist
   1029 	 * state, snd_max might reflect one byte beyond the
   1030 	 * right edge of the window, so use snd_nxt in that
   1031 	 * case, since we know we aren't doing a retransmission.
   1032 	 * (retransmit and persist are mutually exclusive...)
   1033 	 */
   1034 	if (len || (flags & (TH_SYN|TH_FIN)) ||
   1035 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
   1036 		th->th_seq = htonl(tp->snd_nxt);
   1037 	else
   1038 		th->th_seq = htonl(tp->snd_max);
   1039 	th->th_ack = htonl(tp->rcv_nxt);
   1040 	if (optlen) {
   1041 		bcopy((caddr_t)opt, (caddr_t)(th + 1), optlen);
   1042 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
   1043 	}
   1044 	th->th_flags = flags;
   1045 	/*
   1046 	 * Calculate receive window.  Don't shrink window,
   1047 	 * but avoid silly window syndrome.
   1048 	 */
   1049 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)rxsegsize)
   1050 		win = 0;
   1051 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
   1052 		win = (long)TCP_MAXWIN << tp->rcv_scale;
   1053 	if (win < (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt))
   1054 		win = (long)(int32_t)(tp->rcv_adv - tp->rcv_nxt);
   1055 	th->th_win = htons((u_int16_t) (win>>tp->rcv_scale));
   1056 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
   1057 		u_int32_t urp = tp->snd_up - tp->snd_nxt;
   1058 		if (urp > IP_MAXPACKET)
   1059 			urp = IP_MAXPACKET;
   1060 		th->th_urp = htons((u_int16_t)urp);
   1061 		th->th_flags |= TH_URG;
   1062 	} else
   1063 		/*
   1064 		 * If no urgent pointer to send, then we pull
   1065 		 * the urgent pointer to the left edge of the send window
   1066 		 * so that it doesn't drift into the send window on sequence
   1067 		 * number wraparound.
   1068 		 */
   1069 		tp->snd_up = tp->snd_una;		/* drag it along */
   1070 
   1071 #ifdef TCP_SIGNATURE
   1072 #if defined(INET6) && defined(FAST_IPSEC)
   1073 	if (tp->t_family == AF_INET) /* XXX */
   1074 #endif
   1075 	if (sigoff && (tp->t_flags & TF_SIGNATURE)) {
   1076 		struct secasvar *sav;
   1077 		u_int8_t *sigp;
   1078 
   1079 		sav = tcp_signature_getsav(m, th);
   1080 
   1081 		if (sav == NULL) {
   1082 			if (m)
   1083 				m_freem(m);
   1084 			return (EPERM);
   1085 		}
   1086 
   1087 		m->m_pkthdr.len = hdrlen + len;
   1088 		sigp = (caddr_t)th + sizeof(*th) + sigoff;
   1089 		tcp_signature(m, th, (caddr_t)th - mtod(m, caddr_t), sav, sigp);
   1090 
   1091 		key_sa_recordxfer(sav, m);
   1092 #ifdef FAST_IPSEC
   1093 		KEY_FREESAV(&sav);
   1094 #else
   1095 		key_freesav(sav);
   1096 #endif
   1097 	}
   1098 #endif
   1099 
   1100 	/*
   1101 	 * Set ourselves up to be checksummed just before the packet
   1102 	 * hits the wire.  Maybe skip checksums on loopback interfaces.
   1103 	 */
   1104 	switch (af) {
   1105 #ifdef INET
   1106 	case AF_INET:
   1107 		if (__predict_true(ro->ro_rt == NULL ||
   1108 				   !(ro->ro_rt->rt_ifp->if_flags &
   1109 				     IFF_LOOPBACK) ||
   1110 				   tcp_do_loopback_cksum))
   1111 			m->m_pkthdr.csum_flags = M_CSUM_TCPv4;
   1112 		else
   1113 			m->m_pkthdr.csum_flags = 0;
   1114 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
   1115 		if (len + optlen) {
   1116 			/* Fixup the pseudo-header checksum. */
   1117 			/* XXXJRT Not IP Jumbogram safe. */
   1118 			th->th_sum = in_cksum_addword(th->th_sum,
   1119 			    htons((u_int16_t) (len + optlen)));
   1120 		}
   1121 		break;
   1122 #endif
   1123 #ifdef INET6
   1124 	case AF_INET6:
   1125 		/*
   1126 		 * XXX Actually delaying the checksum is Hard
   1127 		 * XXX (well, maybe not for Itojun, but it is
   1128 		 * XXX for me), but we can still take advantage
   1129 		 * XXX of the cached pseudo-header checksum.
   1130 		 */
   1131 		/* equals to hdrlen + len */
   1132 		m->m_pkthdr.len = sizeof(struct ip6_hdr)
   1133 			+ sizeof(struct tcphdr) + optlen + len;
   1134 #ifdef notyet
   1135 		if (__predict_true(ro->ro_rt == NULL ||
   1136 				   !(ro->ro_rt->rt_ifp->if_flags &
   1137 				     IFF_LOOPBACK) ||
   1138 				   tcp_do_loopback_cksum))
   1139 			m->m_pkthdr.csum_flags = M_CSUM_TCPv6;
   1140 		else
   1141 			m->m_pkthdr.csum_flags = 0;
   1142 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
   1143 #endif
   1144 		if (len + optlen) {
   1145 			/* Fixup the pseudo-header checksum. */
   1146 			/* XXXJRT: Not IPv6 Jumbogram safe. */
   1147 			th->th_sum = in_cksum_addword(th->th_sum,
   1148 			    htons((u_int16_t) (len + optlen)));
   1149 		}
   1150 #ifndef notyet
   1151 		if (__predict_true(ro->ro_rt == NULL ||
   1152 				   !(ro->ro_rt->rt_ifp->if_flags &
   1153 				     IFF_LOOPBACK) ||
   1154 				   tcp_do_loopback_cksum))
   1155 			th->th_sum = in6_cksum(m, 0, sizeof(struct ip6_hdr),
   1156 			    sizeof(struct tcphdr) + optlen + len);
   1157 #endif
   1158 		break;
   1159 #endif
   1160 	}
   1161 
   1162 	/*
   1163 	 * In transmit state, time the transmission and arrange for
   1164 	 * the retransmit.  In persist state, just set snd_max.
   1165 	 */
   1166 	if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
   1167 		tcp_seq startseq = tp->snd_nxt;
   1168 
   1169 		/*
   1170 		 * Advance snd_nxt over sequence space of this segment.
   1171 		 * There are no states in which we send both a SYN and a FIN,
   1172 		 * so we collapse the tests for these flags.
   1173 		 */
   1174 		if (flags & (TH_SYN|TH_FIN))
   1175 			tp->snd_nxt++;
   1176 		tp->snd_nxt += len;
   1177 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
   1178 			tp->snd_max = tp->snd_nxt;
   1179 			/*
   1180 			 * Time this transmission if not a retransmission and
   1181 			 * not currently timing anything.
   1182 			 */
   1183 			if (tp->t_rtttime == 0) {
   1184 				tp->t_rtttime = tcp_now;
   1185 				tp->t_rtseq = startseq;
   1186 				tcpstat.tcps_segstimed++;
   1187 			}
   1188 		}
   1189 
   1190 		/*
   1191 		 * Set retransmit timer if not currently set,
   1192 		 * and not doing an ack or a keep-alive probe.
   1193 		 * Initial value for retransmit timer is smoothed
   1194 		 * round-trip time + 2 * round-trip time variance.
   1195 		 * Initialize shift counter which is used for backoff
   1196 		 * of retransmit time.
   1197 		 */
   1198 		if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
   1199 		    tp->snd_nxt != tp->snd_una) {
   1200 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
   1201 				TCP_TIMER_DISARM(tp, TCPT_PERSIST);
   1202 				tp->t_rxtshift = 0;
   1203 			}
   1204 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   1205 		}
   1206 	} else
   1207 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
   1208 			tp->snd_max = tp->snd_nxt + len;
   1209 
   1210 #ifdef TCP_DEBUG
   1211 	/*
   1212 	 * Trace.
   1213 	 */
   1214 	if (so->so_options & SO_DEBUG)
   1215 		tcp_trace(TA_OUTPUT, tp->t_state, tp, m, 0);
   1216 #endif
   1217 
   1218 	/*
   1219 	 * Fill in IP length and desired time to live and
   1220 	 * send to IP level.  There should be a better way
   1221 	 * to handle ttl and tos; we could keep them in
   1222 	 * the template, but need a way to checksum without them.
   1223 	 */
   1224 	m->m_pkthdr.len = hdrlen + len;
   1225 
   1226 	switch (af) {
   1227 #ifdef INET
   1228 	case AF_INET:
   1229 		ip->ip_len = htons(m->m_pkthdr.len);
   1230 		if (tp->t_inpcb) {
   1231 			ip->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;
   1232 			ip->ip_tos = tp->t_inpcb->inp_ip.ip_tos;
   1233 		}
   1234 #ifdef INET6
   1235 		else if (tp->t_in6pcb) {
   1236 			ip->ip_ttl = in6_selecthlim(tp->t_in6pcb, NULL); /*XXX*/
   1237 			ip->ip_tos = 0;	/*XXX*/
   1238 		}
   1239 #endif
   1240 		break;
   1241 #endif
   1242 #ifdef INET6
   1243 	case AF_INET6:
   1244 		ip6->ip6_nxt = IPPROTO_TCP;
   1245 		if (tp->t_in6pcb) {
   1246 			/*
   1247 			 * we separately set hoplimit for every segment, since
   1248 			 * the user might want to change the value via
   1249 			 * setsockopt. Also, desired default hop limit might
   1250 			 * be changed via Neighbor Discovery.
   1251 			 */
   1252 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb,
   1253 				ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
   1254 		}
   1255 		/* ip6->ip6_flow = ??? */
   1256 		/* ip6_plen will be filled in ip6_output(). */
   1257 		break;
   1258 #endif
   1259 	}
   1260 
   1261 	switch (af) {
   1262 #ifdef INET
   1263 	case AF_INET:
   1264 	    {
   1265 		struct mbuf *opts;
   1266 
   1267 		if (tp->t_inpcb)
   1268 			opts = tp->t_inpcb->inp_options;
   1269 		else
   1270 			opts = NULL;
   1271 		error = ip_output(m, opts, ro,
   1272 			(tp->t_mtudisc ? IP_MTUDISC : 0) |
   1273 			(so->so_options & SO_DONTROUTE),
   1274 			(struct ip_moptions *)0, so);
   1275 		break;
   1276 	    }
   1277 #endif
   1278 #ifdef INET6
   1279 	case AF_INET6:
   1280 	    {
   1281 		struct ip6_pktopts *opts;
   1282 
   1283 		if (tp->t_in6pcb)
   1284 			opts = tp->t_in6pcb->in6p_outputopts;
   1285 		else
   1286 			opts = NULL;
   1287 		error = ip6_output(m, opts, (struct route_in6 *)ro,
   1288 			so->so_options & SO_DONTROUTE,
   1289 			(struct ip6_moptions *)0, so, NULL);
   1290 		break;
   1291 	    }
   1292 #endif
   1293 	default:
   1294 		error = EAFNOSUPPORT;
   1295 		break;
   1296 	}
   1297 	if (error) {
   1298 out:
   1299 		if (error == ENOBUFS) {
   1300 			tcpstat.tcps_selfquench++;
   1301 #ifdef INET
   1302 			if (tp->t_inpcb)
   1303 				tcp_quench(tp->t_inpcb, 0);
   1304 #endif
   1305 #ifdef INET6
   1306 			if (tp->t_in6pcb)
   1307 				tcp6_quench(tp->t_in6pcb, 0);
   1308 #endif
   1309 			error = 0;
   1310 		} else if ((error == EHOSTUNREACH || error == ENETDOWN) &&
   1311 		    TCPS_HAVERCVDSYN(tp->t_state)) {
   1312 			tp->t_softerror = error;
   1313 			error = 0;
   1314 		}
   1315 
   1316 		/* Restart the delayed ACK timer, if necessary. */
   1317 		if (tp->t_flags & TF_DELACK)
   1318 			TCP_RESTART_DELACK(tp);
   1319 
   1320 		return (error);
   1321 	}
   1322 	tcpstat.tcps_sndtotal++;
   1323 	if (tp->t_flags & TF_DELACK)
   1324 		tcpstat.tcps_delack++;
   1325 
   1326 	/*
   1327 	 * Data sent (as far as we can tell).
   1328 	 * If this advertises a larger window than any other segment,
   1329 	 * then remember the size of the advertised window.
   1330 	 * Any pending ACK has now been sent.
   1331 	 */
   1332 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
   1333 		tp->rcv_adv = tp->rcv_nxt + win;
   1334 	tp->last_ack_sent = tp->rcv_nxt;
   1335 	tp->t_flags &= ~TF_ACKNOW;
   1336 	TCP_CLEAR_DELACK(tp);
   1337 #ifdef DIAGNOSTIC
   1338 	if (maxburst < 0)
   1339 		printf("tcp_output: maxburst exceeded by %d\n", -maxburst);
   1340 #endif
   1341 	if (sendalot && (!tcp_do_newreno || --maxburst))
   1342 		goto again;
   1343 	return (0);
   1344 }
   1345 
   1346 void
   1347 tcp_setpersist(tp)
   1348 	struct tcpcb *tp;
   1349 {
   1350 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2);
   1351 	int nticks;
   1352 
   1353 	if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
   1354 		panic("tcp_output REXMT");
   1355 	/*
   1356 	 * Start/restart persistance timer.
   1357 	 */
   1358 	if (t < tp->t_rttmin)
   1359 		t = tp->t_rttmin;
   1360 	TCPT_RANGESET(nticks, t * tcp_backoff[tp->t_rxtshift],
   1361 	    TCPTV_PERSMIN, TCPTV_PERSMAX);
   1362 	TCP_TIMER_ARM(tp, TCPT_PERSIST, nticks);
   1363 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
   1364 		tp->t_rxtshift++;
   1365 }
   1366