Home | History | Annotate | Line # | Download | only in netinet
tcp_output.c revision 1.43
      1 /*	$NetBSD: tcp_output.c,v 1.43 1998/07/21 10:46:00 mycroft Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
      9  * Facility, NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. All advertising materials mentioning features or use of this software
     53  *    must display the following acknowledgement:
     54  *	This product includes software developed by the University of
     55  *	California, Berkeley and its contributors.
     56  * 4. Neither the name of the University nor the names of its contributors
     57  *    may be used to endorse or promote products derived from this software
     58  *    without specific prior written permission.
     59  *
     60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     70  * SUCH DAMAGE.
     71  *
     72  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
     73  */
     74 
     75 #include <sys/param.h>
     76 #include <sys/systm.h>
     77 #include <sys/malloc.h>
     78 #include <sys/mbuf.h>
     79 #include <sys/protosw.h>
     80 #include <sys/socket.h>
     81 #include <sys/socketvar.h>
     82 #include <sys/errno.h>
     83 
     84 #include <net/if.h>
     85 #include <net/route.h>
     86 
     87 #include <netinet/in.h>
     88 #include <netinet/in_systm.h>
     89 #include <netinet/ip.h>
     90 #include <netinet/in_pcb.h>
     91 #include <netinet/ip_var.h>
     92 #include <netinet/tcp.h>
     93 #define	TCPOUTFLAGS
     94 #include <netinet/tcp_fsm.h>
     95 #include <netinet/tcp_seq.h>
     96 #include <netinet/tcp_timer.h>
     97 #include <netinet/tcp_var.h>
     98 #include <netinet/tcpip.h>
     99 #include <netinet/tcp_debug.h>
    100 
    101 #ifdef notyet
    102 extern struct mbuf *m_copypack();
    103 #endif
    104 
    105 #define MAX_TCPOPTLEN	32	/* max # bytes that go in options */
    106 
    107 /*
    108  * Knob to enable Congestion Window Monitoring, and control the
    109  * the burst size it allows.  Default burst is 4 packets, per
    110  * the Internet draft.
    111  */
    112 int	tcp_cwm = 0;
    113 int	tcp_cwm_burstsize = 4;
    114 
    115 static __inline void tcp_segsize __P((struct tcpcb *, int *, int *));
    116 static __inline void
    117 tcp_segsize(tp, txsegsizep, rxsegsizep)
    118 	struct tcpcb *tp;
    119 	int *txsegsizep, *rxsegsizep;
    120 {
    121 	struct inpcb *inp = tp->t_inpcb;
    122 	struct rtentry *rt;
    123 	struct ifnet *ifp;
    124 	int size;
    125 
    126 	if ((rt = in_pcbrtentry(inp)) == NULL) {
    127 		size = tcp_mssdflt;
    128 		goto out;
    129 	}
    130 
    131 	ifp = rt->rt_ifp;
    132 
    133 	if (rt->rt_rmx.rmx_mtu != 0)
    134 		size = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
    135 	else if (ip_mtudisc || in_localaddr(inp->inp_faddr) ||
    136 		 ifp->if_flags & IFF_LOOPBACK)
    137 		size = ifp->if_mtu - sizeof(struct tcpiphdr);
    138 	else
    139 		size = tcp_mssdflt;
    140 	size -= (tcp_optlen(tp) + ip_optlen(tp->t_inpcb));
    141 
    142  out:
    143 	*txsegsizep = min(tp->t_peermss, size);
    144 	*rxsegsizep = min(tp->t_ourmss, size);
    145 
    146 	if (*txsegsizep != tp->t_segsz) {
    147 		/*
    148 		 * If the new segment size is larger, we don't want to
    149 		 * mess up the congestion window, but if it is smaller
    150 		 * we'll have to reduce the congestion window to ensure
    151 		 * that we don't get into trouble with initial windows
    152 		 * and the rest.  In any case, if the segment size
    153 		 * has changed, chances are the path has, too, and
    154 		 * our congestion window will be different.
    155 		 */
    156 		if (*txsegsizep < tp->t_segsz) {
    157 			tp->snd_cwnd = max((tp->snd_cwnd / tp->t_segsz)
    158 					   * *txsegsizep, *txsegsizep);
    159 			tp->snd_ssthresh = max((tp->snd_ssthresh / tp->t_segsz)
    160 						* *txsegsizep, *txsegsizep);
    161 		}
    162 		tp->t_segsz = *txsegsizep;
    163 	}
    164 }
    165 
    166 /*
    167  * Tcp output routine: figure out what should be sent and send it.
    168  */
    169 int
    170 tcp_output(tp)
    171 	register struct tcpcb *tp;
    172 {
    173 	register struct socket *so = tp->t_inpcb->inp_socket;
    174 	register long len, win;
    175 	int off, flags, error;
    176 	register struct mbuf *m;
    177 	register struct tcpiphdr *ti;
    178 	u_char opt[MAX_TCPOPTLEN];
    179 	unsigned optlen, hdrlen;
    180 	int idle, sendalot, txsegsize, rxsegsize;
    181 
    182 	tcp_segsize(tp, &txsegsize, &rxsegsize);
    183 
    184 	idle = (tp->snd_max == tp->snd_una);
    185 
    186 	/*
    187 	 * Restart Window computation.  From draft-floyd-incr-init-win-03:
    188 	 *
    189 	 *	Optionally, a TCP MAY set the restart window to the
    190 	 *	minimum of the value used for the initial window and
    191 	 *	the current value of cwnd (in other words, using a
    192 	 *	larger value for the restart window should never increase
    193 	 *	the size of cwnd).
    194 	 */
    195 	if (tcp_cwm) {
    196 		/*
    197 		 * Hughes/Touch/Heidemann Congestion Window Monitoring.
    198 		 * Count the number of packets currently pending
    199 		 * acknowledgement, and limit our congestion window
    200 		 * to a pre-determined allowed burst size plus that count.
    201 		 * This prevents bursting once all pending packets have
    202 		 * been acknowledged (i.e. transmission is idle).
    203 		 *
    204 		 * XXX Link this to Initial Window?
    205 		 */
    206 		tp->snd_cwnd = min(tp->snd_cwnd,
    207 		    (tcp_cwm_burstsize * txsegsize) +
    208 		    (tp->snd_nxt - tp->snd_una));
    209 	} else {
    210 		if (idle && tp->t_idle >= tp->t_rxtcur) {
    211 			/*
    212 			 * We have been idle for "a while" and no acks are
    213 			 * expected to clock out any data we send --
    214 			 * slow start to get ack "clock" running again.
    215 			 */
    216 			tp->snd_cwnd = min(tp->snd_cwnd,
    217 			    TCP_INITIAL_WINDOW(tcp_init_win, txsegsize));
    218 		}
    219 	}
    220 
    221 again:
    222 	/*
    223 	 * Determine length of data that should be transmitted, and
    224 	 * flags that should be used.  If there is some data or critical
    225 	 * controls (SYN, RST) to send, then transmit; otherwise,
    226 	 * investigate further.
    227 	 */
    228 	sendalot = 0;
    229 	off = tp->snd_nxt - tp->snd_una;
    230 	win = min(tp->snd_wnd, tp->snd_cwnd);
    231 
    232 	flags = tcp_outflags[tp->t_state];
    233 	/*
    234 	 * If in persist timeout with window of 0, send 1 byte.
    235 	 * Otherwise, if window is small but nonzero
    236 	 * and timer expired, we will send what we can
    237 	 * and go to transmit state.
    238 	 */
    239 	if (tp->t_force) {
    240 		if (win == 0) {
    241 			/*
    242 			 * If we still have some data to send, then
    243 			 * clear the FIN bit.  Usually this would
    244 			 * happen below when it realizes that we
    245 			 * aren't sending all the data.  However,
    246 			 * if we have exactly 1 byte of unset data,
    247 			 * then it won't clear the FIN bit below,
    248 			 * and if we are in persist state, we wind
    249 			 * up sending the packet without recording
    250 			 * that we sent the FIN bit.
    251 			 *
    252 			 * We can't just blindly clear the FIN bit,
    253 			 * because if we don't have any more data
    254 			 * to send then the probe will be the FIN
    255 			 * itself.
    256 			 */
    257 			if (off < so->so_snd.sb_cc)
    258 				flags &= ~TH_FIN;
    259 			win = 1;
    260 		} else {
    261 			TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    262 			tp->t_rxtshift = 0;
    263 		}
    264 	}
    265 
    266 	if (win < so->so_snd.sb_cc) {
    267 		len = win - off;
    268 		flags &= ~TH_FIN;
    269 	} else
    270 		len = so->so_snd.sb_cc - off;
    271 
    272 	if (len < 0) {
    273 		/*
    274 		 * If FIN has been sent but not acked,
    275 		 * but we haven't been called to retransmit,
    276 		 * len will be -1.  Otherwise, window shrank
    277 		 * after we sent into it.  If window shrank to 0,
    278 		 * cancel pending retransmit, pull snd_nxt back
    279 		 * to (closed) window, and set the persist timer
    280 		 * if it isn't already going.  If the window didn't
    281 		 * close completely, just wait for an ACK.
    282 		 *
    283 		 * If we have a pending FIN, either it has already been
    284 		 * transmitted or it is outside the window, so drop it.
    285 		 * If the FIN has been transmitted, but this is not a
    286 		 * retransmission, then len must be -1.  Therefore we also
    287 		 * prevent here the sending of `gratuitous FINs'.  This
    288 		 * eliminates the need to check for that case below (e.g.
    289 		 * to back up snd_nxt before the FIN so that the sequence
    290 		 * number is correct).
    291 		 */
    292 		len = 0;
    293 		flags &= ~TH_FIN;
    294 		if (win == 0) {
    295 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
    296 			tp->t_rxtshift = 0;
    297 			tp->snd_nxt = tp->snd_una;
    298 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
    299 				tcp_setpersist(tp);
    300 		}
    301 	}
    302 	if (len > txsegsize) {
    303 		len = txsegsize;
    304 		flags &= ~TH_FIN;
    305 		sendalot = 1;
    306 	}
    307 
    308 	win = sbspace(&so->so_rcv);
    309 
    310 	/*
    311 	 * Sender silly window avoidance.  If connection is idle
    312 	 * and can send all data, a maximum segment,
    313 	 * at least a maximum default-size segment do it,
    314 	 * or are forced, do it; otherwise don't bother.
    315 	 * If peer's buffer is tiny, then send
    316 	 * when window is at least half open.
    317 	 * If retransmitting (possibly after persist timer forced us
    318 	 * to send into a small window), then must resend.
    319 	 */
    320 	if (len) {
    321 		if (len == txsegsize)
    322 			goto send;
    323 		if ((idle || tp->t_flags & TF_NODELAY) &&
    324 		    len + off >= so->so_snd.sb_cc)
    325 			goto send;
    326 		if (tp->t_force)
    327 			goto send;
    328 		if (len >= tp->max_sndwnd / 2)
    329 			goto send;
    330 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
    331 			goto send;
    332 	}
    333 
    334 	/*
    335 	 * Compare available window to amount of window known to peer
    336 	 * (as advertised window less next expected input).  If the
    337 	 * difference is at least twice the size of the largest segment
    338 	 * we expect to receive (i.e. two segments) or at least 50% of
    339 	 * the maximum possible window, then want to send a window update
    340 	 * to peer.
    341 	 */
    342 	if (win > 0) {
    343 		/*
    344 		 * "adv" is the amount we can increase the window,
    345 		 * taking into account that we are limited by
    346 		 * TCP_MAXWIN << tp->rcv_scale.
    347 		 */
    348 		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
    349 			(tp->rcv_adv - tp->rcv_nxt);
    350 
    351 		if (adv >= (long) (2 * rxsegsize))
    352 			goto send;
    353 		if (2 * adv >= (long) so->so_rcv.sb_hiwat)
    354 			goto send;
    355 	}
    356 
    357 	/*
    358 	 * Send if we owe peer an ACK.
    359 	 */
    360 	if (tp->t_flags & TF_ACKNOW)
    361 		goto send;
    362 	if (flags & (TH_SYN|TH_FIN|TH_RST))
    363 		goto send;
    364 	if (SEQ_GT(tp->snd_up, tp->snd_una))
    365 		goto send;
    366 
    367 	/*
    368 	 * TCP window updates are not reliable, rather a polling protocol
    369 	 * using ``persist'' packets is used to insure receipt of window
    370 	 * updates.  The three ``states'' for the output side are:
    371 	 *	idle			not doing retransmits or persists
    372 	 *	persisting		to move a small or zero window
    373 	 *	(re)transmitting	and thereby not persisting
    374 	 *
    375 	 * tp->t_timer[TCPT_PERSIST]
    376 	 *	is set when we are in persist state.
    377 	 * tp->t_force
    378 	 *	is set when we are called to send a persist packet.
    379 	 * tp->t_timer[TCPT_REXMT]
    380 	 *	is set when we are retransmitting
    381 	 * The output side is idle when both timers are zero.
    382 	 *
    383 	 * If send window is too small, there is data to transmit, and no
    384 	 * retransmit or persist is pending, then go to persist state.
    385 	 * If nothing happens soon, send when timer expires:
    386 	 * if window is nonzero, transmit what we can,
    387 	 * otherwise force out a byte.
    388 	 */
    389 	if (so->so_snd.sb_cc && TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    390 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    391 		tp->t_rxtshift = 0;
    392 		tcp_setpersist(tp);
    393 	}
    394 
    395 	/*
    396 	 * No reason to send a segment, just return.
    397 	 */
    398 	return (0);
    399 
    400 send:
    401 	/*
    402 	 * Before ESTABLISHED, force sending of initial options
    403 	 * unless TCP set not to do any options.
    404 	 * NOTE: we assume that the IP/TCP header plus TCP options
    405 	 * always fit in a single mbuf, leaving room for a maximum
    406 	 * link header, i.e.
    407 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN
    408 	 */
    409 	optlen = 0;
    410 	hdrlen = sizeof (struct tcpiphdr);
    411 	if (flags & TH_SYN) {
    412 		struct rtentry *rt = in_pcbrtentry(tp->t_inpcb);
    413 
    414 		tp->snd_nxt = tp->iss;
    415 		tp->t_ourmss = tcp_mss_to_advertise(rt != NULL ?
    416 						    rt->rt_ifp : NULL);
    417 		if ((tp->t_flags & TF_NOOPT) == 0) {
    418 			opt[0] = TCPOPT_MAXSEG;
    419 			opt[1] = 4;
    420 			opt[2] = (tp->t_ourmss >> 8) & 0xff;
    421 			opt[3] = tp->t_ourmss & 0xff;
    422 			optlen = 4;
    423 
    424 			if ((tp->t_flags & TF_REQ_SCALE) &&
    425 			    ((flags & TH_ACK) == 0 ||
    426 			    (tp->t_flags & TF_RCVD_SCALE))) {
    427 				*((u_int32_t *) (opt + optlen)) = htonl(
    428 					TCPOPT_NOP << 24 |
    429 					TCPOPT_WINDOW << 16 |
    430 					TCPOLEN_WINDOW << 8 |
    431 					tp->request_r_scale);
    432 				optlen += 4;
    433 			}
    434 		}
    435  	}
    436 
    437  	/*
    438 	 * Send a timestamp and echo-reply if this is a SYN and our side
    439 	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
    440 	 * and our peer have sent timestamps in our SYN's.
    441  	 */
    442  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
    443  	     (flags & TH_RST) == 0 &&
    444  	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
    445 	     (tp->t_flags & TF_RCVD_TSTMP))) {
    446 		u_int32_t *lp = (u_int32_t *)(opt + optlen);
    447 
    448  		/* Form timestamp option as shown in appendix A of RFC 1323. */
    449  		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
    450  		*lp++ = htonl(tcp_now);
    451  		*lp   = htonl(tp->ts_recent);
    452  		optlen += TCPOLEN_TSTAMP_APPA;
    453  	}
    454 
    455  	hdrlen += optlen;
    456 
    457 #ifdef DIAGNOSTIC
    458 	if (len > txsegsize)
    459 		panic("tcp data to be sent is larger than segment");
    460  	if (max_linkhdr + hdrlen > MHLEN)
    461 		panic("tcphdr too big");
    462 #endif
    463 
    464 	/*
    465 	 * Grab a header mbuf, attaching a copy of data to
    466 	 * be transmitted, and initialize the header from
    467 	 * the template for sends on this connection.
    468 	 */
    469 	if (len) {
    470 		if (tp->t_force && len == 1)
    471 			tcpstat.tcps_sndprobe++;
    472 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
    473 			tcpstat.tcps_sndrexmitpack++;
    474 			tcpstat.tcps_sndrexmitbyte += len;
    475 		} else {
    476 			tcpstat.tcps_sndpack++;
    477 			tcpstat.tcps_sndbyte += len;
    478 		}
    479 #ifdef notyet
    480 		if ((m = m_copypack(so->so_snd.sb_mb, off,
    481 		    (int)len, max_linkhdr + hdrlen)) == 0) {
    482 			error = ENOBUFS;
    483 			goto out;
    484 		}
    485 		/*
    486 		 * m_copypack left space for our hdr; use it.
    487 		 */
    488 		m->m_len += hdrlen;
    489 		m->m_data -= hdrlen;
    490 #else
    491 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    492 		if (m == NULL) {
    493 			error = ENOBUFS;
    494 			goto out;
    495 		}
    496 		m->m_data += max_linkhdr;
    497 		m->m_len = hdrlen;
    498 		if (len <= MHLEN - hdrlen - max_linkhdr) {
    499 			m_copydata(so->so_snd.sb_mb, off, (int) len,
    500 			    mtod(m, caddr_t) + hdrlen);
    501 			m->m_len += len;
    502 		} else {
    503 			m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
    504 			if (m->m_next == 0) {
    505 				m_freem(m);
    506 				error = ENOBUFS;
    507 				goto out;
    508 			}
    509 		}
    510 #endif
    511 		/*
    512 		 * If we're sending everything we've got, set PUSH.
    513 		 * (This will keep happy those implementations which only
    514 		 * give data to the user when a buffer fills or
    515 		 * a PUSH comes in.)
    516 		 */
    517 		if (off + len == so->so_snd.sb_cc)
    518 			flags |= TH_PUSH;
    519 	} else {
    520 		if (tp->t_flags & TF_ACKNOW)
    521 			tcpstat.tcps_sndacks++;
    522 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
    523 			tcpstat.tcps_sndctrl++;
    524 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
    525 			tcpstat.tcps_sndurg++;
    526 		else
    527 			tcpstat.tcps_sndwinup++;
    528 
    529 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    530 		if (m == NULL) {
    531 			error = ENOBUFS;
    532 			goto out;
    533 		}
    534 		m->m_data += max_linkhdr;
    535 		m->m_len = hdrlen;
    536 	}
    537 	m->m_pkthdr.rcvif = (struct ifnet *)0;
    538 	ti = mtod(m, struct tcpiphdr *);
    539 	if (tp->t_template == 0)
    540 		panic("tcp_output");
    541 	bcopy((caddr_t)tp->t_template, (caddr_t)ti, sizeof (struct tcpiphdr));
    542 
    543 	/*
    544 	 * If we are doing retransmissions, then snd_nxt will
    545 	 * not reflect the first unsent octet.  For ACK only
    546 	 * packets, we do not want the sequence number of the
    547 	 * retransmitted packet, we want the sequence number
    548 	 * of the next unsent octet.  So, if there is no data
    549 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
    550 	 * when filling in ti_seq.  But if we are in persist
    551 	 * state, snd_max might reflect one byte beyond the
    552 	 * right edge of the window, so use snd_nxt in that
    553 	 * case, since we know we aren't doing a retransmission.
    554 	 * (retransmit and persist are mutually exclusive...)
    555 	 */
    556 	if (len || (flags & (TH_SYN|TH_FIN)) ||
    557 	    TCP_TIMER_ISARMED(tp, TCPT_PERSIST))
    558 		ti->ti_seq = htonl(tp->snd_nxt);
    559 	else
    560 		ti->ti_seq = htonl(tp->snd_max);
    561 	ti->ti_ack = htonl(tp->rcv_nxt);
    562 	if (optlen) {
    563 		bcopy((caddr_t)opt, (caddr_t)(ti + 1), optlen);
    564 		ti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;
    565 	}
    566 	ti->ti_flags = flags;
    567 	/*
    568 	 * Calculate receive window.  Don't shrink window,
    569 	 * but avoid silly window syndrome.
    570 	 */
    571 	if (win < (long)(so->so_rcv.sb_hiwat / 4) && win < (long)rxsegsize)
    572 		win = 0;
    573 	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
    574 		win = (long)TCP_MAXWIN << tp->rcv_scale;
    575 	if (win < (long)(tp->rcv_adv - tp->rcv_nxt))
    576 		win = (long)(tp->rcv_adv - tp->rcv_nxt);
    577 	ti->ti_win = htons((u_int16_t) (win>>tp->rcv_scale));
    578 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
    579 		u_int32_t urp = tp->snd_up - tp->snd_nxt;
    580 		if (urp > IP_MAXPACKET)
    581 			urp = IP_MAXPACKET;
    582 		ti->ti_urp = htons((u_int16_t)urp);
    583 		ti->ti_flags |= TH_URG;
    584 	} else
    585 		/*
    586 		 * If no urgent pointer to send, then we pull
    587 		 * the urgent pointer to the left edge of the send window
    588 		 * so that it doesn't drift into the send window on sequence
    589 		 * number wraparound.
    590 		 */
    591 		tp->snd_up = tp->snd_una;		/* drag it along */
    592 
    593 	/*
    594 	 * Put TCP length in extended header, and then
    595 	 * checksum extended header and data.
    596 	 */
    597 	if (len + optlen)
    598 		ti->ti_len = htons((u_int16_t)(sizeof (struct tcphdr) +
    599 		    optlen + len));
    600 	ti->ti_sum = in_cksum(m, (int)(hdrlen + len));
    601 
    602 	/*
    603 	 * In transmit state, time the transmission and arrange for
    604 	 * the retransmit.  In persist state, just set snd_max.
    605 	 */
    606 	if (tp->t_force == 0 || TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0) {
    607 		tcp_seq startseq = tp->snd_nxt;
    608 
    609 		/*
    610 		 * Advance snd_nxt over sequence space of this segment.
    611 		 * There are no states in which we send both a SYN and a FIN,
    612 		 * so we collapse the tests for these flags.
    613 		 */
    614 		if (flags & (TH_SYN|TH_FIN))
    615 			tp->snd_nxt++;
    616 		tp->snd_nxt += len;
    617 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
    618 			tp->snd_max = tp->snd_nxt;
    619 			/*
    620 			 * Time this transmission if not a retransmission and
    621 			 * not currently timing anything.
    622 			 */
    623 			if (tp->t_rtt == 0) {
    624 				tp->t_rtt = 1;
    625 				tp->t_rtseq = startseq;
    626 				tcpstat.tcps_segstimed++;
    627 			}
    628 		}
    629 
    630 		/*
    631 		 * Set retransmit timer if not currently set,
    632 		 * and not doing an ack or a keep-alive probe.
    633 		 * Initial value for retransmit timer is smoothed
    634 		 * round-trip time + 2 * round-trip time variance.
    635 		 * Initialize shift counter which is used for backoff
    636 		 * of retransmit time.
    637 		 */
    638 		if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 &&
    639 		    tp->snd_nxt != tp->snd_una) {
    640 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
    641 			if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST)) {
    642 				TCP_TIMER_DISARM(tp, TCPT_PERSIST);
    643 				tp->t_rxtshift = 0;
    644 			}
    645 		}
    646 	} else
    647 		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
    648 			tp->snd_max = tp->snd_nxt + len;
    649 
    650 	/*
    651 	 * Trace.
    652 	 */
    653 	if (so->so_options & SO_DEBUG)
    654 		tcp_trace(TA_OUTPUT, tp->t_state, tp, ti, 0);
    655 
    656 	/*
    657 	 * Fill in IP length and desired time to live and
    658 	 * send to IP level.  There should be a better way
    659 	 * to handle ttl and tos; we could keep them in
    660 	 * the template, but need a way to checksum without them.
    661 	 */
    662 	m->m_pkthdr.len = hdrlen + len;
    663     {
    664 	struct rtentry *rt;
    665 
    666 	((struct ip *)ti)->ip_len = m->m_pkthdr.len;
    667 	((struct ip *)ti)->ip_ttl = tp->t_inpcb->inp_ip.ip_ttl;	/* XXX */
    668 	((struct ip *)ti)->ip_tos = tp->t_inpcb->inp_ip.ip_tos;	/* XXX */
    669 
    670 	if (ip_mtudisc && (rt = in_pcbrtentry(tp->t_inpcb)) != 0 &&
    671 	    (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    672 		((struct ip *)ti)->ip_off |= IP_DF;
    673 
    674 #if BSD >= 43
    675 	error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
    676 	    so->so_options & SO_DONTROUTE, 0);
    677 #else
    678 	error = ip_output(m, (struct mbuf *)0, &tp->t_inpcb->inp_route,
    679 	    so->so_options & SO_DONTROUTE);
    680 #endif
    681     }
    682 	if (error) {
    683 out:
    684 		if (error == ENOBUFS) {
    685 			tcp_quench(tp->t_inpcb, 0);
    686 			return (0);
    687 		}
    688 		if ((error == EHOSTUNREACH || error == ENETDOWN)
    689 		    && TCPS_HAVERCVDSYN(tp->t_state)) {
    690 			tp->t_softerror = error;
    691 			return (0);
    692 		}
    693 		return (error);
    694 	}
    695 	tcpstat.tcps_sndtotal++;
    696 	if (tp->t_flags & TF_DELACK)
    697 		tcpstat.tcps_delack++;
    698 
    699 	/*
    700 	 * Data sent (as far as we can tell).
    701 	 * If this advertises a larger window than any other segment,
    702 	 * then remember the size of the advertised window.
    703 	 * Any pending ACK has now been sent.
    704 	 */
    705 	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
    706 		tp->rcv_adv = tp->rcv_nxt + win;
    707 	tp->last_ack_sent = tp->rcv_nxt;
    708 	tp->t_flags &= ~TF_ACKNOW;
    709 	TCP_CLEAR_DELACK(tp);
    710 	if (sendalot)
    711 		goto again;
    712 	return (0);
    713 }
    714 
    715 void
    716 tcp_setpersist(tp)
    717 	register struct tcpcb *tp;
    718 {
    719 	register int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2);
    720 	int nticks;
    721 
    722 	if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
    723 		panic("tcp_output REXMT");
    724 	/*
    725 	 * Start/restart persistance timer.
    726 	 */
    727 	if (t < tp->t_rttmin)
    728 		t = tp->t_rttmin;
    729 	TCPT_RANGESET(nticks, t * tcp_backoff[tp->t_rxtshift],
    730 	    TCPTV_PERSMIN, TCPTV_PERSMAX);
    731 	TCP_TIMER_ARM(tp, TCPT_PERSIST, nticks);
    732 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
    733 		tp->t_rxtshift++;
    734 }
    735