Home | History | Annotate | Line # | Download | only in netinet
tcp_output.c revision 1.68
      1 /*	$NetBSD: tcp_output.c,v 1.68 2001/07/26 21:47:04 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, 2001 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 #include "opt_ipsec.h"
    119 #include "opt_tcp_debug.h"
    120 
    121 #include <sys/param.h>
    122 #include <sys/systm.h>
    123 #include <sys/malloc.h>
    124 #include <sys/mbuf.h>
    125 #include <sys/protosw.h>
    126 #include <sys/socket.h>
    127 #include <sys/socketvar.h>
    128 #include <sys/errno.h>
    129 #include <sys/domain.h>
    130 
    131 #include <net/if.h>
    132 #include <net/route.h>
    133 
    134 #include <netinet/in.h>
    135 #include <netinet/in_systm.h>
    136 #include <netinet/ip.h>
    137 #include <netinet/in_pcb.h>
    138 #include <netinet/ip_var.h>
    139 
    140 #ifdef INET6
    141 #ifndef INET
    142 #include <netinet/in.h>
    143 #endif
    144 #include <netinet/ip6.h>
    145 #include <netinet6/in6_pcb.h>
    146 #include <netinet6/ip6_var.h>
    147 #endif
    148 
    149 #include <netinet/tcp.h>
    150 #define	TCPOUTFLAGS
    151 #include <netinet/tcp_fsm.h>
    152 #include <netinet/tcp_seq.h>
    153 #include <netinet/tcp_timer.h>
    154 #include <netinet/tcp_var.h>
    155 #include <netinet/tcpip.h>
    156 #include <netinet/tcp_debug.h>
    157 
    158 #ifdef notyet
    159 extern struct mbuf *m_copypack();
    160 #endif
    161 
    162 #define MAX_TCPOPTLEN	32	/* max # bytes that go in options */
    163 
    164 /*
    165  * Knob to enable Congestion Window Monitoring, and control the
    166  * the burst size it allows.  Default burst is 4 packets, per
    167  * the Internet draft.
    168  */
    169 int	tcp_cwm = 0;
    170 int	tcp_cwm_burstsize = 4;
    171 
    172 static __inline void
    173 tcp_segsize(struct tcpcb *tp, int *txsegsizep, int *rxsegsizep)
    174 {
    175 #ifdef INET
    176 	struct inpcb *inp = tp->t_inpcb;
    177 #endif
    178 #ifdef INET6
    179 	struct in6pcb *in6p = tp->t_in6pcb;
    180 #endif
    181 	struct rtentry *rt;
    182 	struct ifnet *ifp;
    183 	int size;
    184 	int iphlen;
    185 
    186 #ifdef DIAGNOSTIC
    187 	if (tp->t_inpcb && tp->t_in6pcb)
    188 		panic("tcp_segsize: both t_inpcb and t_in6pcb are set");
    189 #endif
    190 	switch (tp->t_family) {
    191 #ifdef INET
    192 	case AF_INET:
    193 		iphlen = sizeof(struct ip);
    194 		break;
    195 #endif
    196 #ifdef INET6
    197 	case AF_INET6:
    198 		iphlen = sizeof(struct ip6_hdr);
    199 		break;
    200 #endif
    201 	default:
    202 		size = tcp_mssdflt;
    203 		goto out;
    204 	}
    205 
    206 	rt = NULL;
    207 #ifdef INET
    208 	if (inp)
    209 		rt = in_pcbrtentry(inp);
    210 #endif
    211 #ifdef INET6
    212 	if (in6p)
    213 		rt = in6_pcbrtentry(in6p);
    214 #endif
    215 	if (rt == NULL) {
    216 		size = tcp_mssdflt;
    217 		goto out;
    218 	}
    219 
    220 	ifp = rt->rt_ifp;
    221 
    222 	size = tcp_mssdflt;
    223 	if (rt->rt_rmx.rmx_mtu != 0)
    224 		size = rt->rt_rmx.rmx_mtu - iphlen - sizeof(struct tcphdr);
    225 	else if (ifp->if_flags & IFF_LOOPBACK)
    226 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    227 #ifdef INET
    228 	else if (inp && ip_mtudisc)
    229 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    230 	else if (inp && in_localaddr(inp->inp_faddr))
    231 		size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    232 #endif
    233 #ifdef INET6
    234 	else if (in6p) {
    235 #ifdef INET
    236 		if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr)) {
    237 			/* mapped addr case */
    238 			struct in_addr d;
    239 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &d, sizeof(d));
    240 			if (ip_mtudisc || in_localaddr(d))
    241 				size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    242 		} else
    243 #endif
    244 		{
    245 			/*
    246 			 * for IPv6, path MTU discovery is always turned on,
    247 			 * or the node must use packet size <= 1280.
    248 			 */
    249 			size = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
    250 		}
    251 	}
    252 #endif
    253 	size -= tcp_optlen(tp);
    254 	/*
    255 	 * XXX tp->t_ourmss should have the right size, but without this code
    256 	 * fragmentation will occur... need more investigation
    257 	 */
    258 #ifdef INET
    259 	if (inp) {
    260 #ifdef IPSEC
    261 		size -= ipsec4_hdrsiz_tcp(tp);
    262 #endif
    263 		size -= ip_optlen(inp);
    264 	}
    265 #endif
    266 #ifdef INET6
    267 #ifdef INET
    268 	if (in6p && tp->t_family == AF_INET) {
    269 #ifdef IPSEC
    270 		size -= ipsec4_hdrsiz_tcp(tp);
    271 #endif
    272 		/* XXX size -= ip_optlen(in6p); */
    273 	} else
    274 #endif
    275 	if (in6p && tp->t_family == AF_INET6) {
    276 #ifdef IPSEC
    277 		size -= ipsec6_hdrsiz_tcp(tp);
    278 #endif
    279 		size -= ip6_optlen(in6p);
    280 	}
    281 #endif
    282 
    283  out:
    284 	/*
    285 	 * *rxsegsizep holds *estimated* inbound segment size (estimation
    286 	 * assumes that path MTU is the same for both ways).  this is only
    287 	 * for silly window avoidance, do not use the value for other purposes.
    288 	 *
    289 	 * ipseclen is subtracted from both sides, this may not be right.
    290 	 * I'm not quite sure about this (could someone comment).
    291 	 */
    292 	*txsegsizep = min(tp->t_peermss, size);
    293 	*rxsegsizep = min(tp->t_ourmss, size);
    294 
    295 	if (*txsegsizep != tp->t_segsz) {
    296 		/*
    297 		 * If the new segment size is larger, we don't want to
    298 		 * mess up the congestion window, but if it is smaller
    299 		 * we'll have to reduce the congestion window to ensure
    300 		 * that we don't get into trouble with initial windows
    301 		 * and the rest.  In any case, if the segment size
    302 		 * has changed, chances are the path has, too, and
    303 		 * our congestion window will be different.
    304 		 */
    305 		if (*txsegsizep < tp->t_segsz) {
    306 			tp->snd_cwnd = max((tp->snd_cwnd / tp->t_segsz)
    307 					   * *txsegsizep, *txsegsizep);
    308 			tp->snd_ssthresh = max((tp->snd_ssthresh / tp->t_segsz)
    309 						* *txsegsizep, *txsegsizep);
    310 		}
    311 		tp->t_segsz = *txsegsizep;
    312 	}
    313 }
    314 
    315 /*
    316  * Tcp output routine: figure out what should be sent and send it.
    317  */
    318 int
    319 tcp_output(tp)
    320 	struct tcpcb *tp;
    321 {
    322 	struct socket *so;
    323 	struct route *ro;
    324 	long len, win;
    325 	int off, flags, error;
    326 	struct mbuf *m;
    327 	struct ip *ip;
    328 #ifdef INET6
    329 	struct ip6_hdr *ip6;
    330 #endif
    331 	struct tcphdr *th;
    332 	u_char opt[MAX_TCPOPTLEN];
    333 	unsigned optlen, hdrlen;
    334 	int idle, sendalot, txsegsize, rxsegsize;
    335 	int maxburst = TCP_MAXBURST;
    336 	int af;		/* address family on the wire */
    337 	int iphdrlen;
    338 
    339 #ifdef DIAGNOSTIC
    340 	if (tp->t_inpcb && tp->t_in6pcb)
    341 		panic("tcp_output: both t_inpcb and t_in6pcb are set");
    342 #endif
    343 	so = NULL;
    344 	ro = NULL;
    345 	if (tp->t_inpcb) {
    346 		so = tp->t_inpcb->inp_socket;
    347 		ro = &tp->t_inpcb->inp_route;
    348 	}
    349 #ifdef INET6
    350 	else if (tp->t_in6pcb) {
    351 		so = tp->t_in6pcb->in6p_socket;
    352 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    353 	}
    354 #endif
    355 
    356 	switch (af = tp->t_family) {
    357 #ifdef INET
    358 	case AF_INET:
    359 		if (tp->t_inpcb)
    360 			break;
    361 #ifdef INET6
    362 		/* mapped addr case */
    363 		if (tp->t_in6pcb)
    364 			break;
    365 #endif
    366 		return EINVAL;
    367 #endif
    368 #ifdef INET6
    369 	case AF_INET6:
    370 		if (tp->t_in6pcb)
    371 			break;
    372 		return EINVAL;
    373 #endif
    374 	default:
    375 		return EAFNOSUPPORT;
    376 	}
    377 
    378 	tcp_segsize(tp, &txsegsize, &rxsegsize);
    379 
    380 	idle = (tp->snd_max == tp->snd_una);
    381 
    382 	/*
    383 	 * Restart Window computation.  From draft-floyd-incr-init-win-03:
    384 	 *
    385 	 *	Optionally, a TCP MAY set the restart window to the
    386 	 *	minimum of the value used for the initial window and
    387 	 *	the current value of cwnd (in other words, using a
    388 	 *	larger value for the restart window should never increase
    389 	 *	the size of cwnd).
    390 	 */
    391 	if (tcp_cwm) {
    392 		/*
    393 		 * Hughes/Touch/Heidemann Congestion Window Monitoring.
    394 		 * Count the number of packets currently pending
    395 		 * acknowledgement, and limit our congestion window
    396 		 * to a pre-determined allowed burst size plus that count.
    397 		 * This prevents bursting once all pending packets have
    398 		 * been acknowledged (i.e. transmission is idle).
    399 		 *
    400 		 * XXX Link this to Initial Window?
    401 		 */
    402 		tp->snd_cwnd = min(tp->snd_cwnd,
    403 		    (tcp_cwm_burstsize * txsegsize) +
    404 		    (tp->snd_nxt - tp->snd_una));
    405 	} else {
    406 		if (idle && tp->t_idle >= tp->t_rxtcur) {
    407 			/*
    408 			 * We have been idle for "a while" and no acks are
    409 			 * expected to clock out any data we send --
    410 			 * slow start to get ack "clock" running again.
    411 			 */
    412 			tp->snd_cwnd = min(tp->snd_cwnd,
    413 			    TCP_INITIAL_WINDOW(tcp_init_win, txsegsize));
    414 		}
    415 	}
    416 
    417 again:
    418 	/*
    419 	 * Determine length of data that should be transmitted, and
    420 	 * flags that should be used.  If there is some data or critical
    421 	 * controls (SYN, RST) to send, then transmit; otherwise,
    422 	 * investigate further.
    423 	 */
    424 	sendalot = 0;
    425 	off = tp->snd_nxt - tp->snd_una;
    426 	win = min(tp->snd_wnd, tp->snd_cwnd);
    427 
    428 	flags = tcp_outflags[tp->t_state];
    429 	/*
    430 	 * If in persist timeout with window of 0, send 1 byte.
    431 	 * Otherwise, if window is small but nonzero
    432 	 * and timer expired, we will send what we can
    433 	 * and go to transmit state.
    434 	 */
    435 	if (tp->t_force) {
    436 		if (win == 0) {
    437 			/*
    438 			 * If we still have some data to send, then
    439 			 * clear the FIN bit.  Usually this would
    440 			 * happen below when it realizes that we
    441 			 * aren't sending all the data.  However,
    442 			 * if we have exactly 1 byte of unset data,
    443 			 * then it won't clear the FIN bit below,
    444 			 * and if we are in persist state, we wind
    445 			 * up sending the packet without recording
    446 			 * that we sent the FIN bit.
    447 			 *
    448 			 * We can't just blindly clear the FIN bit,
    449 			 * because if we don't have any more data
    450 			 * to send then the probe will be the FIN
    451 			 * itself.
    452 			 */
    453 			if (off < so->so_snd.sb_cc)
    454 				flags &= ~TH_FIN;
    455 			win = 1;
    456 		} else {
    457 			TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    458 			tp->t_rxtshift = 0;
    459 		}
    460 	}
    461 
    462 	if (win < so->so_snd.sb_cc) {
    463 		len = win - off;
    464 		flags &= ~TH_FIN;
    465 	} else
    466 		len = so->so_snd.sb_cc - off;
    467 
    468 	if (len < 0) {
    469 		/*
    470 		 * If FIN has been sent but not acked,
    471 		 * but we haven't been called to retransmit,
    472 		 * len will be -1.  Otherwise, window shrank
    473 		 * after we sent into it.  If window shrank to 0,
    474 		 * cancel pending retransmit, pull snd_nxt back
    475 		 * to (closed) window, and set the persist timer
    476 		 * if it isn't already going.  If the window didn't
    477 		 * close completely, just wait for an ACK.
    478 		 *
    479 		 * If we have a pending FIN, either it has already been
    480 		 * transmitted or it is outside the window, so drop it.
    481 		 * If the FIN has been transmitted, but this is not a
    482 		 * retransmission, then len must be -1.  Therefore we also
    483 		 * prevent here the sending of `gratuitous FINs'.  This
    484 		 * eliminates the need to check for that case below (e.g.
    485 		 * to back up snd_nxt before the FIN so that the sequence
    486 		 * number is correct).
    487 		 */
    488 		len = 0;
    489 		flags &= ~TH_FIN;
    490 		if (win == 0) {
    491 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
    492 			tp->t_rxtshift = 0;
    493 			tp->snd_nxt = tp->snd_una;
    494 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
    495 				tcp_setpersist(tp);
    496 		}
    497 	}
    498 	if (len > txsegsize) {
    499 		len = txsegsize;
    500 		flags &= ~TH_FIN;
    501 		sendalot = 1;
    502 	}
    503 
    504 	win = sbspace(&so->so_rcv);
    505 
    506 	/*
    507 	 * Sender silly window avoidance.  If connection is idle
    508 	 * and can send all data, a maximum segment,
    509 	 * at least a maximum default-size segment do it,
    510 	 * or are forced, do it; otherwise don't bother.
    511 	 * If peer's buffer is tiny, then send
    512 	 * when window is at least half open.
    513 	 * If retransmitting (possibly after persist timer forced us
    514 	 * to send into a small window), then must resend.
    515 	 */
    516 	if (len) {
    517 		if (len == txsegsize)
    518 			goto send;
    519 		if ((so->so_state & SS_MORETOCOME) == 0 &&
    520 		    ((idle || tp->t_flags & TF_NODELAY) &&
    521 		     len + off >= so->so_snd.sb_cc))
    522 			goto send;
    523 		if (tp->t_force)
    524 			goto send;
    525 		if (len >= tp->max_sndwnd / 2)
    526 			goto send;
    527 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
    528 			goto send;
    529 	}
    530 
    531 	/*
    532 	 * Compare available window to amount of window known to peer
    533 	 * (as advertised window less next expected input).  If the
    534 	 * difference is at least twice the size of the largest segment
    535 	 * we expect to receive (i.e. two segments) or at least 50% of
    536 	 * the maximum possible window, then want to send a window update
    537 	 * to peer.
    538 	 */
    539 	if (win > 0) {
    540 		/*
    541 		 * "adv" is the amount we can increase the window,
    542 		 * taking into account that we are limited by
    543 		 * TCP_MAXWIN << tp->rcv_scale.
    544 		 */
    545 		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
    546 			(tp->rcv_adv - tp->rcv_nxt);
    547 
    548 		if (adv >= (long) (2 * rxsegsize))
    549 			goto send;
    550 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
    551 			goto send;
    552 	}
    553 
    554 	/*
    555 	 * Send if we owe peer an ACK.
    556 	 */
    557 	if (tp->t_flags & TF_ACKNOW)
    558 		goto send;
    559 	if (flags & (TH_SYN|TH_FIN|TH_RST))
    560 		goto send;
    561 	if (SEQ_GT(tp->snd_up, tp->snd_una))
    562 		goto send;
    563 
    564 	/*
    565 	 * TCP window updates are not reliable, rather a polling protocol
    566 	 * using ``persist'' packets is used to insure receipt of window
    567 	 * updates.  The three ``states'' for the output side are:
    568 	 *	idle			not doing retransmits or persists
    569 	 *	persisting		to move a small or zero window
    570 	 *	(re)transmitting	and thereby not persisting
    571 	 *
    572 	 * tp->t_timer[TCPT_PERSIST]
    573 	 *	is set when we are in persist state.
    574 	 * tp->t_force
    575 	 *	is set when we are called to send a persist packet.
    576 	 * tp->t_timer[TCPT_REXMT]
    577 	 *	is set when we are retransmitting
    578 	 * The output side is idle when both timers are zero.
    579 	 *
    580 	 * If send window is too small, there is data to transmit, and no
    581 	 * retransmit or persist is pending, then go to persist state.
    582 	 * If nothing happens soon, send when timer expires:
    583 	 * if window is nonzero, transmit what we can,
    584 	 * otherwise force out a byte.
    585 	 */
    586 	if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    587 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    588 		tp->t_rxtshift = 0;
    589 		tcp_setpersist(tp);
    590 	}
    591 
    592 	/*
    593 	 * No reason to send a segment, just return.
    594 	 */
    595 	return (0);
    596 
    597 send:
    598 	/*
    599 	 * Before ESTABLISHED, force sending of initial options
    600 	 * unless TCP set not to do any options.
    601 	 * NOTE: we assume that the IP/TCP header plus TCP options
    602 	 * always fit in a single mbuf, leaving room for a maximum
    603 	 * link header, i.e.
    604 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
    605 	 */
    606 	optlen = 0;
    607 	switch (af) {
    608 #ifdef INET
    609 	case AF_INET:
    610 		iphdrlen = sizeof(struct ip) + sizeof(struct tcphdr);
    611 		break;
    612 #endif
    613 #ifdef INET6
    614 	case AF_INET6:
    615 		iphdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    616 		break;
    617 #endif
    618 	default:	/*pacify gcc*/
    619 		iphdrlen = 0;
    620 		break;
    621 	}
    622 	hdrlen = iphdrlen;
    623 	if (flags & TH_SYN) {
    624 		struct rtentry *rt;
    625 
    626 		rt = NULL;
    627 #ifdef INET
    628 		if (tp->t_inpcb)
    629 			rt = in_pcbrtentry(tp->t_inpcb);
    630 #endif
    631 #ifdef INET6
    632 		if (tp->t_in6pcb)
    633 			rt = in6_pcbrtentry(tp->t_in6pcb);
    634 #endif
    635 
    636 		tp->snd_nxt = tp->iss;
    637 		tp->t_ourmss = tcp_mss_to_advertise(rt != NULL ?
    638 						    rt->rt_ifp : NULL, af);
    639 		if ((tp->t_flags & TF_NOOPT) == 0) {
    640 			opt[0] = TCPOPT_MAXSEG;
    641 			opt[1] = 4;
    642 			opt[2] = (tp->t_ourmss >> 8) & 0xff;
    643 			opt[3] = tp->t_ourmss & 0xff;
    644 			optlen = 4;
    645 
    646 			if ((tp->t_flags & TF_REQ_SCALE) &&
    647 			    ((flags & TH_ACK) == 0 ||
    648 			    (tp->t_flags & TF_RCVD_SCALE))) {
    649 				*((u_int32_t *) (opt + optlen)) = htonl(
    650 					TCPOPT_NOP << 24 |
    651 					TCPOPT_WINDOW << 16 |
    652 					TCPOLEN_WINDOW << 8 |
    653 					tp->request_r_scale);
    654 				optlen += 4;
    655 			}
    656 		}
    657  	}
    658 
    659  	/*
    660 	 * Send a timestamp and echo-reply if this is a SYN and our side
    661 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
    662 	 * and our peer have sent timestamps in our SYN's.
    663  	 */
    664  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
    665  	     (flags & TH_RST) == 0 &&
    666  	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
    667 	     (tp->t_flags & TF_RCVD_TSTMP))) {
    668 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
    669 
    670  		/* Form timestamp option as shown in appendix A of RFC 1323. */
    671  		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
    672  		*lp++ = htonl(TCP_TIMESTAMP(tp));
    673  		*lp   = htonl(tp->ts_recent);
    674  		optlen += TCPOLEN_TSTAMP_APPA;
    675  	}
    676 
    677  	hdrlen += optlen;
    678 
    679 #ifdef DIAGNOSTIC
    680 	if (len > txsegsize)
    681 		panic("tcp data to be sent is larger than segment");
    682  	if (max_linkhdr + hdrlen > MCLBYTES)
    683 		panic("tcphdr too big");
    684 #endif
    685 
    686 	/*
    687 	 * Grab a header mbuf, attaching a copy of data to
    688 	 * be transmitted, and initialize the header from
    689 	 * the template for sends on this connection.
    690 	 */
    691 	if (len) {
    692 		if (tp->t_force && len == 1)
    693 			tcpstat.tcps_sndprobe++;
    694 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
    695 			tcpstat.tcps_sndrexmitpack++;
    696 			tcpstat.tcps_sndrexmitbyte += len;
    697 		} else {
    698 			tcpstat.tcps_sndpack++;
    699 			tcpstat.tcps_sndbyte += len;
    700 		}
    701 #ifdef notyet
    702 		if ((m = m_copypack(so->so_snd.sb_mb, off,
    703 		    (int)len, max_linkhdr + hdrlen)) == 0) {
    704 			error = ENOBUFS;
    705 			goto out;
    706 		}
    707 		/*
    708 		 * m_copypack left space for our hdr; use it.
    709 		 */
    710 		m->m_len += hdrlen;
    711 		m->m_data -= hdrlen;
    712 #else
    713 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    714 		if (m != NULL &&
    715 		    (max_linkhdr + hdrlen > MHLEN ||
    716 		     max_linkhdr + hdrlen + len <= MCLBYTES)) {
    717 			MCLGET(m, M_DONTWAIT);
    718 			if ((m->m_flags & M_EXT) == 0) {
    719 				m_freem(m);
    720 				m = NULL;
    721 			}
    722 		}
    723 		if (m == NULL) {
    724 			error = ENOBUFS;
    725 			goto out;
    726 		}
    727 		m->m_data += max_linkhdr;
    728 		m->m_len = hdrlen;
    729 		if (len <= M_TRAILINGSPACE(m)) {
    730 			m_copydata(so->so_snd.sb_mb, off, (int) len,
    731 			    mtod(m, caddr_t) + hdrlen);
    732 			m->m_len += len;
    733 		} else {
    734 			m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
    735 			if (m->m_next == NULL) {
    736 				m_freem(m);
    737 				error = ENOBUFS;
    738 				goto out;
    739 			}
    740 		}
    741 #endif
    742 		/*
    743 		 * If we're sending everything we've got, set PUSH.
    744 		 * (This will keep happy those implementations which only
    745 		 * give data to the user when a buffer fills or
    746 		 * a PUSH comes in.)
    747 		 */
    748 		if (off + len == so->so_snd.sb_cc)
    749 			flags |= TH_PUSH;
    750 	} else {
    751 		if (tp->t_flags & TF_ACKNOW)
    752 			tcpstat.tcps_sndacks++;
    753 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
    754 			tcpstat.tcps_sndctrl++;
    755 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
    756 			tcpstat.tcps_sndurg++;
    757 		else
    758 			tcpstat.tcps_sndwinup++;
    759 
    760 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    761 		if (m != NULL && max_linkhdr + hdrlen > MHLEN) {
    762 			MCLGET(m, M_DONTWAIT);
    763 			if ((m->m_flags & M_EXT) == 0) {
    764 				m_freem(m);
    765 				m = NULL;
    766 			}
    767 		}
    768 		if (m == NULL) {
    769 			error = ENOBUFS;
    770 			goto out;
    771 		}
    772 		m->m_data += max_linkhdr;
    773 		m->m_len = hdrlen;
    774 	}
    775 	m->m_pkthdr.rcvif = (struct ifnet *)0;
    776 	switch (af) {
    777 #ifdef INET
    778 	case AF_INET:
    779 		ip = mtod(m, struct ip *);
    780 #ifdef INET6
    781 		ip6 = NULL;
    782 #endif
    783 		th = (struct tcphdr *)(ip + 1);
    784 		break;
    785 #endif
    786 #ifdef INET6
    787 	case AF_INET6:
    788 		ip = NULL;
    789 		ip6 = mtod(m, struct ip6_hdr *);
    790 		th = (struct tcphdr *)(ip6 + 1);
    791 		break;
    792 #endif
    793 	default:	/*pacify gcc*/
    794 		ip = NULL;
    795 #ifdef INET6
    796 		ip6 = NULL;
    797 #endif
    798 		th = NULL;
    799 		break;
    800 	}
    801 	if (tp->t_template == 0)
    802 		panic("tcp_output");
    803 	if (tp->t_template->m_len < iphdrlen)
    804 		panic("tcp_output");
    805 	bcopy(mtod(tp->t_template, caddr_t), mtod(m, caddr_t), iphdrlen);
    806 
    807 	/*
    808 	 * If we are doing retransmissions, then snd_nxt will
    809 	 * not reflect the first unsent octet.  For ACK only
    810 	 * packets, we do not want the sequence number of the
    811 	 * retransmitted packet, we want the sequence number
    812 	 * of the next unsent octet.  So, if there is no data
    813 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
    814 	 * when filling in ti_seq.  But if we are in persist
    815 	 * state, snd_max might reflect one byte beyond the
    816 	 * right edge of the window, so use snd_nxt in that
    817 	 * case, since we know we aren't doing a retransmission.
    818 	 * (retransmit and persist are mutually exclusive...)
    819 	 */
    820 	if (len || (flags & (TH_SYN|TH_FIN)) ||
    821 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
    822 		th->th_seq = htonl(tp->snd_nxt);
    823 	else
    824 		th->th_seq = htonl(tp->snd_max);
    825 	th->th_ack = htonl(tp->rcv_nxt);
    826 	if (optlen) {
    827 		bcopy((caddr_t)opt, (caddr_t)(th + 1), optlen);
    828 		th->th_off = (sizeof (struct tcphdr) + optlen) >> 2;
    829 	}
    830 	th->th_flags = flags;
    831 	/*
    832 	 * Calculate receive window.  Don't shrink window,
    833 	 * but avoid silly window syndrome.
    834 	 */
    835 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)rxsegsize)
    836 		win = 0;
    837 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
    838 		win = (long)TCP_MAXWIN << tp->rcv_scale;
    839 	if (win < (long)(tp->rcv_adv - tp->rcv_nxt))
    840 		win = (long)(tp->rcv_adv - tp->rcv_nxt);
    841 	th->th_win = htons((u_int16_t) (win>>tp->rcv_scale));
    842 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
    843 		u_int32_t urp = tp->snd_up - tp->snd_nxt;
    844 		if (urp > IP_MAXPACKET)
    845 			urp = IP_MAXPACKET;
    846 		th->th_urp = htons((u_int16_t)urp);
    847 		th->th_flags |= TH_URG;
    848 	} else
    849 		/*
    850 		 * If no urgent pointer to send, then we pull
    851 		 * the urgent pointer to the left edge of the send window
    852 		 * so that it doesn't drift into the send window on sequence
    853 		 * number wraparound.
    854 		 */
    855 		tp->snd_up = tp->snd_una;		/* drag it along */
    856 
    857 	/*
    858 	 * Set ourselves up to be checksummed just before the packet
    859 	 * hits the wire.
    860 	 */
    861 	switch (af) {
    862 #ifdef INET
    863 	case AF_INET:
    864 		m->m_pkthdr.csum_flags = M_CSUM_TCPv4;
    865 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
    866 		if (len + optlen) {
    867 			/* Fixup the pseudo-header checksum. */
    868 			/* XXXJRT Not IP Jumbogram safe. */
    869 			th->th_sum = in_cksum_addword(th->th_sum,
    870 			    htons((u_int16_t) (len + optlen)));
    871 		}
    872 		break;
    873 #endif
    874 #ifdef INET6
    875 	case AF_INET6:
    876 		/*
    877 		 * XXX Actually delaying the checksum is Hard
    878 		 * XXX (well, maybe not for Itojun, but it is
    879 		 * XXX for me), but we can still take advantage
    880 		 * XXX of the cached pseudo-header checksum.
    881 		 */
    882 		/* equals to hdrlen + len */
    883 		m->m_pkthdr.len = sizeof(struct ip6_hdr)
    884 			+ sizeof(struct tcphdr) + optlen + len;
    885 #ifdef notyet
    886 		m->m_pkthdr.csum_flags = M_CSUM_TCPv6;
    887 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
    888 #endif
    889 		if (len + optlen) {
    890 			/* Fixup the pseudo-header checksum. */
    891 			/* XXXJRT: Not IPv6 Jumbogram safe. */
    892 			th->th_sum = in_cksum_addword(th->th_sum,
    893 			    htons((u_int16_t) (len + optlen)));
    894 		}
    895 #ifndef notyet
    896 		th->th_sum = in6_cksum(m, 0, sizeof(struct ip6_hdr),
    897 		    sizeof(struct tcphdr) + optlen + len);
    898 #endif
    899 		break;
    900 #endif
    901 	}
    902 
    903 	/*
    904 	 * In transmit state, time the transmission and arrange for
    905 	 * the retransmit.  In persist state, just set snd_max.
    906 	 */
    907 	if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    908 		tcp_seq startseq = tp->snd_nxt;
    909 
    910 		/*
    911 		 * Advance snd_nxt over sequence space of this segment.
    912 		 * There are no states in which we send both a SYN and a FIN,
    913 		 * so we collapse the tests for these flags.
    914 		 */
    915 		if (flags & (TH_SYN|TH_FIN))
    916 			tp->snd_nxt++;
    917 		tp->snd_nxt += len;
    918 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
    919 			tp->snd_max = tp->snd_nxt;
    920 			/*
    921 			 * Time this transmission if not a retransmission and
    922 			 * not currently timing anything.
    923 			 */
    924 			if (tp->t_rtt == 0) {
    925 				tp->t_rtt = 1;
    926 				tp->t_rtseq = startseq;
    927 				tcpstat.tcps_segstimed++;
    928 			}
    929 		}
    930 
    931 		/*
    932 		 * Set retransmit timer if not currently set,
    933 		 * and not doing an ack or a keep-alive probe.
    934 		 * Initial value for retransmit timer is smoothed
    935 		 * round-trip time + 2 * round-trip time variance.
    936 		 * Initialize shift counter which is used for backoff
    937 		 * of retransmit time.
    938 		 */
    939 		if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    940 		    tp->snd_nxt != tp->snd_una) {
    941 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
    942 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
    943 				TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    944 				tp->t_rxtshift = 0;
    945 			}
    946 		}
    947 	} else
    948 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
    949 			tp->snd_max = tp->snd_nxt + len;
    950 
    951 #ifdef TCP_DEBUG
    952 	/*
    953 	 * Trace.
    954 	 */
    955 	if (so->so_options & SO_DEBUG) {
    956 		/*
    957 		 * need to recover version # field, which was overwritten
    958 		 * on ip_cksum computation.
    959 		 */
    960 		struct ip *sip;
    961 		sip = mtod(m, struct ip *);
    962 		switch (af) {
    963 #ifdef INET
    964 		case AF_INET:
    965 			sip->ip_v = 4;
    966 			break;
    967 #endif
    968 #ifdef INET6
    969 		case AF_INET6:
    970 			sip->ip_v = 6;
    971 			break;
    972 #endif
    973 		}
    974 		tcp_trace(TA_OUTPUT, tp->t_state, tp, m, 0);
    975 	}
    976 #endif
    977 
    978 	/*
    979 	 * Fill in IP length and desired time to live and
    980 	 * send to IP level.  There should be a better way
    981 	 * to handle ttl and tos; we could keep them in
    982 	 * the template, but need a way to checksum without them.
    983 	 */
    984 	m->m_pkthdr.len = hdrlen + len;
    985 
    986 	switch (af) {
    987 #ifdef INET
    988 	case AF_INET:
    989 		ip->ip_len = m->m_pkthdr.len;
    990 		if (tp->t_inpcb) {
    991 			ip->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;
    992 			ip->ip_tos = tp->t_inpcb->inp_ip.ip_tos;
    993 		}
    994 #ifdef INET6
    995 		else if (tp->t_in6pcb) {
    996 			ip->ip_ttl = in6_selecthlim(tp->t_in6pcb, NULL); /*XXX*/
    997 			ip->ip_tos = 0;	/*XXX*/
    998 		}
    999 #endif
   1000 		break;
   1001 #endif
   1002 #ifdef INET6
   1003 	case AF_INET6:
   1004 		ip6->ip6_nxt = IPPROTO_TCP;
   1005 		if (tp->t_in6pcb) {
   1006 			/*
   1007 			 * we separately set hoplimit for every segment, since
   1008 			 * the user might want to change the value via
   1009 			 * setsockopt. Also, desired default hop limit might
   1010 			 * be changed via Neighbor Discovery.
   1011 			 */
   1012 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb,
   1013 				ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
   1014 		}
   1015 		/* ip6->ip6_flow = ??? */
   1016 		/* ip6_plen will be filled in ip6_output(). */
   1017 		break;
   1018 #endif
   1019 	}
   1020 
   1021 #ifdef IPSEC
   1022 	if (ipsec_setsocket(m, so) != 0) {
   1023 		m_freem(m);
   1024 		error = ENOBUFS;
   1025 		goto out;
   1026 	}
   1027 #endif /*IPSEC*/
   1028 
   1029 	switch (af) {
   1030 #ifdef INET
   1031 	case AF_INET:
   1032 	    {
   1033 		struct mbuf *opts;
   1034 
   1035 		if (tp->t_inpcb)
   1036 			opts = tp->t_inpcb->inp_options;
   1037 		else
   1038 			opts = NULL;
   1039 		error = ip_output(m, opts, ro,
   1040 			(ip_mtudisc ? IP_MTUDISC : 0) |
   1041 			(so->so_options & SO_DONTROUTE),
   1042 			0);
   1043 		break;
   1044 	    }
   1045 #endif
   1046 #ifdef INET6
   1047 	case AF_INET6:
   1048 	    {
   1049 		struct ip6_pktopts *opts;
   1050 
   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, NULL);
   1057 		break;
   1058 	    }
   1059 #endif
   1060 	default:
   1061 		error = EAFNOSUPPORT;
   1062 		break;
   1063 	}
   1064 	if (error) {
   1065 out:
   1066 		if (error == ENOBUFS) {
   1067 #ifdef INET
   1068 			if (tp->t_inpcb)
   1069 				tcp_quench(tp->t_inpcb, 0);
   1070 #endif
   1071 #ifdef INET6
   1072 			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 	struct tcpcb *tp;
   1111 {
   1112 	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