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