Home | History | Annotate | Line # | Download | only in netinet
tcp_output.c revision 1.47.4.1
      1 /*	$NetBSD: tcp_output.c,v 1.47.4.1 1999/07/01 23:47:03 thorpej Exp $	*/
      2 
      3 /*
      4 %%% portions-copyright-nrl-95
      5 Portions of this software are Copyright 1995-1998 by Randall Atkinson,
      6 Ronald Lee, Daniel McDonald, Bao Phan, and Chris Winters. All Rights
      7 Reserved. All rights under this copyright have been assigned to the US
      8 Naval Research Laboratory (NRL). The NRL Copyright Notice and License
      9 Agreement Version 1.1 (January 17, 1995) applies to these portions of the
     10 software.
     11 You should have received a copy of the license with this software. If you
     12 didn't get a copy, you may request one from <license (at) ipv6.nrl.navy.mil>.
     13 
     14 */
     15 
     16 /*
     17  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
     18  * All rights reserved.
     19  *
     20  * Redistribution and use in source and binary forms, with or without
     21  * modification, are permitted provided that the following conditions
     22  * are met:
     23  * 1. Redistributions of source code must retain the above copyright
     24  *    notice, this list of conditions and the following disclaimer.
     25  * 2. Redistributions in binary form must reproduce the above copyright
     26  *    notice, this list of conditions and the following disclaimer in the
     27  *    documentation and/or other materials provided with the distribution.
     28  * 3. Neither the name of the project nor the names of its contributors
     29  *    may be used to endorse or promote products derived from this software
     30  *    without specific prior written permission.
     31  *
     32  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     42  * SUCH DAMAGE.
     43  */
     44 
     45 /*-
     46  * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
     47  * All rights reserved.
     48  *
     49  * This code is derived from software contributed to The NetBSD Foundation
     50  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
     51  * Facility, NASA Ames Research Center.
     52  *
     53  * Redistribution and use in source and binary forms, with or without
     54  * modification, are permitted provided that the following conditions
     55  * are met:
     56  * 1. Redistributions of source code must retain the above copyright
     57  *    notice, this list of conditions and the following disclaimer.
     58  * 2. Redistributions in binary form must reproduce the above copyright
     59  *    notice, this list of conditions and the following disclaimer in the
     60  *    documentation and/or other materials provided with the distribution.
     61  * 3. All advertising materials mentioning features or use of this software
     62  *    must display the following acknowledgement:
     63  *	This product includes software developed by the NetBSD
     64  *	Foundation, Inc. and its contributors.
     65  * 4. Neither the name of The NetBSD Foundation nor the names of its
     66  *    contributors may be used to endorse or promote products derived
     67  *    from this software without specific prior written permission.
     68  *
     69  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     70  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     71  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     72  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     73  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     74  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     75  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     76  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     77  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     78  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     79  * POSSIBILITY OF SUCH DAMAGE.
     80  */
     81 
     82 /*
     83  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
     84  *	The Regents of the University of California.  All rights reserved.
     85  *
     86  * Redistribution and use in source and binary forms, with or without
     87  * modification, are permitted provided that the following conditions
     88  * are met:
     89  * 1. Redistributions of source code must retain the above copyright
     90  *    notice, this list of conditions and the following disclaimer.
     91  * 2. Redistributions in binary form must reproduce the above copyright
     92  *    notice, this list of conditions and the following disclaimer in the
     93  *    documentation and/or other materials provided with the distribution.
     94  * 3. All advertising materials mentioning features or use of this software
     95  *    must display the following acknowledgement:
     96  *	This product includes software developed by the University of
     97  *	California, Berkeley and its contributors.
     98  * 4. Neither the name of the University nor the names of its contributors
     99  *    may be used to endorse or promote products derived from this software
    100  *    without specific prior written permission.
    101  *
    102  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
    103  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    104  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    105  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
    106  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    107  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    108  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    109  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    110  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    111  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    112  * SUCH DAMAGE.
    113  *
    114  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
    115  */
    116 
    117 #include "opt_inet.h"
    118 
    119 #include <sys/param.h>
    120 #include <sys/systm.h>
    121 #include <sys/malloc.h>
    122 #include <sys/mbuf.h>
    123 #include <sys/protosw.h>
    124 #include <sys/socket.h>
    125 #include <sys/socketvar.h>
    126 #include <sys/errno.h>
    127 #include <sys/domain.h>
    128 
    129 #include <net/if.h>
    130 #include <net/route.h>
    131 
    132 #include <netinet/in.h>
    133 #include <netinet/in_systm.h>
    134 #include <netinet/ip.h>
    135 #include <netinet/in_pcb.h>
    136 #include <netinet/ip_var.h>
    137 
    138 #ifdef INET6
    139 #ifndef INET
    140 #include <netinet/in.h>
    141 #endif
    142 #include <netinet/ip6.h>
    143 #include <netinet6/in6_pcb.h>
    144 #include <netinet6/ip6_var.h>
    145 #endif
    146 
    147 #include <netinet/tcp.h>
    148 #define	TCPOUTFLAGS
    149 #include <netinet/tcp_fsm.h>
    150 #include <netinet/tcp_seq.h>
    151 #include <netinet/tcp_timer.h>
    152 #include <netinet/tcp_var.h>
    153 #include <netinet/tcpip.h>
    154 #include <netinet/tcp_debug.h>
    155 
    156 #ifdef notyet
    157 extern struct mbuf *m_copypack();
    158 #endif
    159 
    160 #define MAX_TCPOPTLEN	32	/* max # bytes that go in options */
    161 
    162 /*
    163  * Knob to enable Congestion Window Monitoring, and control the
    164  * the burst size it allows.  Default burst is 4 packets, per
    165  * the Internet draft.
    166  */
    167 int	tcp_cwm = 0;
    168 int	tcp_cwm_burstsize = 4;
    169 
    170 static __inline void tcp_segsize __P((struct tcpcb *, int *, int *));
    171 static __inline void
    172 tcp_segsize(tp, txsegsizep, rxsegsizep)
    173 	struct tcpcb *tp;
    174 	int *txsegsizep, *rxsegsizep;
    175 {
    176 	struct inpcb *inp = tp->t_inpcb;
    177 #ifdef INET6
    178 	struct in6pcb *in6p = tp->t_in6pcb;
    179 #endif
    180 	struct rtentry *rt;
    181 	struct ifnet *ifp;
    182 	int size;
    183 	int iphlen;
    184 
    185 	switch (tp->t_family) {
    186 	case AF_INET:
    187 		iphlen = sizeof(struct ip);
    188 		break;
    189 #ifdef INET6
    190 	case AF_INET6:
    191 		iphlen = sizeof(struct ip6_hdr);
    192 		break;
    193 #endif
    194 	default:
    195 		size = tcp_mssdflt;
    196 		goto out;
    197 	}
    198 
    199 	if (inp)
    200 		rt = in_pcbrtentry(inp);
    201 #if defined(INET6) && !defined(TCP6)
    202 	else if (in6p)
    203 		rt = in6_pcbrtentry(in6p);
    204 #endif
    205 	else
    206 		rt = NULL;
    207 	if (rt == NULL) {
    208 		size = tcp_mssdflt;
    209 		goto out;
    210 	}
    211 
    212 	ifp = rt->rt_ifp;
    213 
    214 	size = tcp_mssdflt;
    215 	if (rt->rt_rmx.rmx_mtu != 0)
    216 		size = rt->rt_rmx.rmx_mtu - iphlen - sizeof(struct tcphdr);
    217 	else if (ip_mtudisc || ifp->if_flags & IFF_LOOPBACK)
    218 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    219 	else if (inp && in_localaddr(inp->inp_faddr))
    220 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    221 #ifdef INET6
    222 	else if (in6p) {
    223 		if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr)) {
    224 			/* mapped addr case */
    225 			struct in_addr d;
    226 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &d, sizeof(d));
    227 			if (in_localaddr(d))
    228 				size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    229 		} else {
    230 			if (in6_localaddr(&in6p->in6p_faddr))
    231 				size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    232 		}
    233 	}
    234 #endif
    235 	size -= tcp_optlen(tp);
    236 	/*
    237 	 * XXX tp->t_ourmss should have the right size, but without this code
    238 	 * fragmentation will occur... need more investigation
    239 	 */
    240 	if (inp) {
    241 #ifdef IPSEC
    242 		size_t t = ipsec4_hdrsiz_tcp(tp);
    243 		if (t < size)
    244 			size -= t;
    245 #endif
    246 		size -= ip_optlen(inp);
    247 	}
    248 #ifdef INET6
    249 	else if (in6p && tp->t_family == AF_INET) {
    250 #ifdef IPSEC
    251 		size_t t = ipsec4_hdrsiz_tcp(tp);
    252 		if (t < size)
    253 			size -= t;
    254 #endif
    255 		/* XXX size -= ip_optlen(in6p); */
    256 	}
    257 	else if (in6p && tp->t_family == AF_INET6) {
    258 #if defined(IPSEC) && !defined(TCP6)
    259 		size_t t = ipsec6_hdrsiz_tcp(tp);
    260 		if (t < size)
    261 			size -= t;
    262 #endif
    263 		size -= ip6_optlen(in6p);
    264 	}
    265 #endif
    266 
    267  out:
    268 	*txsegsizep = min(tp->t_peermss, size);
    269 	*rxsegsizep = min(tp->t_ourmss, size);
    270 
    271 	if (*txsegsizep != tp->t_segsz) {
    272 		/*
    273 		 * If the new segment size is larger, we don't want to
    274 		 * mess up the congestion window, but if it is smaller
    275 		 * we'll have to reduce the congestion window to ensure
    276 		 * that we don't get into trouble with initial windows
    277 		 * and the rest.  In any case, if the segment size
    278 		 * has changed, chances are the path has, too, and
    279 		 * our congestion window will be different.
    280 		 */
    281 		if (*txsegsizep < tp->t_segsz) {
    282 			tp->snd_cwnd = max((tp->snd_cwnd / tp->t_segsz)
    283 					   * *txsegsizep, *txsegsizep);
    284 			tp->snd_ssthresh = max((tp->snd_ssthresh / tp->t_segsz)
    285 						* *txsegsizep, *txsegsizep);
    286 		}
    287 		tp->t_segsz = *txsegsizep;
    288 	}
    289 }
    290 
    291 /*
    292  * Tcp output routine: figure out what should be sent and send it.
    293  */
    294 int
    295 tcp_output(tp)
    296 	register struct tcpcb *tp;
    297 {
    298 	struct socket *so;
    299 	struct route *ro;
    300 	struct rtentry *rt;
    301 	long len, win;
    302 	int off, flags, error;
    303 	register struct mbuf *m;
    304 	struct ip *ip;
    305 #ifdef INET6
    306 	struct ip6_hdr *ip6;
    307 #endif
    308 	register struct tcphdr *th;
    309 	u_char opt[MAX_TCPOPTLEN];
    310 	unsigned optlen, hdrlen;
    311 	int idle, sendalot, txsegsize, rxsegsize;
    312 	int maxburst = TCP_MAXBURST;
    313 	int af;		/* address family on the wire */
    314 	int iphdrlen;
    315 
    316 	so = NULL;
    317 	ro = NULL;
    318 	if (tp->t_inpcb) {
    319 		so = tp->t_inpcb->inp_socket;
    320 		ro = &tp->t_inpcb->inp_route;
    321 	}
    322 #ifdef INET6
    323 	else if (tp->t_in6pcb) {
    324 		so = tp->t_in6pcb->in6p_socket;
    325 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    326 	}
    327 #endif
    328 
    329 	switch (af = tp->t_family) {
    330 	case AF_INET:
    331 		if (tp->t_inpcb)
    332 			break;
    333 #ifdef INET6
    334 		/* mapped addr case */
    335 		if (tp->t_in6pcb)
    336 			break;
    337 #endif
    338 		return EINVAL;
    339 #ifdef INET6
    340 	case AF_INET6:
    341 		if (tp->t_in6pcb)
    342 			break;
    343 		return EINVAL;
    344 #endif
    345 	default:
    346 		return EAFNOSUPPORT;
    347 	}
    348 
    349 	tcp_segsize(tp, &txsegsize, &rxsegsize);
    350 
    351 	idle = (tp->snd_max == tp->snd_una);
    352 
    353 	/*
    354 	 * Restart Window computation.  From draft-floyd-incr-init-win-03:
    355 	 *
    356 	 *	Optionally, a TCP MAY set the restart window to the
    357 	 *	minimum of the value used for the initial window and
    358 	 *	the current value of cwnd (in other words, using a
    359 	 *	larger value for the restart window should never increase
    360 	 *	the size of cwnd).
    361 	 */
    362 	if (tcp_cwm) {
    363 		/*
    364 		 * Hughes/Touch/Heidemann Congestion Window Monitoring.
    365 		 * Count the number of packets currently pending
    366 		 * acknowledgement, and limit our congestion window
    367 		 * to a pre-determined allowed burst size plus that count.
    368 		 * This prevents bursting once all pending packets have
    369 		 * been acknowledged (i.e. transmission is idle).
    370 		 *
    371 		 * XXX Link this to Initial Window?
    372 		 */
    373 		tp->snd_cwnd = min(tp->snd_cwnd,
    374 		    (tcp_cwm_burstsize * txsegsize) +
    375 		    (tp->snd_nxt - tp->snd_una));
    376 	} else {
    377 		if (idle && tp->t_idle >= tp->t_rxtcur) {
    378 			/*
    379 			 * We have been idle for "a while" and no acks are
    380 			 * expected to clock out any data we send --
    381 			 * slow start to get ack "clock" running again.
    382 			 */
    383 			tp->snd_cwnd = min(tp->snd_cwnd,
    384 			    TCP_INITIAL_WINDOW(tcp_init_win, txsegsize));
    385 		}
    386 	}
    387 
    388 again:
    389 	/*
    390 	 * Determine length of data that should be transmitted, and
    391 	 * flags that should be used.  If there is some data or critical
    392 	 * controls (SYN, RST) to send, then transmit; otherwise,
    393 	 * investigate further.
    394 	 */
    395 	sendalot = 0;
    396 	off = tp->snd_nxt - tp->snd_una;
    397 	win = min(tp->snd_wnd, tp->snd_cwnd);
    398 
    399 	flags = tcp_outflags[tp->t_state];
    400 	/*
    401 	 * If in persist timeout with window of 0, send 1 byte.
    402 	 * Otherwise, if window is small but nonzero
    403 	 * and timer expired, we will send what we can
    404 	 * and go to transmit state.
    405 	 */
    406 	if (tp->t_force) {
    407 		if (win == 0) {
    408 			/*
    409 			 * If we still have some data to send, then
    410 			 * clear the FIN bit.  Usually this would
    411 			 * happen below when it realizes that we
    412 			 * aren't sending all the data.  However,
    413 			 * if we have exactly 1 byte of unset data,
    414 			 * then it won't clear the FIN bit below,
    415 			 * and if we are in persist state, we wind
    416 			 * up sending the packet without recording
    417 			 * that we sent the FIN bit.
    418 			 *
    419 			 * We can't just blindly clear the FIN bit,
    420 			 * because if we don't have any more data
    421 			 * to send then the probe will be the FIN
    422 			 * itself.
    423 			 */
    424 			if (off < so->so_snd.sb_cc)
    425 				flags &= ~TH_FIN;
    426 			win = 1;
    427 		} else {
    428 			TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    429 			tp->t_rxtshift = 0;
    430 		}
    431 	}
    432 
    433 	if (win < so->so_snd.sb_cc) {
    434 		len = win - off;
    435 		flags &= ~TH_FIN;
    436 	} else
    437 		len = so->so_snd.sb_cc - off;
    438 
    439 	if (len < 0) {
    440 		/*
    441 		 * If FIN has been sent but not acked,
    442 		 * but we haven't been called to retransmit,
    443 		 * len will be -1.  Otherwise, window shrank
    444 		 * after we sent into it.  If window shrank to 0,
    445 		 * cancel pending retransmit, pull snd_nxt back
    446 		 * to (closed) window, and set the persist timer
    447 		 * if it isn't already going.  If the window didn't
    448 		 * close completely, just wait for an ACK.
    449 		 *
    450 		 * If we have a pending FIN, either it has already been
    451 		 * transmitted or it is outside the window, so drop it.
    452 		 * If the FIN has been transmitted, but this is not a
    453 		 * retransmission, then len must be -1.  Therefore we also
    454 		 * prevent here the sending of `gratuitous FINs'.  This
    455 		 * eliminates the need to check for that case below (e.g.
    456 		 * to back up snd_nxt before the FIN so that the sequence
    457 		 * number is correct).
    458 		 */
    459 		len = 0;
    460 		flags &= ~TH_FIN;
    461 		if (win == 0) {
    462 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
    463 			tp->t_rxtshift = 0;
    464 			tp->snd_nxt = tp->snd_una;
    465 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
    466 				tcp_setpersist(tp);
    467 		}
    468 	}
    469 	if (len > txsegsize) {
    470 		len = txsegsize;
    471 		flags &= ~TH_FIN;
    472 		sendalot = 1;
    473 	}
    474 
    475 	win = sbspace(&so->so_rcv);
    476 
    477 	/*
    478 	 * Sender silly window avoidance.  If connection is idle
    479 	 * and can send all data, a maximum segment,
    480 	 * at least a maximum default-size segment do it,
    481 	 * or are forced, do it; otherwise don't bother.
    482 	 * If peer's buffer is tiny, then send
    483 	 * when window is at least half open.
    484 	 * If retransmitting (possibly after persist timer forced us
    485 	 * to send into a small window), then must resend.
    486 	 */
    487 	if (len) {
    488 		if (len == txsegsize)
    489 			goto send;
    490 		if ((so->so_state & SS_MORETOCOME) == 0 &&
    491 		    ((idle || tp->t_flags & TF_NODELAY) &&
    492 		     len + off >= so->so_snd.sb_cc))
    493 			goto send;
    494 		if (tp->t_force)
    495 			goto send;
    496 		if (len >= tp->max_sndwnd / 2)
    497 			goto send;
    498 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
    499 			goto send;
    500 	}
    501 
    502 	/*
    503 	 * Compare available window to amount of window known to peer
    504 	 * (as advertised window less next expected input).  If the
    505 	 * difference is at least twice the size of the largest segment
    506 	 * we expect to receive (i.e. two segments) or at least 50% of
    507 	 * the maximum possible window, then want to send a window update
    508 	 * to peer.
    509 	 */
    510 	if (win > 0) {
    511 		/*
    512 		 * "adv" is the amount we can increase the window,
    513 		 * taking into account that we are limited by
    514 		 * TCP_MAXWIN << tp->rcv_scale.
    515 		 */
    516 		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
    517 			(tp->rcv_adv - tp->rcv_nxt);
    518 
    519 		if (adv >= (long) (2 * rxsegsize))
    520 			goto send;
    521 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
    522 			goto send;
    523 	}
    524 
    525 	/*
    526 	 * Send if we owe peer an ACK.
    527 	 */
    528 	if (tp->t_flags & TF_ACKNOW)
    529 		goto send;
    530 	if (flags & (TH_SYN|TH_FIN|TH_RST))
    531 		goto send;
    532 	if (SEQ_GT(tp->snd_up, tp->snd_una))
    533 		goto send;
    534 
    535 	/*
    536 	 * TCP window updates are not reliable, rather a polling protocol
    537 	 * using ``persist'' packets is used to insure receipt of window
    538 	 * updates.  The three ``states'' for the output side are:
    539 	 *	idle			not doing retransmits or persists
    540 	 *	persisting		to move a small or zero window
    541 	 *	(re)transmitting	and thereby not persisting
    542 	 *
    543 	 * tp->t_timer[TCPT_PERSIST]
    544 	 *	is set when we are in persist state.
    545 	 * tp->t_force
    546 	 *	is set when we are called to send a persist packet.
    547 	 * tp->t_timer[TCPT_REXMT]
    548 	 *	is set when we are retransmitting
    549 	 * The output side is idle when both timers are zero.
    550 	 *
    551 	 * If send window is too small, there is data to transmit, and no
    552 	 * retransmit or persist is pending, then go to persist state.
    553 	 * If nothing happens soon, send when timer expires:
    554 	 * if window is nonzero, transmit what we can,
    555 	 * otherwise force out a byte.
    556 	 */
    557 	if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    558 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    559 		tp->t_rxtshift = 0;
    560 		tcp_setpersist(tp);
    561 	}
    562 
    563 	/*
    564 	 * No reason to send a segment, just return.
    565 	 */
    566 	return (0);
    567 
    568 send:
    569 	/*
    570 	 * Before ESTABLISHED, force sending of initial options
    571 	 * unless TCP set not to do any options.
    572 	 * NOTE: we assume that the IP/TCP header plus TCP options
    573 	 * always fit in a single mbuf, leaving room for a maximum
    574 	 * link header, i.e.
    575 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
    576 	 */
    577 	optlen = 0;
    578 	switch (af) {
    579 	case AF_INET:
    580 		iphdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
    581 		break;
    582 #ifdef INET6
    583 	case AF_INET6:
    584 		iphdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    585 		break;
    586 #endif
    587 	}
    588 	hdrlen = iphdrlen;
    589 	if (flags & TH_SYN) {
    590 		struct rtentry *rt;
    591 
    592 		if (tp->t_inpcb)
    593 			rt = in_pcbrtentry(tp->t_inpcb);
    594 #if defined(INET6) && !defined(TCP6)
    595 		else if (tp->t_in6pcb)
    596 			rt = in6_pcbrtentry(tp->t_in6pcb);
    597 #endif
    598 		else
    599 			rt = NULL;
    600 
    601 		tp->snd_nxt = tp->iss;
    602 		tp->t_ourmss = tcp_mss_to_advertise(rt != NULL ?
    603 						    rt->rt_ifp : NULL);
    604 #ifdef IPSEC
    605 	    {
    606 		size_t t;
    607 		switch (af) {
    608 		case AF_INET:
    609 			t = ipsec4_hdrsiz_tcp(tp);
    610 			break;
    611 #if defined(INET6) && !defined(TCP6)
    612 		case AF_INET6:
    613 			t = ipsec6_hdrsiz_tcp(tp);
    614 			break;
    615 #endif
    616 		}
    617 		if (t < tp->t_ourmss)
    618 			tp->t_ourmss -= t;
    619 	    }
    620 #endif
    621 		if ((tp->t_flags & TF_NOOPT) == 0) {
    622 			opt[0] = TCPOPT_MAXSEG;
    623 			opt[1] = 4;
    624 			opt[2] = (tp->t_ourmss >> 8) & 0xff;
    625 			opt[3] = tp->t_ourmss & 0xff;
    626 			optlen = 4;
    627 
    628 			if ((tp->t_flags & TF_REQ_SCALE) &&
    629 			    ((flags & TH_ACK) == 0 ||
    630 			    (tp->t_flags & TF_RCVD_SCALE))) {
    631 				*((u_int32_t *) (opt + optlen)) = htonl(
    632 					TCPOPT_NOP << 24 |
    633 					TCPOPT_WINDOW << 16 |
    634 					TCPOLEN_WINDOW << 8 |
    635 					tp->request_r_scale);
    636 				optlen += 4;
    637 			}
    638 		}
    639  	}
    640 
    641  	/*
    642 	 * Send a timestamp and echo-reply if this is a SYN and our side
    643 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
    644 	 * and our peer have sent timestamps in our SYN's.
    645  	 */
    646  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
    647  	     (flags & TH_RST) == 0 &&
    648  	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
    649 	     (tp->t_flags & TF_RCVD_TSTMP))) {
    650 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
    651 
    652  		/* Form timestamp option as shown in appendix A of RFC 1323. */
    653  		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
    654  		*lp++ = htonl(tcp_now);
    655  		*lp   = htonl(tp->ts_recent);
    656  		optlen += TCPOLEN_TSTAMP_APPA;
    657  	}
    658 
    659  	hdrlen += optlen;
    660 
    661 #ifdef DIAGNOSTIC
    662 	if (len > txsegsize)
    663 		panic("tcp data to be sent is larger than segment");
    664  	if (max_linkhdr + hdrlen > MCLBYTES)
    665 		panic("tcphdr too big");
    666 #endif
    667 
    668 	/*
    669 	 * Grab a header mbuf, attaching a copy of data to
    670 	 * be transmitted, and initialize the header from
    671 	 * the template for sends on this connection.
    672 	 */
    673 	if (len) {
    674 		if (tp->t_force && len == 1)
    675 			tcpstat.tcps_sndprobe++;
    676 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
    677 			tcpstat.tcps_sndrexmitpack++;
    678 			tcpstat.tcps_sndrexmitbyte += len;
    679 		} else {
    680 			tcpstat.tcps_sndpack++;
    681 			tcpstat.tcps_sndbyte += len;
    682 		}
    683 #ifdef notyet
    684 		if ((m = m_copypack(so->so_snd.sb_mb, off,
    685 		    (int)len, max_linkhdr + hdrlen)) == 0) {
    686 			error = ENOBUFS;
    687 			goto out;
    688 		}
    689 		/*
    690 		 * m_copypack left space for our hdr; use it.
    691 		 */
    692 		m->m_len += hdrlen;
    693 		m->m_data -= hdrlen;
    694 #else
    695 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    696 		if (m != NULL) {
    697 			MCLGET(m, M_DONTWAIT);
    698 			if ((m->m_flags & M_EXT) == 0) {
    699 				m_freem(m);
    700 				m = NULL;
    701 			}
    702 		}
    703 		if (m == NULL) {
    704 			error = ENOBUFS;
    705 			goto out;
    706 		}
    707 		m->m_data += max_linkhdr;
    708 		m->m_len = hdrlen;
    709 		if (len <= MCLBYTES - hdrlen - max_linkhdr) {
    710 			m_copydata(so->so_snd.sb_mb, off, (int) len,
    711 			    mtod(m, caddr_t) + hdrlen);
    712 			m->m_len += len;
    713 		} else {
    714 			m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
    715 			if (m->m_next == 0) {
    716 				m_freem(m);
    717 				error = ENOBUFS;
    718 				goto out;
    719 			}
    720 		}
    721 #endif
    722 		/*
    723 		 * If we're sending everything we've got, set PUSH.
    724 		 * (This will keep happy those implementations which only
    725 		 * give data to the user when a buffer fills or
    726 		 * a PUSH comes in.)
    727 		 */
    728 		if (off + len == so->so_snd.sb_cc)
    729 			flags |= TH_PUSH;
    730 	} else {
    731 		if (tp->t_flags & TF_ACKNOW)
    732 			tcpstat.tcps_sndacks++;
    733 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
    734 			tcpstat.tcps_sndctrl++;
    735 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
    736 			tcpstat.tcps_sndurg++;
    737 		else
    738 			tcpstat.tcps_sndwinup++;
    739 
    740 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    741 		if (m != NULL) {
    742 			MCLGET(m, M_DONTWAIT);
    743 			if ((m->m_flags & M_EXT) == 0) {
    744 				m_freem(m);
    745 				m = NULL;
    746 			}
    747 		}
    748 		if (m == NULL) {
    749 			error = ENOBUFS;
    750 			goto out;
    751 		}
    752 		m->m_data += max_linkhdr;
    753 		m->m_len = hdrlen;
    754 	}
    755 	m->m_pkthdr.rcvif = (struct ifnet *)0;
    756 	switch (af) {
    757 	case AF_INET:
    758 		ip = mtod(m, struct ip *);
    759 #ifdef INET6
    760 		ip6 = NULL;
    761 #endif
    762 		th = (struct tcphdr *)(ip + 1);
    763 		break;
    764 #ifdef INET6
    765 	case AF_INET6:
    766 		ip = NULL;
    767 		ip6 = mtod(m, struct ip6_hdr *);
    768 		th = (struct tcphdr *)(ip6 + 1);
    769 		break;
    770 #endif
    771 	}
    772 	if (tp->t_template == 0)
    773 		panic("tcp_output");
    774 	if (tp->t_template->m_len < iphdrlen)
    775 		panic("tcp_output");
    776 	bcopy(mtod(tp->t_template, caddr_t), mtod(m, caddr_t), iphdrlen);
    777 
    778 	/*
    779 	 * If we are doing retransmissions, then snd_nxt will
    780 	 * not reflect the first unsent octet.  For ACK only
    781 	 * packets, we do not want the sequence number of the
    782 	 * retransmitted packet, we want the sequence number
    783 	 * of the next unsent octet.  So, if there is no data
    784 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
    785 	 * when filling in ti_seq.  But if we are in persist
    786 	 * state, snd_max might reflect one byte beyond the
    787 	 * right edge of the window, so use snd_nxt in that
    788 	 * case, since we know we aren't doing a retransmission.
    789 	 * (retransmit and persist are mutually exclusive...)
    790 	 */
    791 	if (len || (flags & (TH_SYN|TH_FIN)) ||
    792 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
    793 		th->th_seq = htonl(tp->snd_nxt);
    794 	else
    795 		th->th_seq = htonl(tp->snd_max);
    796 	th->th_ack = htonl(tp->rcv_nxt);
    797 	if (optlen) {
    798 		bcopy((caddr_t)opt, (caddr_t)(th + 1), optlen);
    799 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
    800 	}
    801 	th->th_flags = flags;
    802 	/*
    803 	 * Calculate receive window.  Don't shrink window,
    804 	 * but avoid silly window syndrome.
    805 	 */
    806 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)rxsegsize)
    807 		win = 0;
    808 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
    809 		win = (long)TCP_MAXWIN << tp->rcv_scale;
    810 	if (win < (long)(tp->rcv_adv - tp->rcv_nxt))
    811 		win = (long)(tp->rcv_adv - tp->rcv_nxt);
    812 	th->th_win = htons((u_int16_t) (win>>tp->rcv_scale));
    813 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
    814 		u_int32_t urp = tp->snd_up - tp->snd_nxt;
    815 		if (urp > IP_MAXPACKET)
    816 			urp = IP_MAXPACKET;
    817 		th->th_urp = htons((u_int16_t)urp);
    818 		th->th_flags |= TH_URG;
    819 	} else
    820 		/*
    821 		 * If no urgent pointer to send, then we pull
    822 		 * the urgent pointer to the left edge of the send window
    823 		 * so that it doesn't drift into the send window on sequence
    824 		 * number wraparound.
    825 		 */
    826 		tp->snd_up = tp->snd_una;		/* drag it along */
    827 
    828 	/*
    829 	 * Put TCP length in extended header, and then
    830 	 * checksum extended header and data.
    831 	 */
    832 	switch (af) {
    833 	case AF_INET:
    834 	    {
    835 		struct ipovly *ipov = (struct ipovly *)ip;
    836 		if (len + optlen)
    837 			ipov->ih_len = htons((u_int16_t)(sizeof(struct tcphdr) +
    838 			    optlen + len));
    839 		bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
    840 		th->th_sum = 0;
    841 		th->th_sum = in_cksum(m, (int)(hdrlen + len));
    842 		break;
    843 	    }
    844 #ifdef INET6
    845 	case AF_INET6:
    846 		/* equals to hdrlen + len */
    847 		m->m_pkthdr.len = sizeof(struct ip6_hdr)
    848 			+ sizeof(struct tcphdr) + optlen + len;
    849 		th->th_sum = 0;
    850 		th->th_sum = in6_cksum(m, IPPROTO_TCP,
    851 				sizeof(struct ip6_hdr),
    852 				sizeof(struct tcphdr) + optlen + len);
    853 		break;
    854 #endif
    855 	}
    856 
    857 	/*
    858 	 * In transmit state, time the transmission and arrange for
    859 	 * the retransmit.  In persist state, just set snd_max.
    860 	 */
    861 	if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    862 		tcp_seq startseq = tp->snd_nxt;
    863 
    864 		/*
    865 		 * Advance snd_nxt over sequence space of this segment.
    866 		 * There are no states in which we send both a SYN and a FIN,
    867 		 * so we collapse the tests for these flags.
    868 		 */
    869 		if (flags & (TH_SYN|TH_FIN))
    870 			tp->snd_nxt++;
    871 		tp->snd_nxt += len;
    872 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
    873 			tp->snd_max = tp->snd_nxt;
    874 			/*
    875 			 * Time this transmission if not a retransmission and
    876 			 * not currently timing anything.
    877 			 */
    878 			if (tp->t_rtt == 0) {
    879 				tp->t_rtt = 1;
    880 				tp->t_rtseq = startseq;
    881 				tcpstat.tcps_segstimed++;
    882 			}
    883 		}
    884 
    885 		/*
    886 		 * Set retransmit timer if not currently set,
    887 		 * and not doing an ack or a keep-alive probe.
    888 		 * Initial value for retransmit timer is smoothed
    889 		 * round-trip time + 2 * round-trip time variance.
    890 		 * Initialize shift counter which is used for backoff
    891 		 * of retransmit time.
    892 		 */
    893 		if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    894 		    tp->snd_nxt != tp->snd_una) {
    895 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
    896 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
    897 				TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    898 				tp->t_rxtshift = 0;
    899 			}
    900 		}
    901 	} else
    902 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
    903 			tp->snd_max = tp->snd_nxt + len;
    904 
    905 	/*
    906 	 * Trace.
    907 	 */
    908 	if (so->so_options & SO_DEBUG) {
    909 		/*
    910 		 * need to recover version # field, which was overwritten
    911 		 * on ip_cksum computation.
    912 		 */
    913 		struct ip *sip;
    914 		sip = mtod(m, struct ip *);
    915 		switch (af) {
    916 		case AF_INET:
    917 			sip->ip_v = 4;
    918 			break;
    919 #ifdef INET6
    920 		case AF_INET6:
    921 			sip->ip_v = 6;
    922 			break;
    923 #endif
    924 		}
    925 		tcp_trace(TA_OUTPUT, tp->t_state, tp, m, 0);
    926 	}
    927 
    928 	/*
    929 	 * Fill in IP length and desired time to live and
    930 	 * send to IP level.  There should be a better way
    931 	 * to handle ttl and tos; we could keep them in
    932 	 * the template, but need a way to checksum without them.
    933 	 */
    934 	m->m_pkthdr.len = hdrlen + len;
    935 
    936 	switch (af) {
    937 	case AF_INET:
    938 		ip->ip_len = m->m_pkthdr.len;
    939 		if (tp->t_inpcb) {
    940 			ip->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;
    941 			ip->ip_tos = tp->t_inpcb->inp_ip.ip_tos;
    942 		}
    943 #ifdef INET6
    944 		else if (tp->t_in6pcb) {
    945 			ip->ip_ttl = tp->t_in6pcb->in6p_ip6.ip6_hlim;
    946 			ip->ip_tos = 0;	/*XXX*/
    947 		}
    948 #endif
    949 		break;
    950 #ifdef INET6
    951 	case AF_INET6:
    952 		ip6->ip6_nxt = IPPROTO_TCP;
    953 		if (tp->t_in6pcb)
    954 			ip6->ip6_hlim = tp->t_in6pcb->in6p_ip6.ip6_hlim;
    955 		/* ip6->ip6_flow = ??? */
    956 		/* ip6_plen will be filled in ip6_output(). */
    957 		break;
    958 #endif
    959 	}
    960 
    961 	/*
    962 	 * If we're doing Path MTU discovery, we need to set DF unless
    963 	 * the route's MTU is locked.  If we lack a route, we need to
    964 	 * look it up now.
    965 	 *
    966 	 * ip_output() could do this for us, but it's convenient to just
    967 	 * do it here unconditionally.
    968 	 */
    969 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
    970 		if (ro->ro_rt != NULL) {
    971 			RTFREE(ro->ro_rt);
    972 			ro->ro_rt = NULL;
    973 		}
    974 		switch (af) {
    975 		case AF_INET:
    976 		    {
    977 			struct sockaddr_in *dst;
    978 			dst = satosin(&ro->ro_dst);
    979 			dst->sin_family = AF_INET;
    980 			dst->sin_len = sizeof(*dst);
    981 			if (tp->t_inpcb)
    982 				dst->sin_addr = tp->t_inpcb->inp_faddr;
    983 #ifdef INET6
    984 			else if (tp->t_in6pcb) {
    985 				bcopy(&tp->t_in6pcb->in6p_faddr.s6_addr32[3],
    986 					&dst->sin_addr, sizeof(dst->sin_addr));
    987 			}
    988 #endif
    989 			break;
    990 		    }
    991 #ifdef INET6
    992 		case AF_INET6:
    993 		    {
    994 			struct sockaddr_in6 *dst;
    995 			dst = satosin6(&ro->ro_dst);
    996 			dst->sin6_family = AF_INET6;
    997 			dst->sin6_len = sizeof(*dst);
    998 			dst->sin6_addr = tp->t_in6pcb->in6p_faddr;
    999 			break;
   1000 		    }
   1001 #endif
   1002 		}
   1003 		rtalloc(ro);
   1004 		if ((rt = ro->ro_rt) == NULL) {
   1005 			m_freem(m);
   1006 			switch (af) {
   1007 			case AF_INET:
   1008 				ipstat.ips_noroute++;
   1009 				break;
   1010 #ifdef INET6
   1011 			case AF_INET6:
   1012 				ip6stat.ip6s_noroute++;
   1013 				break;
   1014 #endif
   1015 			}
   1016 			error = EHOSTUNREACH;
   1017 			goto out;
   1018 		}
   1019 	}
   1020 #ifdef IPSEC
   1021 	m->m_pkthdr.rcvif = (struct ifnet *)so;
   1022 #endif /*IPSEC*/
   1023 
   1024 	switch (af) {
   1025 	case AF_INET:
   1026 	    {
   1027 		struct mbuf *opts;
   1028 
   1029 		if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
   1030 			ip->ip_off |= IP_DF;
   1031 
   1032 #if BSD >= 43
   1033 		if (tp->t_inpcb)
   1034 			opts = tp->t_inpcb->inp_options;
   1035 		else
   1036 			opts = NULL;
   1037 		error = ip_output(m, opts, ro,
   1038 			so->so_options & SO_DONTROUTE, 0);
   1039 #else
   1040 		opts = NULL;
   1041 		error = ip_output(m, opts, ro, so->so_options & SO_DONTROUTE);
   1042 #endif
   1043 		break;
   1044 	    }
   1045 #ifdef INET6
   1046 	case AF_INET6:
   1047 	    {
   1048 		struct ip6_pktopts *opts;
   1049 
   1050 #if BSD >= 43
   1051 		if (tp->t_in6pcb)
   1052 			opts = tp->t_in6pcb->in6p_outputopts;
   1053 		else
   1054 			opts = NULL;
   1055 		error = ip6_output(m, opts, (struct route_in6 *)ro,
   1056 			so->so_options & SO_DONTROUTE, 0);
   1057 #else
   1058 		opts = NULL;
   1059 		error = ip6_output(m, opts, (struct route_in6 *)ro,
   1060 			so->so_options & SO_DONTROUTE);
   1061 #endif
   1062 		break;
   1063 	    }
   1064 #endif
   1065 	}
   1066 	if (error) {
   1067 out:
   1068 		if (error == ENOBUFS) {
   1069 			if (tp->t_inpcb)
   1070 				tcp_quench(tp->t_inpcb, 0);
   1071 #if 0 /*XXX def INET6*/
   1072 			else if (tp->t_in6pcb)
   1073 				tcp6_quench(tp->t_in6pcb, 0);
   1074 #endif
   1075 			return (0);
   1076 		}
   1077 		if ((error == EHOSTUNREACH || error == ENETDOWN)
   1078 		    && TCPS_HAVERCVDSYN(tp->t_state)) {
   1079 			tp->t_softerror = error;
   1080 			return (0);
   1081 		}
   1082 		return (error);
   1083 	}
   1084 	tcpstat.tcps_sndtotal++;
   1085 	if (tp->t_flags & TF_DELACK)
   1086 		tcpstat.tcps_delack++;
   1087 
   1088 	/*
   1089 	 * Data sent (as far as we can tell).
   1090 	 * If this advertises a larger window than any other segment,
   1091 	 * then remember the size of the advertised window.
   1092 	 * Any pending ACK has now been sent.
   1093 	 */
   1094 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
   1095 		tp->rcv_adv = tp->rcv_nxt + win;
   1096 	tp->last_ack_sent = tp->rcv_nxt;
   1097 	tp->t_flags &= ~TF_ACKNOW;
   1098 	TCP_CLEAR_DELACK(tp);
   1099 #ifdef DIAGNOSTIC
   1100 	if (maxburst < 0)
   1101 		printf("tcp_output: maxburst exceeded by %d\n", -maxburst);
   1102 #endif
   1103 	if (sendalot && (!tcp_do_newreno || --maxburst))
   1104 		goto again;
   1105 	return (0);
   1106 }
   1107 
   1108 void
   1109 tcp_setpersist(tp)
   1110 	register struct tcpcb *tp;
   1111 {
   1112 	register int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2);
   1113 	int nticks;
   1114 
   1115 	if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
   1116 		panic("tcp_output REXMT");
   1117 	/*
   1118 	 * Start/restart persistance timer.
   1119 	 */
   1120 	if (t < tp->t_rttmin)
   1121 		t = tp->t_rttmin;
   1122 	TCPT_RANGESET(nticks, t * tcp_backoff[tp->t_rxtshift],
   1123 	    TCPTV_PERSMIN, TCPTV_PERSMAX);
   1124 	TCP_TIMER_ARM(tp, TCPT_PERSIST, nticks);
   1125 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
   1126 		tp->t_rxtshift++;
   1127 }
   1128