xref: /dflybsd-src/sys/netinet/tcp_input.c (revision bc49aa1be5400e3bdd801519c6936e8947d5d432)
1 /*
2  * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2002, 2003, 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
36  *
37  * License terms: all terms for the DragonFly license above plus the following:
38  *
39  * 4. All advertising materials mentioning features or use of this software
40  *    must display the following acknowledgement:
41  *
42  *	This product includes software developed by Jeffrey M. Hsu
43  *	for the DragonFly Project.
44  *
45  *    This requirement may be waived with permission from Jeffrey Hsu.
46  *    This requirement will sunset and may be removed on July 8 2005,
47  *    after which the standard DragonFly license (as shown above) will
48  *    apply.
49  */
50 
51 /*
52  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
53  *	The Regents of the University of California.  All rights reserved.
54  *
55  * Redistribution and use in source and binary forms, with or without
56  * modification, are permitted provided that the following conditions
57  * are met:
58  * 1. Redistributions of source code must retain the above copyright
59  *    notice, this list of conditions and the following disclaimer.
60  * 2. Redistributions in binary form must reproduce the above copyright
61  *    notice, this list of conditions and the following disclaimer in the
62  *    documentation and/or other materials provided with the distribution.
63  * 3. All advertising materials mentioning features or use of this software
64  *    must display the following acknowledgement:
65  *	This product includes software developed by the University of
66  *	California, Berkeley and its contributors.
67  * 4. Neither the name of the University nor the names of its contributors
68  *    may be used to endorse or promote products derived from this software
69  *    without specific prior written permission.
70  *
71  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
81  * SUCH DAMAGE.
82  *
83  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
84  * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
85  * $DragonFly: src/sys/netinet/tcp_input.c,v 1.31 2004/07/17 20:31:31 hsu Exp $
86  */
87 
88 #include "opt_ipfw.h"		/* for ipfw_fwd		*/
89 #include "opt_inet6.h"
90 #include "opt_ipsec.h"
91 #include "opt_tcpdebug.h"
92 #include "opt_tcp_input.h"
93 
94 #include <sys/param.h>
95 #include <sys/systm.h>
96 #include <sys/kernel.h>
97 #include <sys/sysctl.h>
98 #include <sys/malloc.h>
99 #include <sys/mbuf.h>
100 #include <sys/proc.h>		/* for proc0 declaration */
101 #include <sys/protosw.h>
102 #include <sys/socket.h>
103 #include <sys/socketvar.h>
104 #include <sys/syslog.h>
105 #include <sys/in_cksum.h>
106 
107 #include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
108 #include <machine/stdarg.h>
109 
110 #include <net/if.h>
111 #include <net/route.h>
112 
113 #include <netinet/in.h>
114 #include <netinet/in_systm.h>
115 #include <netinet/ip.h>
116 #include <netinet/ip_icmp.h>	/* for ICMP_BANDLIM */
117 #include <netinet/in_var.h>
118 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
119 #include <netinet/in_pcb.h>
120 #include <netinet/ip_var.h>
121 #include <netinet/ip6.h>
122 #include <netinet/icmp6.h>
123 #include <netinet6/nd6.h>
124 #include <netinet6/ip6_var.h>
125 #include <netinet6/in6_pcb.h>
126 #include <netinet/tcp.h>
127 #include <netinet/tcp_fsm.h>
128 #include <netinet/tcp_seq.h>
129 #include <netinet/tcp_timer.h>
130 #include <netinet/tcp_var.h>
131 #include <netinet6/tcp6_var.h>
132 #include <netinet/tcpip.h>
133 
134 #ifdef TCPDEBUG
135 #include <netinet/tcp_debug.h>
136 
137 u_char tcp_saveipgen[40];    /* the size must be of max ip header, now IPv6 */
138 struct tcphdr tcp_savetcp;
139 #endif
140 
141 #ifdef FAST_IPSEC
142 #include <netipsec/ipsec.h>
143 #include <netipsec/ipsec6.h>
144 #endif
145 
146 #ifdef IPSEC
147 #include <netinet6/ipsec.h>
148 #include <netinet6/ipsec6.h>
149 #include <netproto/key/key.h>
150 #endif
151 
152 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
153 
154 static const int tcprexmtthresh = 3;
155 tcp_cc	tcp_ccgen;
156 static int log_in_vain = 0;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
158     &log_in_vain, 0, "Log all incoming TCP connections");
159 
160 static int blackhole = 0;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
162     &blackhole, 0, "Do not send RST when dropping refused connections");
163 
164 int tcp_delack_enabled = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
166     &tcp_delack_enabled, 0,
167     "Delay ACK to try and piggyback it onto a data packet");
168 
169 #ifdef TCP_DROP_SYNFIN
170 static int drop_synfin = 0;
171 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
172     &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
173 #endif
174 
175 static int tcp_do_limitedtransmit = 1;
176 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
177     &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
178 
179 static int tcp_do_early_retransmit = 0;
180 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
181     &tcp_do_early_retransmit, 0, "Early retransmit");
182 
183 static int tcp_do_rfc3390 = 1;
184 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
185     &tcp_do_rfc3390, 0,
186     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
187 
188 static int tcp_do_eifel_detect = 1;
189 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
190     &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
191 
192 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
193     "TCP Segment Reassembly Queue");
194 
195 int tcp_reass_maxseg = 0;
196 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
197     &tcp_reass_maxseg, 0,
198     "Global maximum number of TCP Segments in Reassembly Queue");
199 
200 int tcp_reass_qsize = 0;
201 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
202     &tcp_reass_qsize, 0,
203     "Global number of TCP Segments currently in Reassembly Queue");
204 
205 static int tcp_reass_overflows = 0;
206 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
207     &tcp_reass_overflows, 0,
208     "Global number of TCP Segment Reassembly Queue Overflows");
209 
210 struct inpcbinfo tcbinfo[MAXCPU];
211 
212 static void	 tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
213 static void	 tcp_pulloutofband(struct socket *,
214 		     struct tcphdr *, struct mbuf *, int);
215 static int	 tcp_reass(struct tcpcb *, struct tcphdr *, int *,
216 		     struct mbuf *);
217 static void	 tcp_xmit_timer(struct tcpcb *, int);
218 static void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
219 
220 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
221 #ifdef INET6
222 #define ND6_HINT(tp) \
223 do { \
224 	if ((tp) && (tp)->t_inpcb && \
225 	    ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
226 	    (tp)->t_inpcb->in6p_route.ro_rt) \
227 		nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
228 } while (0)
229 #else
230 #define ND6_HINT(tp)
231 #endif
232 
233 /*
234  * Indicate whether this ack should be delayed.  We can delay the ack if
235  *	- delayed acks are enabled and
236  *	- there is no delayed ack timer in progress and
237  *	- our last ack wasn't a 0-sized window.  We never want to delay
238  *	  the ack that opens up a 0-sized window.
239  */
240 #define DELAY_ACK(tp) \
241 	(tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
242 	(tp->t_flags & TF_RXWIN0SENT) == 0)
243 
244 static int
245 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
246 {
247 	struct tseg_qent *q;
248 	struct tseg_qent *p = NULL;
249 	struct tseg_qent *nq;
250 	struct tseg_qent *te;
251 	struct socket *so = tp->t_inpcb->inp_socket;
252 	int flags;
253 
254 	/*
255 	 * Call with th==0 after become established to
256 	 * force pre-ESTABLISHED data up to user socket.
257 	 */
258 	if (th == 0)
259 		goto present;
260 
261 	/*
262 	 * Limit the number of segments in the reassembly queue to prevent
263 	 * holding on to too many segments (and thus running out of mbufs).
264 	 * Make sure to let the missing segment through which caused this
265 	 * queue.  Always keep one global queue entry spare to be able to
266 	 * process the missing segment.
267 	 */
268 	if (th->th_seq != tp->rcv_nxt &&
269 	    tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
270 		tcp_reass_overflows++;
271 		tcpstat.tcps_rcvmemdrop++;
272 		m_freem(m);
273 		return (0);
274 	}
275 
276 	/* Allocate a new queue entry. */
277 	MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
278 	       M_INTWAIT | M_NULLOK);
279 	if (te == NULL) {
280 		tcpstat.tcps_rcvmemdrop++;
281 		m_freem(m);
282 		return (0);
283 	}
284 	tcp_reass_qsize++;
285 
286 	/*
287 	 * Find a segment which begins after this one does.
288 	 */
289 	LIST_FOREACH(q, &tp->t_segq, tqe_q) {
290 		if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
291 			break;
292 		p = q;
293 	}
294 
295 	/*
296 	 * If there is a preceding segment, it may provide some of
297 	 * our data already.  If so, drop the data from the incoming
298 	 * segment.  If it provides all of our data, drop us.
299 	 */
300 	if (p != NULL) {
301 		int i;
302 		/* conversion to int (in i) handles seq wraparound */
303 		i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
304 		if (i > 0) {
305 			if (i >= *tlenp) {
306 				tcpstat.tcps_rcvduppack++;
307 				tcpstat.tcps_rcvdupbyte += *tlenp;
308 				m_freem(m);
309 				free(te, M_TSEGQ);
310 				tcp_reass_qsize--;
311 				/*
312 				 * Try to present any queued data
313 				 * at the left window edge to the user.
314 				 * This is needed after the 3-WHS
315 				 * completes.
316 				 */
317 				goto present;	/* ??? */
318 			}
319 			m_adj(m, i);
320 			*tlenp -= i;
321 			th->th_seq += i;
322 		}
323 	}
324 	tcpstat.tcps_rcvoopack++;
325 	tcpstat.tcps_rcvoobyte += *tlenp;
326 
327 	/*
328 	 * While we overlap succeeding segments trim them or,
329 	 * if they are completely covered, dequeue them.
330 	 */
331 	while (q) {
332 		int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
333 		if (i <= 0)
334 			break;
335 		if (i < q->tqe_len) {
336 			q->tqe_th->th_seq += i;
337 			q->tqe_len -= i;
338 			m_adj(q->tqe_m, i);
339 			break;
340 		}
341 
342 		nq = LIST_NEXT(q, tqe_q);
343 		LIST_REMOVE(q, tqe_q);
344 		m_freem(q->tqe_m);
345 		free(q, M_TSEGQ);
346 		tcp_reass_qsize--;
347 		q = nq;
348 	}
349 
350 	/* Insert the new segment queue entry into place. */
351 	te->tqe_m = m;
352 	te->tqe_th = th;
353 	te->tqe_len = *tlenp;
354 
355 	if (p == NULL) {
356 		LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
357 	} else {
358 		LIST_INSERT_AFTER(p, te, tqe_q);
359 	}
360 
361 present:
362 	/*
363 	 * Present data to user, advancing rcv_nxt through
364 	 * completed sequence space.
365 	 */
366 	if (!TCPS_HAVEESTABLISHED(tp->t_state))
367 		return (0);
368 	q = LIST_FIRST(&tp->t_segq);
369 	if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
370 		return (0);
371 	do {
372 		tp->rcv_nxt += q->tqe_len;
373 		flags = q->tqe_th->th_flags & TH_FIN;
374 		nq = LIST_NEXT(q, tqe_q);
375 		LIST_REMOVE(q, tqe_q);
376 		if (so->so_state & SS_CANTRCVMORE)
377 			m_freem(q->tqe_m);
378 		else
379 			sbappend(&so->so_rcv, q->tqe_m);
380 		free(q, M_TSEGQ);
381 		tcp_reass_qsize--;
382 		q = nq;
383 	} while (q && q->tqe_th->th_seq == tp->rcv_nxt);
384 	ND6_HINT(tp);
385 	sorwakeup(so);
386 	return (flags);
387 }
388 
389 /*
390  * TCP input routine, follows pages 65-76 of the
391  * protocol specification dated September, 1981 very closely.
392  */
393 #ifdef INET6
394 int
395 tcp6_input(struct mbuf **mp, int *offp, int proto)
396 {
397 	struct mbuf *m = *mp;
398 	struct in6_ifaddr *ia6;
399 
400 	IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
401 
402 	/*
403 	 * draft-itojun-ipv6-tcp-to-anycast
404 	 * better place to put this in?
405 	 */
406 	ia6 = ip6_getdstifaddr(m);
407 	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
408 		struct ip6_hdr *ip6;
409 
410 		ip6 = mtod(m, struct ip6_hdr *);
411 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
412 			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
413 		return (IPPROTO_DONE);
414 	}
415 
416 	tcp_input(m, *offp, proto);
417 	return (IPPROTO_DONE);
418 }
419 #endif
420 
421 void
422 tcp_input(struct mbuf *m, ...)
423 {
424 	__va_list ap;
425 	int off0, proto;
426 	struct tcphdr *th;
427 	struct ip *ip = NULL;
428 	struct ipovly *ipov;
429 	struct inpcb *inp = NULL;
430 	u_char *optp = NULL;
431 	int optlen = 0;
432 	int len, tlen, off;
433 	int drop_hdrlen;
434 	struct tcpcb *tp = NULL;
435 	int thflags;
436 	struct socket *so = 0;
437 	int todrop, acked, ourfinisacked, needoutput = 0;
438 	u_long tiwin;
439 	struct tcpopt to;		/* options in this segment */
440 	struct rmxp_tao *taop;		/* pointer to our TAO cache entry */
441 	struct rmxp_tao	tao_noncached;	/* in case there's no cached entry */
442 	struct sockaddr_in *next_hop = NULL;
443 	int rstreason; /* For badport_bandlim accounting purposes */
444 	int cpu;
445 	struct ip6_hdr *ip6 = NULL;
446 #ifdef INET6
447 	boolean_t isipv6;
448 #else
449 	const boolean_t isipv6 = FALSE;
450 #endif
451 #ifdef TCPDEBUG
452 	short ostate = 0;
453 #endif
454 
455 	__va_start(ap, m);
456 	off0 = __va_arg(ap, int);
457 	proto = __va_arg(ap, int);
458 	__va_end(ap);
459 
460 	tcpstat.tcps_rcvtotal++;
461 
462 	/* Grab info from and strip MT_TAG mbufs prepended to the chain. */
463 	while  (m->m_type == MT_TAG) {
464 		if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
465 			next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
466 		m = m->m_next;
467 	}
468 
469 #ifdef INET6
470 	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
471 #endif
472 
473 	if (isipv6) {
474 		/* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
475 		ip6 = mtod(m, struct ip6_hdr *);
476 		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
477 		if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
478 			tcpstat.tcps_rcvbadsum++;
479 			goto drop;
480 		}
481 		th = (struct tcphdr *)((caddr_t)ip6 + off0);
482 
483 		/*
484 		 * Be proactive about unspecified IPv6 address in source.
485 		 * As we use all-zero to indicate unbounded/unconnected pcb,
486 		 * unspecified IPv6 address can be used to confuse us.
487 		 *
488 		 * Note that packets with unspecified IPv6 destination is
489 		 * already dropped in ip6_input.
490 		 */
491 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
492 			/* XXX stat */
493 			goto drop;
494 		}
495 	} else {
496 		/*
497 		 * Get IP and TCP header together in first mbuf.
498 		 * Note: IP leaves IP header in first mbuf.
499 		 */
500 		if (off0 > sizeof(struct ip)) {
501 			ip_stripoptions(m);
502 			off0 = sizeof(struct ip);
503 		}
504 		/* already checked and pulled up in ip_demux() */
505 		KASSERT(m->m_len >= sizeof(struct tcpiphdr),
506 		    ("TCP header not in one mbuf"));
507 		ip = mtod(m, struct ip *);
508 		ipov = (struct ipovly *)ip;
509 		th = (struct tcphdr *)((caddr_t)ip + off0);
510 		tlen = ip->ip_len;
511 
512 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
513 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
514 				th->th_sum = m->m_pkthdr.csum_data;
515 			else
516 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
517 						ip->ip_dst.s_addr,
518 						htonl(m->m_pkthdr.csum_data +
519 							ip->ip_len +
520 							IPPROTO_TCP));
521 			th->th_sum ^= 0xffff;
522 		} else {
523 			/*
524 			 * Checksum extended TCP header and data.
525 			 */
526 			len = sizeof(struct ip) + tlen;
527 			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
528 			ipov->ih_len = (u_short)tlen;
529 			ipov->ih_len = htons(ipov->ih_len);
530 			th->th_sum = in_cksum(m, len);
531 		}
532 		if (th->th_sum) {
533 			tcpstat.tcps_rcvbadsum++;
534 			goto drop;
535 		}
536 #ifdef INET6
537 		/* Re-initialization for later version check */
538 		ip->ip_v = IPVERSION;
539 #endif
540 	}
541 
542 	/*
543 	 * Check that TCP offset makes sense,
544 	 * pull out TCP options and adjust length.		XXX
545 	 */
546 	off = th->th_off << 2;
547 	/* already checked and pulled up in ip_demux() */
548 	KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
549 	    ("bad TCP data offset"));
550 	tlen -= off;	/* tlen is used instead of ti->ti_len */
551 	if (off > sizeof(struct tcphdr)) {
552 		if (isipv6) {
553 			IP6_EXTHDR_CHECK(m, off0, off, );
554 			ip6 = mtod(m, struct ip6_hdr *);
555 			th = (struct tcphdr *)((caddr_t)ip6 + off0);
556 		} else {
557 			/* already pulled up in ip_demux() */
558 			KASSERT(m->m_len >= sizeof(struct ip) + off,
559 			    ("TCP header and options not in one mbuf"));
560 		}
561 		optlen = off - sizeof(struct tcphdr);
562 		optp = (u_char *)(th + 1);
563 	}
564 	thflags = th->th_flags;
565 
566 #ifdef TCP_DROP_SYNFIN
567 	/*
568 	 * If the drop_synfin option is enabled, drop all packets with
569 	 * both the SYN and FIN bits set. This prevents e.g. nmap from
570 	 * identifying the TCP/IP stack.
571 	 *
572 	 * This is a violation of the TCP specification.
573 	 */
574 	if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
575 		goto drop;
576 #endif
577 
578 	/*
579 	 * Convert TCP protocol specific fields to host format.
580 	 */
581 	th->th_seq = ntohl(th->th_seq);
582 	th->th_ack = ntohl(th->th_ack);
583 	th->th_win = ntohs(th->th_win);
584 	th->th_urp = ntohs(th->th_urp);
585 
586 	/*
587 	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
588 	 * until after ip6_savecontrol() is called and before other functions
589 	 * which don't want those proto headers.
590 	 * Because ip6_savecontrol() is going to parse the mbuf to
591 	 * search for data to be passed up to user-land, it wants mbuf
592 	 * parameters to be unchanged.
593 	 * XXX: the call of ip6_savecontrol() has been obsoleted based on
594 	 * latest version of the advanced API (20020110).
595 	 */
596 	drop_hdrlen = off0 + off;
597 
598 	/*
599 	 * Locate pcb for segment.
600 	 */
601 findpcb:
602 	/* IPFIREWALL_FORWARD section */
603 	if (next_hop != NULL && !isipv6) {  /* IPv6 support is not there yet */
604 		/*
605 		 * Transparently forwarded. Pretend to be the destination.
606 		 * already got one like this?
607 		 */
608 		cpu = mycpu->gd_cpuid;
609 		inp = in_pcblookup_hash(&tcbinfo[cpu],
610 					ip->ip_src, th->th_sport,
611 					ip->ip_dst, th->th_dport,
612 					0, m->m_pkthdr.rcvif);
613 		if (!inp) {
614 			/*
615 			 * It's new.  Try to find the ambushing socket.
616 			 */
617 
618 			/*
619 			 * The rest of the ipfw code stores the port in
620 			 * host order.  XXX
621 			 * (The IP address is still in network order.)
622 			 */
623 			in_port_t dport = next_hop->sin_port ?
624 						htons(next_hop->sin_port) :
625 						th->th_dport;
626 
627 			cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
628 					  next_hop->sin_addr.s_addr, dport);
629 			inp = in_pcblookup_hash(&tcbinfo[cpu],
630 						ip->ip_src, th->th_sport,
631 						next_hop->sin_addr, dport,
632 						1, m->m_pkthdr.rcvif);
633 		}
634 	} else {
635 		if (isipv6) {
636 			inp = in6_pcblookup_hash(&tcbinfo[0],
637 						 &ip6->ip6_src, th->th_sport,
638 						 &ip6->ip6_dst, th->th_dport,
639 						 1, m->m_pkthdr.rcvif);
640 		} else {
641 			cpu = mycpu->gd_cpuid;
642 			inp = in_pcblookup_hash(&tcbinfo[cpu],
643 						ip->ip_src, th->th_sport,
644 						ip->ip_dst, th->th_dport,
645 						1, m->m_pkthdr.rcvif);
646 		}
647       }
648 
649 #ifdef IPSEC
650 	if (isipv6) {
651 		if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
652 			ipsec6stat.in_polvio++;
653 			goto drop;
654 		}
655 	} else {
656 		if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
657 			ipsecstat.in_polvio++;
658 			goto drop;
659 		}
660 	}
661 #endif
662 #ifdef FAST_IPSEC
663 	if (isipv6) {
664 		if (inp != NULL && ipsec6_in_reject(m, inp)) {
665 			goto drop;
666 		}
667 	} else {
668 		if (inp != NULL && ipsec4_in_reject(m, inp)) {
669 			goto drop;
670 		}
671 	}
672 #endif
673 
674 	/*
675 	 * If the state is CLOSED (i.e., TCB does not exist) then
676 	 * all data in the incoming segment is discarded.
677 	 * If the TCB exists but is in CLOSED state, it is embryonic,
678 	 * but should either do a listen or a connect soon.
679 	 */
680 	if (inp == NULL) {
681 		if (log_in_vain) {
682 #ifdef INET6
683 			char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
684 #else
685 			char dbuf[4 * sizeof "123"], sbuf[4 * sizeof "123"];
686 #endif
687 			if (isipv6) {
688 				strcpy(dbuf, "[");
689 				strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
690 				strcat(dbuf, "]");
691 				strcpy(sbuf, "[");
692 				strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
693 				strcat(sbuf, "]");
694 			} else {
695 				strcpy(dbuf, inet_ntoa(ip->ip_dst));
696 				strcpy(sbuf, inet_ntoa(ip->ip_src));
697 			}
698 			switch (log_in_vain) {
699 			case 1:
700 				if ((thflags & TH_SYN) == 0)
701 					break;
702 			case 2:
703 				log(LOG_INFO,
704 				    "Connection attempt to TCP %s:%d "
705 				    "from %s:%d flags:0x%02x\n",
706 				    dbuf, ntohs(th->th_dport), sbuf,
707 				    ntohs(th->th_sport), thflags);
708 				break;
709 			default:
710 				break;
711 			}
712 		}
713 		if (blackhole) {
714 			switch (blackhole) {
715 			case 1:
716 				if (thflags & TH_SYN)
717 					goto drop;
718 				break;
719 			case 2:
720 				goto drop;
721 			default:
722 				goto drop;
723 			}
724 		}
725 		rstreason = BANDLIM_RST_CLOSEDPORT;
726 		goto dropwithreset;
727 	}
728 	tp = intotcpcb(inp);
729 	if (tp == NULL) {
730 		rstreason = BANDLIM_RST_CLOSEDPORT;
731 		goto dropwithreset;
732 	}
733 	if (tp->t_state == TCPS_CLOSED)
734 		goto drop;
735 
736 	/* Unscale the window into a 32-bit value. */
737 	if (!(thflags & TH_SYN))
738 		tiwin = th->th_win << tp->snd_scale;
739 	else
740 		tiwin = th->th_win;
741 
742 	so = inp->inp_socket;
743 
744 #ifdef TCPDEBUG
745 	if (so->so_options & SO_DEBUG) {
746 		ostate = tp->t_state;
747 		if (isipv6)
748 			bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
749 		else
750 			bcopy(ip, tcp_saveipgen, sizeof(*ip));
751 		tcp_savetcp = *th;
752 	}
753 #endif
754 
755 	bzero(&to, sizeof(to));
756 
757 	if (so->so_options & SO_ACCEPTCONN) {
758 		struct in_conninfo inc;
759 
760 #ifdef INET6
761 		inc.inc_isipv6 = (isipv6 == TRUE);
762 #endif
763 		if (isipv6) {
764 			inc.inc6_faddr = ip6->ip6_src;
765 			inc.inc6_laddr = ip6->ip6_dst;
766 			inc.inc6_route.ro_rt = NULL;		/* XXX */
767 		} else {
768 			inc.inc_faddr = ip->ip_src;
769 			inc.inc_laddr = ip->ip_dst;
770 			inc.inc_route.ro_rt = NULL;		/* XXX */
771 		}
772 		inc.inc_fport = th->th_sport;
773 		inc.inc_lport = th->th_dport;
774 
775 	        /*
776 	         * If the state is LISTEN then ignore segment if it contains
777 		 * a RST.  If the segment contains an ACK then it is bad and
778 		 * send a RST.  If it does not contain a SYN then it is not
779 		 * interesting; drop it.
780 		 *
781 		 * If the state is SYN_RECEIVED (syncache) and seg contains
782 		 * an ACK, but not for our SYN/ACK, send a RST.  If the seg
783 		 * contains a RST, check the sequence number to see if it
784 		 * is a valid reset segment.
785 		 */
786 		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
787 			if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
788 				if (!syncache_expand(&inc, th, &so, m)) {
789 					/*
790 					 * No syncache entry, or ACK was not
791 					 * for our SYN/ACK.  Send a RST.
792 					 */
793 					tcpstat.tcps_badsyn++;
794 					rstreason = BANDLIM_RST_OPENPORT;
795 					goto dropwithreset;
796 				}
797 				if (so == NULL)
798 					/*
799 					 * Could not complete 3-way handshake,
800 					 * connection is being closed down, and
801 					 * syncache will free mbuf.
802 					 */
803 					return;
804 				/*
805 				 * Socket is created in state SYN_RECEIVED.
806 				 * Continue processing segment.
807 				 */
808 				inp = sotoinpcb(so);
809 				tp = intotcpcb(inp);
810 				/*
811 				 * This is what would have happened in
812 				 * tcp_output() when the SYN,ACK was sent.
813 				 */
814 				tp->snd_up = tp->snd_una;
815 				tp->snd_max = tp->snd_nxt = tp->iss + 1;
816 				tp->last_ack_sent = tp->rcv_nxt;
817 /*
818  * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
819  * until the _second_ ACK is received:
820  *    rcv SYN (set wscale opts)	 --> send SYN/ACK, set snd_wnd = window.
821  *    rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
822  *        move to ESTAB, set snd_wnd to tiwin.
823  */
824 				tp->snd_wnd = tiwin;	/* unscaled */
825 				goto after_listen;
826 			}
827 			if (thflags & TH_RST) {
828 				syncache_chkrst(&inc, th);
829 				goto drop;
830 			}
831 			if (thflags & TH_ACK) {
832 				syncache_badack(&inc);
833 				tcpstat.tcps_badsyn++;
834 				rstreason = BANDLIM_RST_OPENPORT;
835 				goto dropwithreset;
836 			}
837 			goto drop;
838 		}
839 
840 		/*
841 		 * Segment's flags are (SYN) or (SYN|FIN).
842 		 */
843 #ifdef INET6
844 		/*
845 		 * If deprecated address is forbidden,
846 		 * we do not accept SYN to deprecated interface
847 		 * address to prevent any new inbound connection from
848 		 * getting established.
849 		 * When we do not accept SYN, we send a TCP RST,
850 		 * with deprecated source address (instead of dropping
851 		 * it).  We compromise it as it is much better for peer
852 		 * to send a RST, and RST will be the final packet
853 		 * for the exchange.
854 		 *
855 		 * If we do not forbid deprecated addresses, we accept
856 		 * the SYN packet.  RFC2462 does not suggest dropping
857 		 * SYN in this case.
858 		 * If we decipher RFC2462 5.5.4, it says like this:
859 		 * 1. use of deprecated addr with existing
860 		 *    communication is okay - "SHOULD continue to be
861 		 *    used"
862 		 * 2. use of it with new communication:
863 		 *   (2a) "SHOULD NOT be used if alternate address
864 		 *        with sufficient scope is available"
865 		 *   (2b) nothing mentioned otherwise.
866 		 * Here we fall into (2b) case as we have no choice in
867 		 * our source address selection - we must obey the peer.
868 		 *
869 		 * The wording in RFC2462 is confusing, and there are
870 		 * multiple description text for deprecated address
871 		 * handling - worse, they are not exactly the same.
872 		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
873 		 */
874 		if (isipv6 && !ip6_use_deprecated) {
875 			struct in6_ifaddr *ia6;
876 
877 			if ((ia6 = ip6_getdstifaddr(m)) &&
878 			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
879 				tp = NULL;
880 				rstreason = BANDLIM_RST_OPENPORT;
881 				goto dropwithreset;
882 			}
883 		}
884 #endif
885 		/*
886 		 * If it is from this socket, drop it, it must be forged.
887 		 * Don't bother responding if the destination was a broadcast.
888 		 */
889 		if (th->th_dport == th->th_sport) {
890 			if (isipv6) {
891 				if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
892 						       &ip6->ip6_src))
893 					goto drop;
894 			} else {
895 				if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
896 					goto drop;
897 			}
898 		}
899 		/*
900 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
901 		 *
902 		 * Note that it is quite possible to receive unicast
903 		 * link-layer packets with a broadcast IP address. Use
904 		 * in_broadcast() to find them.
905 		 */
906 		if (m->m_flags & (M_BCAST|M_MCAST))
907 			goto drop;
908 		if (isipv6) {
909 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
910 			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
911 				goto drop;
912 		} else {
913 			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
914 			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
915 			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
916 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
917 				goto drop;
918 		}
919 		/*
920 		 * SYN appears to be valid; create compressed TCP state
921 		 * for syncache, or perform t/tcp connection.
922 		 */
923 		if (so->so_qlen <= so->so_qlimit) {
924 			tcp_dooptions(&to, optp, optlen, TRUE);
925 			if (!syncache_add(&inc, &to, th, &so, m))
926 				goto drop;
927 			if (so == NULL)
928 				/*
929 				 * Entry added to syncache, mbuf used to
930 				 * send SYN,ACK packet.
931 				 */
932 				return;
933 			/*
934 			 * Segment passed TAO tests.
935 			 */
936 			inp = sotoinpcb(so);
937 			tp = intotcpcb(inp);
938 			tp->snd_wnd = tiwin;
939 			tp->t_starttime = ticks;
940 			tp->t_state = TCPS_ESTABLISHED;
941 
942 			/*
943 			 * If there is a FIN, or if there is data and the
944 			 * connection is local, then delay SYN,ACK(SYN) in
945 			 * the hope of piggy-backing it on a response
946 			 * segment.  Otherwise must send ACK now in case
947 			 * the other side is slow starting.
948 			 */
949 			if (DELAY_ACK(tp) &&
950 			    ((thflags & TH_FIN) ||
951 			     (tlen != 0 &&
952 			      ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
953 			       (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
954 				callout_reset(tp->tt_delack, tcp_delacktime,
955 						tcp_timer_delack, tp);
956 				tp->t_flags |= TF_NEEDSYN;
957 			} else
958 				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
959 
960 			tcpstat.tcps_connects++;
961 			soisconnected(so);
962 			goto trimthenstep6;
963 		}
964 		goto drop;
965 	}
966 after_listen:
967 
968 /* XXX temp debugging */
969 	/* should not happen - syncache should pick up these connections */
970 	if (tp->t_state == TCPS_LISTEN)
971 		panic("tcp_input: TCPS_LISTEN");
972 
973 	/*
974 	 * Segment received on connection.
975 	 * Reset idle time and keep-alive timer.
976 	 */
977 	tp->t_rcvtime = ticks;
978 	if (TCPS_HAVEESTABLISHED(tp->t_state))
979 		callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
980 
981 	/*
982 	 * Process options.
983 	 * XXX this is tradtitional behavior, may need to be cleaned up.
984 	 */
985 	tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
986 	if (thflags & TH_SYN) {
987 		if (to.to_flags & TOF_SCALE) {
988 			tp->t_flags |= TF_RCVD_SCALE;
989 			tp->requested_s_scale = to.to_requested_s_scale;
990 		}
991 		if (to.to_flags & TOF_TS) {
992 			tp->t_flags |= TF_RCVD_TSTMP;
993 			tp->ts_recent = to.to_tsval;
994 			tp->ts_recent_age = ticks;
995 		}
996 		if (to.to_flags & (TOF_CC|TOF_CCNEW))
997 			tp->t_flags |= TF_RCVD_CC;
998 		if (to.to_flags & TOF_MSS)
999 			tcp_mss(tp, to.to_mss);
1000 	}
1001 
1002 	/*
1003 	 * Header prediction: check for the two common cases
1004 	 * of a uni-directional data xfer.  If the packet has
1005 	 * no control flags, is in-sequence, the window didn't
1006 	 * change and we're not retransmitting, it's a
1007 	 * candidate.  If the length is zero and the ack moved
1008 	 * forward, we're the sender side of the xfer.  Just
1009 	 * free the data acked & wake any higher level process
1010 	 * that was blocked waiting for space.  If the length
1011 	 * is non-zero and the ack didn't move, we're the
1012 	 * receiver side.  If we're getting packets in-order
1013 	 * (the reassembly queue is empty), add the data to
1014 	 * the socket buffer and note that we need a delayed ack.
1015 	 * Make sure that the hidden state-flags are also off.
1016 	 * Since we check for TCPS_ESTABLISHED above, it can only
1017 	 * be TH_NEEDSYN.
1018 	 */
1019 	if (tp->t_state == TCPS_ESTABLISHED &&
1020 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1021 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1022 	    ((to.to_flags & TOF_TS) == 0 ||
1023 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1024 	    /*
1025 	     * Using the CC option is compulsory if once started:
1026 	     *   the segment is OK if no T/TCP was negotiated or
1027 	     *   if the segment has a CC option equal to CCrecv
1028 	     */
1029 	    ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
1030 	     ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
1031 	    th->th_seq == tp->rcv_nxt &&
1032 	    tiwin && tiwin == tp->snd_wnd &&
1033 	    tp->snd_nxt == tp->snd_max) {
1034 
1035 		/*
1036 		 * If last ACK falls within this segment's sequence numbers,
1037 		 * record the timestamp.
1038 		 * NOTE that the test is modified according to the latest
1039 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1040 		 */
1041 		if ((to.to_flags & TOF_TS) != 0 &&
1042 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1043 			tp->ts_recent_age = ticks;
1044 			tp->ts_recent = to.to_tsval;
1045 		}
1046 
1047 		if (tlen == 0) {
1048 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1049 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1050 			    tp->snd_cwnd >= tp->snd_wnd &&
1051 			    !IN_FASTRECOVERY(tp)) {
1052 				/*
1053 				 * this is a pure ack for outstanding data.
1054 				 */
1055 				++tcpstat.tcps_predack;
1056 				/*
1057 				 * "bad retransmit" recovery
1058 				 *
1059 				 * If Eifel detection applies, then
1060 				 * it is deterministic, so use it
1061 				 * unconditionally over the old heuristic.
1062 				 * Otherwise, fall back to the old heuristic.
1063 				 */
1064 				if (tcp_do_eifel_detect &&
1065 				    (to.to_flags & TOF_TS) && to.to_tsecr &&
1066 				    (tp->t_flags & TF_FIRSTACCACK)) {
1067 					/* Eifel detection applicable. */
1068 					if (to.to_tsecr < tp->t_rexmtTS) {
1069 						tcp_revert_congestion_state(tp);
1070 						++tcpstat.tcps_eifeldetected;
1071 					}
1072 				} else if (tp->t_rxtshift == 1 &&
1073 					   ticks < tp->t_badrxtwin) {
1074 					tcp_revert_congestion_state(tp);
1075 					++tcpstat.tcps_rttdetected;
1076 				}
1077 				tp->t_flags &= ~(TF_FIRSTACCACK |
1078 						 TF_FASTREXMT | TF_EARLYREXMT);
1079 				/*
1080 				 * Recalculate the retransmit timer / rtt.
1081 				 *
1082 				 * Some machines (certain windows boxes)
1083 				 * send broken timestamp replies during the
1084 				 * SYN+ACK phase, ignore timestamps of 0.
1085 				 */
1086 				if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1087 					tcp_xmit_timer(tp,
1088 						       ticks - to.to_tsecr + 1);
1089 				} else if (tp->t_rtttime &&
1090 					   SEQ_GT(th->th_ack, tp->t_rtseq)) {
1091 					tcp_xmit_timer(tp,
1092 						       ticks - tp->t_rtttime);
1093 				}
1094 				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1095 				acked = th->th_ack - tp->snd_una;
1096 				tcpstat.tcps_rcvackpack++;
1097 				tcpstat.tcps_rcvackbyte += acked;
1098 				sbdrop(&so->so_snd, acked);
1099 				tp->snd_recover = th->th_ack - 1;
1100 				tp->snd_una = th->th_ack;
1101 				tp->t_dupacks = 0;
1102 				m_freem(m);
1103 				ND6_HINT(tp); /* some progress has been done */
1104 
1105 				/*
1106 				 * If all outstanding data are acked, stop
1107 				 * retransmit timer, otherwise restart timer
1108 				 * using current (possibly backed-off) value.
1109 				 * If process is waiting for space,
1110 				 * wakeup/selwakeup/signal.  If data
1111 				 * are ready to send, let tcp_output
1112 				 * decide between more output or persist.
1113 				 */
1114 				if (tp->snd_una == tp->snd_max)
1115 					callout_stop(tp->tt_rexmt);
1116 				else if (!callout_active(tp->tt_persist))
1117 					callout_reset(tp->tt_rexmt,
1118 						      tp->t_rxtcur,
1119 						      tcp_timer_rexmt, tp);
1120 
1121 				sowwakeup(so);
1122 				if (so->so_snd.sb_cc)
1123 					(void) tcp_output(tp);
1124 				return;
1125 			}
1126 		} else if (th->th_ack == tp->snd_una &&
1127 		    LIST_EMPTY(&tp->t_segq) &&
1128 		    tlen <= sbspace(&so->so_rcv)) {
1129 			/*
1130 			 * this is a pure, in-sequence data packet
1131 			 * with nothing on the reassembly queue and
1132 			 * we have enough buffer space to take it.
1133 			 */
1134 			++tcpstat.tcps_preddat;
1135 			tp->rcv_nxt += tlen;
1136 			tcpstat.tcps_rcvpack++;
1137 			tcpstat.tcps_rcvbyte += tlen;
1138 			ND6_HINT(tp);	/* some progress has been done */
1139 			/*
1140 			 * Add data to socket buffer.
1141 			 */
1142 			if (so->so_state & SS_CANTRCVMORE) {
1143 				m_freem(m);
1144 			} else {
1145 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1146 				sbappend(&so->so_rcv, m);
1147 			}
1148 			sorwakeup(so);
1149 			if (DELAY_ACK(tp)) {
1150 	                        callout_reset(tp->tt_delack, tcp_delacktime,
1151 	                            tcp_timer_delack, tp);
1152 			} else {
1153 				tp->t_flags |= TF_ACKNOW;
1154 				tcp_output(tp);
1155 			}
1156 			return;
1157 		}
1158 	}
1159 
1160 	/*
1161 	 * Calculate amount of space in receive window,
1162 	 * and then do TCP input processing.
1163 	 * Receive window is amount of space in rcv queue,
1164 	 * but not less than advertised window.
1165 	 */
1166 	{ int win;
1167 
1168 	win = sbspace(&so->so_rcv);
1169 	if (win < 0)
1170 		win = 0;
1171 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1172 	}
1173 
1174 	switch (tp->t_state) {
1175 
1176 	/*
1177 	 * If the state is SYN_RECEIVED:
1178 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1179 	 */
1180 	case TCPS_SYN_RECEIVED:
1181 		if ((thflags & TH_ACK) &&
1182 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1183 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1184 				rstreason = BANDLIM_RST_OPENPORT;
1185 				goto dropwithreset;
1186 		}
1187 		break;
1188 
1189 	/*
1190 	 * If the state is SYN_SENT:
1191 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1192 	 *	if seg contains a RST, then drop the connection.
1193 	 *	if seg does not contain SYN, then drop it.
1194 	 * Otherwise this is an acceptable SYN segment
1195 	 *	initialize tp->rcv_nxt and tp->irs
1196 	 *	if seg contains ack then advance tp->snd_una
1197 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1198 	 *	arrange for segment to be acked (eventually)
1199 	 *	continue processing rest of data/controls, beginning with URG
1200 	 */
1201 	case TCPS_SYN_SENT:
1202 		if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1203 			taop = &tao_noncached;
1204 			bzero(taop, sizeof(*taop));
1205 		}
1206 
1207 		if ((thflags & TH_ACK) &&
1208 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1209 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1210 			/*
1211 			 * If we have a cached CCsent for the remote host,
1212 			 * hence we haven't just crashed and restarted,
1213 			 * do not send a RST.  This may be a retransmission
1214 			 * from the other side after our earlier ACK was lost.
1215 			 * Our new SYN, when it arrives, will serve as the
1216 			 * needed ACK.
1217 			 */
1218 			if (taop->tao_ccsent != 0)
1219 				goto drop;
1220 			else {
1221 				rstreason = BANDLIM_UNLIMITED;
1222 				goto dropwithreset;
1223 			}
1224 		}
1225 		if (thflags & TH_RST) {
1226 			if (thflags & TH_ACK)
1227 				tp = tcp_drop(tp, ECONNREFUSED);
1228 			goto drop;
1229 		}
1230 		if ((thflags & TH_SYN) == 0)
1231 			goto drop;
1232 		tp->snd_wnd = th->th_win;	/* initial send window */
1233 		tp->cc_recv = to.to_cc;		/* foreign CC */
1234 
1235 		tp->irs = th->th_seq;
1236 		tcp_rcvseqinit(tp);
1237 		if (thflags & TH_ACK) {
1238 			/*
1239 			 * Our SYN was acked.  If segment contains CC.ECHO
1240 			 * option, check it to make sure this segment really
1241 			 * matches our SYN.  If not, just drop it as old
1242 			 * duplicate, but send an RST if we're still playing
1243 			 * by the old rules.  If no CC.ECHO option, make sure
1244 			 * we don't get fooled into using T/TCP.
1245 			 */
1246 			if (to.to_flags & TOF_CCECHO) {
1247 				if (tp->cc_send != to.to_ccecho) {
1248 					if (taop->tao_ccsent != 0)
1249 						goto drop;
1250 					else {
1251 						rstreason = BANDLIM_UNLIMITED;
1252 						goto dropwithreset;
1253 					}
1254 				}
1255 			} else
1256 				tp->t_flags &= ~TF_RCVD_CC;
1257 			tcpstat.tcps_connects++;
1258 			soisconnected(so);
1259 			/* Do window scaling on this connection? */
1260 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1261 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1262 				tp->snd_scale = tp->requested_s_scale;
1263 				tp->rcv_scale = tp->request_r_scale;
1264 			}
1265 			/* Segment is acceptable, update cache if undefined. */
1266 			if (taop->tao_ccsent == 0)
1267 				taop->tao_ccsent = to.to_ccecho;
1268 
1269 			tp->rcv_adv += tp->rcv_wnd;
1270 			tp->snd_una++;		/* SYN is acked */
1271 			/*
1272 			 * If there's data, delay ACK; if there's also a FIN
1273 			 * ACKNOW will be turned on later.
1274 			 */
1275 			if (DELAY_ACK(tp) && tlen != 0)
1276                                 callout_reset(tp->tt_delack, tcp_delacktime,
1277                                     tcp_timer_delack, tp);
1278 			else
1279 				tp->t_flags |= TF_ACKNOW;
1280 			/*
1281 			 * Received <SYN,ACK> in SYN_SENT[*] state.
1282 			 * Transitions:
1283 			 *	SYN_SENT  --> ESTABLISHED
1284 			 *	SYN_SENT* --> FIN_WAIT_1
1285 			 */
1286 			tp->t_starttime = ticks;
1287 			if (tp->t_flags & TF_NEEDFIN) {
1288 				tp->t_state = TCPS_FIN_WAIT_1;
1289 				tp->t_flags &= ~TF_NEEDFIN;
1290 				thflags &= ~TH_SYN;
1291 			} else {
1292 				tp->t_state = TCPS_ESTABLISHED;
1293 				callout_reset(tp->tt_keep, tcp_keepidle,
1294 					      tcp_timer_keep, tp);
1295 			}
1296 		} else {
1297 			/*
1298 			 * Received initial SYN in SYN-SENT[*] state =>
1299 			 * simultaneous open.  If segment contains CC option
1300 			 * and there is a cached CC, apply TAO test.
1301 			 * If it succeeds, connection is * half-synchronized.
1302 			 * Otherwise, do 3-way handshake:
1303 			 *        SYN-SENT -> SYN-RECEIVED
1304 			 *        SYN-SENT* -> SYN-RECEIVED*
1305 			 * If there was no CC option, clear cached CC value.
1306 			 */
1307 			tp->t_flags |= TF_ACKNOW;
1308 			callout_stop(tp->tt_rexmt);
1309 			if (to.to_flags & TOF_CC) {
1310 				if (taop->tao_cc != 0 &&
1311 				    CC_GT(to.to_cc, taop->tao_cc)) {
1312 					/*
1313 					 * update cache and make transition:
1314 					 *        SYN-SENT -> ESTABLISHED*
1315 					 *        SYN-SENT* -> FIN-WAIT-1*
1316 					 */
1317 					taop->tao_cc = to.to_cc;
1318 					tp->t_starttime = ticks;
1319 					if (tp->t_flags & TF_NEEDFIN) {
1320 						tp->t_state = TCPS_FIN_WAIT_1;
1321 						tp->t_flags &= ~TF_NEEDFIN;
1322 					} else {
1323 						tp->t_state = TCPS_ESTABLISHED;
1324 						callout_reset(tp->tt_keep,
1325 							      tcp_keepidle,
1326 							      tcp_timer_keep,
1327 							      tp);
1328 					}
1329 					tp->t_flags |= TF_NEEDSYN;
1330 				} else
1331 					tp->t_state = TCPS_SYN_RECEIVED;
1332 			} else {
1333 				/* CC.NEW or no option => invalidate cache */
1334 				taop->tao_cc = 0;
1335 				tp->t_state = TCPS_SYN_RECEIVED;
1336 			}
1337 		}
1338 
1339 trimthenstep6:
1340 		/*
1341 		 * Advance th->th_seq to correspond to first data byte.
1342 		 * If data, trim to stay within window,
1343 		 * dropping FIN if necessary.
1344 		 */
1345 		th->th_seq++;
1346 		if (tlen > tp->rcv_wnd) {
1347 			todrop = tlen - tp->rcv_wnd;
1348 			m_adj(m, -todrop);
1349 			tlen = tp->rcv_wnd;
1350 			thflags &= ~TH_FIN;
1351 			tcpstat.tcps_rcvpackafterwin++;
1352 			tcpstat.tcps_rcvbyteafterwin += todrop;
1353 		}
1354 		tp->snd_wl1 = th->th_seq - 1;
1355 		tp->rcv_up = th->th_seq;
1356 		/*
1357 		 * Client side of transaction: already sent SYN and data.
1358 		 * If the remote host used T/TCP to validate the SYN,
1359 		 * our data will be ACK'd; if so, enter normal data segment
1360 		 * processing in the middle of step 5, ack processing.
1361 		 * Otherwise, goto step 6.
1362 		 */
1363 		if (thflags & TH_ACK)
1364 			goto process_ACK;
1365 
1366 		goto step6;
1367 
1368 	/*
1369 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1370 	 *	if segment contains a SYN and CC [not CC.NEW] option:
1371 	 *              if state == TIME_WAIT and connection duration > MSL,
1372 	 *                  drop packet and send RST;
1373 	 *
1374 	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
1375 	 *		    ack the FIN (and data) in retransmission queue.
1376 	 *                  Complete close and delete TCPCB.  Then reprocess
1377 	 *                  segment, hoping to find new TCPCB in LISTEN state;
1378 	 *
1379 	 *		else must be old SYN; drop it.
1380 	 *      else do normal processing.
1381 	 */
1382 	case TCPS_LAST_ACK:
1383 	case TCPS_CLOSING:
1384 	case TCPS_TIME_WAIT:
1385 		if ((thflags & TH_SYN) &&
1386 		    (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1387 			if (tp->t_state == TCPS_TIME_WAIT &&
1388 					(ticks - tp->t_starttime) > tcp_msl) {
1389 				rstreason = BANDLIM_UNLIMITED;
1390 				goto dropwithreset;
1391 			}
1392 			if (CC_GT(to.to_cc, tp->cc_recv)) {
1393 				tp = tcp_close(tp);
1394 				goto findpcb;
1395 			}
1396 			else
1397 				goto drop;
1398 		}
1399 		break;  /* continue normal processing */
1400 	}
1401 
1402 	/*
1403 	 * States other than LISTEN or SYN_SENT.
1404 	 * First check the RST flag and sequence number since reset segments
1405 	 * are exempt from the timestamp and connection count tests.  This
1406 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1407 	 * below which allowed reset segments in half the sequence space
1408 	 * to fall though and be processed (which gives forged reset
1409 	 * segments with a random sequence number a 50 percent chance of
1410 	 * killing a connection).
1411 	 * Then check timestamp, if present.
1412 	 * Then check the connection count, if present.
1413 	 * Then check that at least some bytes of segment are within
1414 	 * receive window.  If segment begins before rcv_nxt,
1415 	 * drop leading data (and SYN); if nothing left, just ack.
1416 	 *
1417 	 *
1418 	 * If the RST bit is set, check the sequence number to see
1419 	 * if this is a valid reset segment.
1420 	 * RFC 793 page 37:
1421 	 *   In all states except SYN-SENT, all reset (RST) segments
1422 	 *   are validated by checking their SEQ-fields.  A reset is
1423 	 *   valid if its sequence number is in the window.
1424 	 * Note: this does not take into account delayed ACKs, so
1425 	 *   we should test against last_ack_sent instead of rcv_nxt.
1426 	 *   The sequence number in the reset segment is normally an
1427 	 *   echo of our outgoing acknowlegement numbers, but some hosts
1428 	 *   send a reset with the sequence number at the rightmost edge
1429 	 *   of our receive window, and we have to handle this case.
1430 	 * If we have multiple segments in flight, the intial reset
1431 	 * segment sequence numbers will be to the left of last_ack_sent,
1432 	 * but they will eventually catch up.
1433 	 * In any case, it never made sense to trim reset segments to
1434 	 * fit the receive window since RFC 1122 says:
1435 	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1436 	 *
1437 	 *    A TCP SHOULD allow a received RST segment to include data.
1438 	 *
1439 	 *    DISCUSSION
1440 	 *         It has been suggested that a RST segment could contain
1441 	 *         ASCII text that encoded and explained the cause of the
1442 	 *         RST.  No standard has yet been established for such
1443 	 *         data.
1444 	 *
1445 	 * If the reset segment passes the sequence number test examine
1446 	 * the state:
1447 	 *    SYN_RECEIVED STATE:
1448 	 *	If passive open, return to LISTEN state.
1449 	 *	If active open, inform user that connection was refused.
1450 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1451 	 *	Inform user that connection was reset, and close tcb.
1452 	 *    CLOSING, LAST_ACK STATES:
1453 	 *	Close the tcb.
1454 	 *    TIME_WAIT STATE:
1455 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1456 	 *      RFC 1337.
1457 	 */
1458 	if (thflags & TH_RST) {
1459 		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1460 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1461 			switch (tp->t_state) {
1462 
1463 			case TCPS_SYN_RECEIVED:
1464 				so->so_error = ECONNREFUSED;
1465 				goto close;
1466 
1467 			case TCPS_ESTABLISHED:
1468 			case TCPS_FIN_WAIT_1:
1469 			case TCPS_FIN_WAIT_2:
1470 			case TCPS_CLOSE_WAIT:
1471 				so->so_error = ECONNRESET;
1472 			close:
1473 				tp->t_state = TCPS_CLOSED;
1474 				tcpstat.tcps_drops++;
1475 				tp = tcp_close(tp);
1476 				break;
1477 
1478 			case TCPS_CLOSING:
1479 			case TCPS_LAST_ACK:
1480 				tp = tcp_close(tp);
1481 				break;
1482 
1483 			case TCPS_TIME_WAIT:
1484 				break;
1485 			}
1486 		}
1487 		goto drop;
1488 	}
1489 
1490 	/*
1491 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1492 	 * and it's less than ts_recent, drop it.
1493 	 */
1494 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1495 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1496 
1497 		/* Check to see if ts_recent is over 24 days old.  */
1498 		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1499 			/*
1500 			 * Invalidate ts_recent.  If this segment updates
1501 			 * ts_recent, the age will be reset later and ts_recent
1502 			 * will get a valid value.  If it does not, setting
1503 			 * ts_recent to zero will at least satisfy the
1504 			 * requirement that zero be placed in the timestamp
1505 			 * echo reply when ts_recent isn't valid.  The
1506 			 * age isn't reset until we get a valid ts_recent
1507 			 * because we don't want out-of-order segments to be
1508 			 * dropped when ts_recent is old.
1509 			 */
1510 			tp->ts_recent = 0;
1511 		} else {
1512 			tcpstat.tcps_rcvduppack++;
1513 			tcpstat.tcps_rcvdupbyte += tlen;
1514 			tcpstat.tcps_pawsdrop++;
1515 			if (tlen)
1516 				goto dropafterack;
1517 			goto drop;
1518 		}
1519 	}
1520 
1521 	/*
1522 	 * T/TCP mechanism
1523 	 *   If T/TCP was negotiated and the segment doesn't have CC,
1524 	 *   or if its CC is wrong then drop the segment.
1525 	 *   RST segments do not have to comply with this.
1526 	 */
1527 	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1528 	    ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1529 		goto dropafterack;
1530 
1531 	/*
1532 	 * In the SYN-RECEIVED state, validate that the packet belongs to
1533 	 * this connection before trimming the data to fit the receive
1534 	 * window.  Check the sequence number versus IRS since we know
1535 	 * the sequence numbers haven't wrapped.  This is a partial fix
1536 	 * for the "LAND" DoS attack.
1537 	 */
1538 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1539 		rstreason = BANDLIM_RST_OPENPORT;
1540 		goto dropwithreset;
1541 	}
1542 
1543 	todrop = tp->rcv_nxt - th->th_seq;
1544 	if (todrop > 0) {
1545 		if (thflags & TH_SYN) {
1546 			thflags &= ~TH_SYN;
1547 			th->th_seq++;
1548 			if (th->th_urp > 1)
1549 				th->th_urp--;
1550 			else
1551 				thflags &= ~TH_URG;
1552 			todrop--;
1553 		}
1554 		/*
1555 		 * Following if statement from Stevens, vol. 2, p. 960.
1556 		 */
1557 		if (todrop > tlen
1558 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1559 			/*
1560 			 * Any valid FIN must be to the left of the window.
1561 			 * At this point the FIN must be a duplicate or out
1562 			 * of sequence; drop it.
1563 			 */
1564 			thflags &= ~TH_FIN;
1565 
1566 			/*
1567 			 * Send an ACK to resynchronize and drop any data.
1568 			 * But keep on processing for RST or ACK.
1569 			 */
1570 			tp->t_flags |= TF_ACKNOW;
1571 			todrop = tlen;
1572 			tcpstat.tcps_rcvduppack++;
1573 			tcpstat.tcps_rcvdupbyte += todrop;
1574 		} else {
1575 			tcpstat.tcps_rcvpartduppack++;
1576 			tcpstat.tcps_rcvpartdupbyte += todrop;
1577 		}
1578 		drop_hdrlen += todrop;	/* drop from the top afterwards */
1579 		th->th_seq += todrop;
1580 		tlen -= todrop;
1581 		if (th->th_urp > todrop)
1582 			th->th_urp -= todrop;
1583 		else {
1584 			thflags &= ~TH_URG;
1585 			th->th_urp = 0;
1586 		}
1587 	}
1588 
1589 	/*
1590 	 * If new data are received on a connection after the
1591 	 * user processes are gone, then RST the other end.
1592 	 */
1593 	if ((so->so_state & SS_NOFDREF) &&
1594 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1595 		tp = tcp_close(tp);
1596 		tcpstat.tcps_rcvafterclose++;
1597 		rstreason = BANDLIM_UNLIMITED;
1598 		goto dropwithreset;
1599 	}
1600 
1601 	/*
1602 	 * If segment ends after window, drop trailing data
1603 	 * (and PUSH and FIN); if nothing left, just ACK.
1604 	 */
1605 	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1606 	if (todrop > 0) {
1607 		tcpstat.tcps_rcvpackafterwin++;
1608 		if (todrop >= tlen) {
1609 			tcpstat.tcps_rcvbyteafterwin += tlen;
1610 			/*
1611 			 * If a new connection request is received
1612 			 * while in TIME_WAIT, drop the old connection
1613 			 * and start over if the sequence numbers
1614 			 * are above the previous ones.
1615 			 */
1616 			if (thflags & TH_SYN &&
1617 			    tp->t_state == TCPS_TIME_WAIT &&
1618 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1619 				tp = tcp_close(tp);
1620 				goto findpcb;
1621 			}
1622 			/*
1623 			 * If window is closed can only take segments at
1624 			 * window edge, and have to drop data and PUSH from
1625 			 * incoming segments.  Continue processing, but
1626 			 * remember to ack.  Otherwise, drop segment
1627 			 * and ack.
1628 			 */
1629 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1630 				tp->t_flags |= TF_ACKNOW;
1631 				tcpstat.tcps_rcvwinprobe++;
1632 			} else
1633 				goto dropafterack;
1634 		} else
1635 			tcpstat.tcps_rcvbyteafterwin += todrop;
1636 		m_adj(m, -todrop);
1637 		tlen -= todrop;
1638 		thflags &= ~(TH_PUSH|TH_FIN);
1639 	}
1640 
1641 	/*
1642 	 * If last ACK falls within this segment's sequence numbers,
1643 	 * record its timestamp.
1644 	 * NOTE that the test is modified according to the latest
1645 	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1646 	 */
1647 	if ((to.to_flags & TOF_TS) != 0 &&
1648 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1649 		tp->ts_recent_age = ticks;
1650 		tp->ts_recent = to.to_tsval;
1651 	}
1652 
1653 	/*
1654 	 * If a SYN is in the window, then this is an
1655 	 * error and we send an RST and drop the connection.
1656 	 */
1657 	if (thflags & TH_SYN) {
1658 		tp = tcp_drop(tp, ECONNRESET);
1659 		rstreason = BANDLIM_UNLIMITED;
1660 		goto dropwithreset;
1661 	}
1662 
1663 	/*
1664 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1665 	 * flag is on (half-synchronized state), then queue data for
1666 	 * later processing; else drop segment and return.
1667 	 */
1668 	if ((thflags & TH_ACK) == 0) {
1669 		if (tp->t_state == TCPS_SYN_RECEIVED ||
1670 		    (tp->t_flags & TF_NEEDSYN))
1671 			goto step6;
1672 		else
1673 			goto drop;
1674 	}
1675 
1676 	/*
1677 	 * Ack processing.
1678 	 */
1679 	switch (tp->t_state) {
1680 
1681 	/*
1682 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1683 	 * ESTABLISHED state and continue processing.
1684 	 * The ACK was checked above.
1685 	 */
1686 	case TCPS_SYN_RECEIVED:
1687 
1688 		tcpstat.tcps_connects++;
1689 		soisconnected(so);
1690 		/* Do window scaling? */
1691 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1692 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1693 			tp->snd_scale = tp->requested_s_scale;
1694 			tp->rcv_scale = tp->request_r_scale;
1695 		}
1696 		/*
1697 		 * Upon successful completion of 3-way handshake,
1698 		 * update cache.CC if it was undefined, pass any queued
1699 		 * data to the user, and advance state appropriately.
1700 		 */
1701 		if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1702 		    taop->tao_cc == 0)
1703 			taop->tao_cc = tp->cc_recv;
1704 
1705 		/*
1706 		 * Make transitions:
1707 		 *      SYN-RECEIVED  -> ESTABLISHED
1708 		 *      SYN-RECEIVED* -> FIN-WAIT-1
1709 		 */
1710 		tp->t_starttime = ticks;
1711 		if (tp->t_flags & TF_NEEDFIN) {
1712 			tp->t_state = TCPS_FIN_WAIT_1;
1713 			tp->t_flags &= ~TF_NEEDFIN;
1714 		} else {
1715 			tp->t_state = TCPS_ESTABLISHED;
1716 			callout_reset(tp->tt_keep, tcp_keepidle,
1717 				      tcp_timer_keep, tp);
1718 		}
1719 		/*
1720 		 * If segment contains data or ACK, will call tcp_reass()
1721 		 * later; if not, do so now to pass queued data to user.
1722 		 */
1723 		if (tlen == 0 && (thflags & TH_FIN) == 0)
1724 			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1725 			    (struct mbuf *)0);
1726 		tp->snd_wl1 = th->th_seq - 1;
1727 		/* fall into ... */
1728 
1729 	/*
1730 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1731 	 * ACKs.  If the ack is in the range
1732 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1733 	 * then advance tp->snd_una to th->th_ack and drop
1734 	 * data from the retransmission queue.  If this ACK reflects
1735 	 * more up to date window information we update our window information.
1736 	 */
1737 	case TCPS_ESTABLISHED:
1738 	case TCPS_FIN_WAIT_1:
1739 	case TCPS_FIN_WAIT_2:
1740 	case TCPS_CLOSE_WAIT:
1741 	case TCPS_CLOSING:
1742 	case TCPS_LAST_ACK:
1743 	case TCPS_TIME_WAIT:
1744 
1745 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1746 			if (tlen != 0 || tiwin != tp->snd_wnd) {
1747 				tp->t_dupacks = 0;
1748 				break;
1749 			}
1750 			tcpstat.tcps_rcvdupack++;
1751 			/*
1752 			 * If we have outstanding data (other than
1753 			 * a window probe), this is a completely
1754 			 * duplicate ack (ie, window info didn't
1755 			 * change), the ack is the biggest we've
1756 			 * seen and we've seen exactly our rexmt
1757 			 * threshhold of them, assume a packet
1758 			 * has been dropped and retransmit it.
1759 			 * Kludge snd_nxt & the congestion
1760 			 * window so we send only this one
1761 			 * packet.
1762 			 *
1763 			 * We know we're losing at the current
1764 			 * window size so do congestion avoidance
1765 			 * (set ssthresh to half the current window
1766 			 * and pull our congestion window back to
1767 			 * the new ssthresh).
1768 			 *
1769 			 * Dup acks mean that packets have left the
1770 			 * network (they're now cached at the receiver)
1771 			 * so bump cwnd by the amount in the receiver
1772 			 * to keep a constant cwnd packets in the
1773 			 * network.
1774 			 */
1775 			if (!callout_active(tp->tt_rexmt) ||
1776 			    th->th_ack != tp->snd_una) {
1777 				tp->t_dupacks = 0;
1778 				break;
1779 			}
1780 			if (IN_FASTRECOVERY(tp)) {
1781 				tp->snd_cwnd += tp->t_maxseg;
1782 				(void) tcp_output(tp);
1783 			} else if (++tp->t_dupacks == tcprexmtthresh) {
1784 				tcp_seq onxt;
1785 				u_int win;
1786 
1787 				if (SEQ_LEQ(th->th_ack, tp->snd_recover)) {
1788 					tp->t_dupacks = 0;
1789 					break;
1790 				}
1791 fastretransmit:
1792 				if (tcp_do_eifel_detect &&
1793 				    (tp->t_flags & TF_RCVD_TSTMP)) {
1794 					tcp_save_congestion_state(tp);
1795 					tp->t_flags |= TF_FASTREXMT;
1796 				}
1797 				win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1798 				    tp->t_maxseg;
1799 				if (win < 2)
1800 					win = 2;
1801 				tp->snd_ssthresh = win * tp->t_maxseg;
1802 				ENTER_FASTRECOVERY(tp);
1803 				tp->snd_recover = tp->snd_max;
1804 				callout_stop(tp->tt_rexmt);
1805 				tp->t_rtttime = 0;
1806 				onxt = tp->snd_nxt;
1807 				tp->snd_nxt = th->th_ack;
1808 				tp->snd_cwnd = tp->t_maxseg;
1809 				(void) tcp_output(tp);
1810 				++tcpstat.tcps_sndfastrexmit;
1811 				KASSERT(tp->snd_limited <= 2,
1812 				    ("tp->snd_limited too big"));
1813 				tp->snd_cwnd = tp->snd_ssthresh +
1814 				    (tp->t_maxseg *
1815 				     (tp->t_dupacks - tp->snd_limited));
1816 				if (SEQ_GT(onxt, tp->snd_nxt))
1817 					tp->snd_nxt = onxt;
1818 			} else if (tcp_do_limitedtransmit) {
1819 				u_long oldcwnd = tp->snd_cwnd;
1820 				tcp_seq oldsndmax = tp->snd_max;
1821 				/* outstanding data */
1822 				uint32_t ownd = tp->snd_max - tp->snd_una;
1823 				u_int sent;
1824 
1825 #define	iceildiv(n, d)		(((n)+(d)-1) / (d))
1826 
1827 				KASSERT(tp->t_dupacks == 1 ||
1828 					tp->t_dupacks == 2,
1829 				    ("dupacks not 1 or 2"));
1830 				if (tp->t_dupacks == 1)
1831 					tp->snd_limited = 0;
1832 				tp->snd_cwnd = ownd +
1833 				    (tp->t_dupacks - tp->snd_limited) *
1834 				    tp->t_maxseg;
1835 				(void) tcp_output(tp);
1836 				tp->snd_cwnd = oldcwnd;
1837 				sent = tp->snd_max - oldsndmax;
1838 				if (sent > tp->t_maxseg) {
1839 					KASSERT((tp->t_dupacks == 2 &&
1840 						 tp->snd_limited == 0) ||
1841 						(sent == tp->t_maxseg + 1 &&
1842 						 tp->t_flags & TF_SENTFIN),
1843 					    ("sent too much"));
1844 					KASSERT(sent <= tp->t_maxseg * 2,
1845 					    ("sent too many segments"));
1846 					tp->snd_limited = 2;
1847 					tcpstat.tcps_sndlimited += 2;
1848 				} else if (sent > 0) {
1849 					++tp->snd_limited;
1850 					++tcpstat.tcps_sndlimited;
1851 				} else if (tcp_do_early_retransmit &&
1852 				    (tcp_do_eifel_detect &&
1853 				     (tp->t_flags & TF_RCVD_TSTMP)) &&
1854 				    tp->t_dupacks + 1 >=
1855 				      iceildiv(ownd, tp->t_maxseg)) {
1856 					++tcpstat.tcps_sndearlyrexmit;
1857 					tp->t_flags |= TF_EARLYREXMT;
1858 					goto fastretransmit;
1859 				}
1860 			}
1861 			goto drop;
1862 		}
1863 
1864 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1865 
1866 		/*
1867 		 * If the congestion window was inflated to account
1868 		 * for the other side's cached packets, retract it.
1869 		 */
1870 		if (IN_FASTRECOVERY(tp)) {
1871 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1872 				tcp_newreno_partial_ack(tp, th);
1873 			} else {
1874 				/*
1875 				 * Window inflation should have left us
1876 				 * with approximately snd_ssthresh
1877 				 * outstanding data.
1878 				 * But in case we would be inclined to
1879 				 * send a burst, better to do it via
1880 				 * the slow start mechanism.
1881 				 */
1882 				if (SEQ_GT(th->th_ack + tp->snd_ssthresh,
1883 					   tp->snd_max))
1884 					tp->snd_cwnd = tp->snd_max -
1885 					    th->th_ack + tp->t_maxseg;
1886 				else
1887 					tp->snd_cwnd = tp->snd_ssthresh;
1888 			}
1889 		}
1890 		tp->t_dupacks = 0;
1891 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1892 			/*
1893 			 * Detected optimistic ACK attack.
1894 			 * Force slow-start to de-synchronize attack.
1895 			 */
1896 			tp->snd_cwnd = tp->t_maxseg;
1897 
1898 			tcpstat.tcps_rcvacktoomuch++;
1899 			goto dropafterack;
1900 		}
1901 		/*
1902 		 * If we reach this point, ACK is not a duplicate,
1903 		 *     i.e., it ACKs something we sent.
1904 		 */
1905 		if (tp->t_flags & TF_NEEDSYN) {
1906 			/*
1907 			 * T/TCP: Connection was half-synchronized, and our
1908 			 * SYN has been ACK'd (so connection is now fully
1909 			 * synchronized).  Go to non-starred state,
1910 			 * increment snd_una for ACK of SYN, and check if
1911 			 * we can do window scaling.
1912 			 */
1913 			tp->t_flags &= ~TF_NEEDSYN;
1914 			tp->snd_una++;
1915 			/* Do window scaling? */
1916 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1917 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1918 				tp->snd_scale = tp->requested_s_scale;
1919 				tp->rcv_scale = tp->request_r_scale;
1920 			}
1921 		}
1922 
1923 process_ACK:
1924 		acked = th->th_ack - tp->snd_una;
1925 		tcpstat.tcps_rcvackpack++;
1926 		tcpstat.tcps_rcvackbyte += acked;
1927 
1928 		/*
1929 		 * If we just performed our first retransmit, and the ACK
1930 		 * arrives within our recovery window, then it was a mistake
1931 		 * to do the retransmit in the first place.  Recover our
1932 		 * original cwnd and ssthresh, and proceed to transmit where
1933 		 * we left off.
1934 		 */
1935 		if (tcp_do_eifel_detect && acked &&
1936 		    (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
1937 		    (tp->t_flags & TF_FIRSTACCACK)) {
1938 			/* Eifel detection applicable. */
1939 			if (to.to_tsecr < tp->t_rexmtTS) {
1940 				++tcpstat.tcps_eifeldetected;
1941 				tcp_revert_congestion_state(tp);
1942 				if (tp->t_rxtshift == 1 &&
1943 				    ticks >= tp->t_badrxtwin)
1944 					++tcpstat.tcps_rttcantdetect;
1945 			}
1946 		} else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1947 			tcp_revert_congestion_state(tp);
1948 			++tcpstat.tcps_rttdetected;
1949 		}
1950 
1951 		/*
1952 		 * If we have a timestamp reply, update smoothed
1953 		 * round trip time.  If no timestamp is present but
1954 		 * transmit timer is running and timed sequence
1955 		 * number was acked, update smoothed round trip time.
1956 		 * Since we now have an rtt measurement, cancel the
1957 		 * timer backoff (cf., Phil Karn's retransmit alg.).
1958 		 * Recompute the initial retransmit timer.
1959 		 *
1960 		 * Some machines (certain windows boxes) send broken
1961 		 * timestamp replies during the SYN+ACK phase, ignore
1962 		 * timestamps of 0.
1963 		 */
1964 		if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
1965 			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1966 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
1967 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1968 		tcp_xmit_bandwidth_limit(tp, th->th_ack);
1969 
1970 		/*
1971 		 * If all outstanding data is acked, stop retransmit
1972 		 * timer and remember to restart (more output or persist).
1973 		 * If there is more data to be acked, restart retransmit
1974 		 * timer, using current (possibly backed-off) value.
1975 		 */
1976 		if (th->th_ack == tp->snd_max) {
1977 			callout_stop(tp->tt_rexmt);
1978 			needoutput = 1;
1979 		} else if (!callout_active(tp->tt_persist))
1980 			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1981 				      tcp_timer_rexmt, tp);
1982 
1983 		/*
1984 		 * If no data (only SYN) was ACK'd,
1985 		 *    skip rest of ACK processing.
1986 		 */
1987 		if (acked == 0)
1988 			goto step6;
1989 
1990 		/* Stop looking for an acceptable ACK since one was received. */
1991 		tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
1992 
1993 		/*
1994 		 * When new data is acked, open the congestion window.
1995 		 * If the window gives us less than ssthresh packets
1996 		 * in flight, open exponentially (maxseg per packet).
1997 		 * Otherwise open linearly: maxseg per window
1998 		 * (maxseg^2 / cwnd per packet).
1999 		 */
2000 		if (!IN_FASTRECOVERY(tp)) {
2001 			u_int cw = tp->snd_cwnd;
2002 			u_int incr = tp->t_maxseg;
2003 
2004 			if (cw > tp->snd_ssthresh)
2005 				incr = incr * incr / cw;
2006 			tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2007 		}
2008 		if (acked > so->so_snd.sb_cc) {
2009 			tp->snd_wnd -= so->so_snd.sb_cc;
2010 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2011 			ourfinisacked = 1;
2012 		} else {
2013 			sbdrop(&so->so_snd, acked);
2014 			tp->snd_wnd -= acked;
2015 			ourfinisacked = 0;
2016 		}
2017 		sowwakeup(so);
2018 		if (IN_FASTRECOVERY(tp)) {
2019 			if (SEQ_GEQ(th->th_ack, tp->snd_recover))
2020 				EXIT_FASTRECOVERY(tp);
2021 		} else {
2022 			tp->snd_recover = th->th_ack - 1;
2023 		}
2024 		tp->snd_una = th->th_ack;
2025 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2026 			tp->snd_nxt = tp->snd_una;
2027 
2028 		switch (tp->t_state) {
2029 
2030 		/*
2031 		 * In FIN_WAIT_1 STATE in addition to the processing
2032 		 * for the ESTABLISHED state if our FIN is now acknowledged
2033 		 * then enter FIN_WAIT_2.
2034 		 */
2035 		case TCPS_FIN_WAIT_1:
2036 			if (ourfinisacked) {
2037 				/*
2038 				 * If we can't receive any more
2039 				 * data, then closing user can proceed.
2040 				 * Starting the timer is contrary to the
2041 				 * specification, but if we don't get a FIN
2042 				 * we'll hang forever.
2043 				 */
2044 				if (so->so_state & SS_CANTRCVMORE) {
2045 					soisdisconnected(so);
2046 					callout_reset(tp->tt_2msl, tcp_maxidle,
2047 						      tcp_timer_2msl, tp);
2048 				}
2049 				tp->t_state = TCPS_FIN_WAIT_2;
2050 			}
2051 			break;
2052 
2053 		/*
2054 		 * In CLOSING STATE in addition to the processing for
2055 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2056 		 * then enter the TIME-WAIT state, otherwise ignore
2057 		 * the segment.
2058 		 */
2059 		case TCPS_CLOSING:
2060 			if (ourfinisacked) {
2061 				tp->t_state = TCPS_TIME_WAIT;
2062 				tcp_canceltimers(tp);
2063 				/* Shorten TIME_WAIT [RFC-1644, p.28] */
2064 				if (tp->cc_recv != 0 &&
2065 				    (ticks - tp->t_starttime) < tcp_msl)
2066 					callout_reset(tp->tt_2msl,
2067 						      tp->t_rxtcur *
2068 						      TCPTV_TWTRUNC,
2069 						      tcp_timer_2msl, tp);
2070 				else
2071 					callout_reset(tp->tt_2msl, 2 * tcp_msl,
2072 						      tcp_timer_2msl, tp);
2073 				soisdisconnected(so);
2074 			}
2075 			break;
2076 
2077 		/*
2078 		 * In LAST_ACK, we may still be waiting for data to drain
2079 		 * and/or to be acked, as well as for the ack of our FIN.
2080 		 * If our FIN is now acknowledged, delete the TCB,
2081 		 * enter the closed state and return.
2082 		 */
2083 		case TCPS_LAST_ACK:
2084 			if (ourfinisacked) {
2085 				tp = tcp_close(tp);
2086 				goto drop;
2087 			}
2088 			break;
2089 
2090 		/*
2091 		 * In TIME_WAIT state the only thing that should arrive
2092 		 * is a retransmission of the remote FIN.  Acknowledge
2093 		 * it and restart the finack timer.
2094 		 */
2095 		case TCPS_TIME_WAIT:
2096 			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2097 				      tcp_timer_2msl, tp);
2098 			goto dropafterack;
2099 		}
2100 	}
2101 
2102 step6:
2103 	/*
2104 	 * Update window information.
2105 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2106 	 */
2107 	if ((thflags & TH_ACK) &&
2108 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2109 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2110 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2111 		/* keep track of pure window updates */
2112 		if (tlen == 0 &&
2113 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2114 			tcpstat.tcps_rcvwinupd++;
2115 		tp->snd_wnd = tiwin;
2116 		tp->snd_wl1 = th->th_seq;
2117 		tp->snd_wl2 = th->th_ack;
2118 		if (tp->snd_wnd > tp->max_sndwnd)
2119 			tp->max_sndwnd = tp->snd_wnd;
2120 		needoutput = 1;
2121 	}
2122 
2123 	/*
2124 	 * Process segments with URG.
2125 	 */
2126 	if ((thflags & TH_URG) && th->th_urp &&
2127 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
2128 		/*
2129 		 * This is a kludge, but if we receive and accept
2130 		 * random urgent pointers, we'll crash in
2131 		 * soreceive.  It's hard to imagine someone
2132 		 * actually wanting to send this much urgent data.
2133 		 */
2134 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2135 			th->th_urp = 0;			/* XXX */
2136 			thflags &= ~TH_URG;		/* XXX */
2137 			goto dodata;			/* XXX */
2138 		}
2139 		/*
2140 		 * If this segment advances the known urgent pointer,
2141 		 * then mark the data stream.  This should not happen
2142 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2143 		 * a FIN has been received from the remote side.
2144 		 * In these states we ignore the URG.
2145 		 *
2146 		 * According to RFC961 (Assigned Protocols),
2147 		 * the urgent pointer points to the last octet
2148 		 * of urgent data.  We continue, however,
2149 		 * to consider it to indicate the first octet
2150 		 * of data past the urgent section as the original
2151 		 * spec states (in one of two places).
2152 		 */
2153 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2154 			tp->rcv_up = th->th_seq + th->th_urp;
2155 			so->so_oobmark = so->so_rcv.sb_cc +
2156 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2157 			if (so->so_oobmark == 0)
2158 				so->so_state |= SS_RCVATMARK;
2159 			sohasoutofband(so);
2160 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2161 		}
2162 		/*
2163 		 * Remove out of band data so doesn't get presented to user.
2164 		 * This can happen independent of advancing the URG pointer,
2165 		 * but if two URG's are pending at once, some out-of-band
2166 		 * data may creep in... ick.
2167 		 */
2168 		if (th->th_urp <= (u_long)tlen
2169 #ifdef SO_OOBINLINE
2170 		     && (so->so_options & SO_OOBINLINE) == 0
2171 #endif
2172 		     )
2173 			tcp_pulloutofband(so, th, m,
2174 				drop_hdrlen);	/* hdr drop is delayed */
2175 	} else {
2176 		/*
2177 		 * If no out of band data is expected,
2178 		 * pull receive urgent pointer along
2179 		 * with the receive window.
2180 		 */
2181 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2182 			tp->rcv_up = tp->rcv_nxt;
2183 	}
2184 dodata:							/* XXX */
2185 
2186 	/*
2187 	 * Process the segment text, merging it into the TCP sequencing queue,
2188 	 * and arranging for acknowledgment of receipt if necessary.
2189 	 * This process logically involves adjusting tp->rcv_wnd as data
2190 	 * is presented to the user (this happens in tcp_usrreq.c,
2191 	 * case PRU_RCVD).  If a FIN has already been received on this
2192 	 * connection then we just ignore the text.
2193 	 */
2194 	if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2195 		m_adj(m, drop_hdrlen);	/* delayed header drop */
2196 		/*
2197 		 * Insert segment which includes th into TCP reassembly queue
2198 		 * with control block tp.  Set thflags to whether reassembly now
2199 		 * includes a segment with FIN.  This handles the common case
2200 		 * inline (segment is the next to be received on an established
2201 		 * connection, and the queue is empty), avoiding linkage into
2202 		 * and removal from the queue and repetition of various
2203 		 * conversions.
2204 		 * Set DELACK for segments received in order, but ack
2205 		 * immediately when segments are out of order (so
2206 		 * fast retransmit can work).
2207 		 */
2208 		if (th->th_seq == tp->rcv_nxt &&
2209 		    LIST_EMPTY(&tp->t_segq) &&
2210 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2211 			if (DELAY_ACK(tp))
2212 				callout_reset(tp->tt_delack, tcp_delacktime,
2213 					      tcp_timer_delack, tp);
2214 			else
2215 				tp->t_flags |= TF_ACKNOW;
2216 			tp->rcv_nxt += tlen;
2217 			thflags = th->th_flags & TH_FIN;
2218 			tcpstat.tcps_rcvpack++;
2219 			tcpstat.tcps_rcvbyte += tlen;
2220 			ND6_HINT(tp);
2221 			if (so->so_state & SS_CANTRCVMORE)
2222 				m_freem(m);
2223 			else
2224 				sbappend(&so->so_rcv, m);
2225 			sorwakeup(so);
2226 		} else {
2227 			thflags = tcp_reass(tp, th, &tlen, m);
2228 			tp->t_flags |= TF_ACKNOW;
2229 		}
2230 
2231 		/*
2232 		 * Note the amount of data that peer has sent into
2233 		 * our window, in order to estimate the sender's
2234 		 * buffer size.
2235 		 */
2236 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2237 	} else {
2238 		m_freem(m);
2239 		thflags &= ~TH_FIN;
2240 	}
2241 
2242 	/*
2243 	 * If FIN is received ACK the FIN and let the user know
2244 	 * that the connection is closing.
2245 	 */
2246 	if (thflags & TH_FIN) {
2247 		if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2248 			socantrcvmore(so);
2249 			/*
2250 			 * If connection is half-synchronized
2251 			 * (ie NEEDSYN flag on) then delay ACK,
2252 			 * so it may be piggybacked when SYN is sent.
2253 			 * Otherwise, since we received a FIN then no
2254 			 * more input can be expected, send ACK now.
2255 			 */
2256 			if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2257                                 callout_reset(tp->tt_delack, tcp_delacktime,
2258                                     tcp_timer_delack, tp);
2259 			else
2260 				tp->t_flags |= TF_ACKNOW;
2261 			tp->rcv_nxt++;
2262 		}
2263 		switch (tp->t_state) {
2264 
2265 		/*
2266 		 * In SYN_RECEIVED and ESTABLISHED STATES
2267 		 * enter the CLOSE_WAIT state.
2268 		 */
2269 		case TCPS_SYN_RECEIVED:
2270 			tp->t_starttime = ticks;
2271 			/*FALLTHROUGH*/
2272 		case TCPS_ESTABLISHED:
2273 			tp->t_state = TCPS_CLOSE_WAIT;
2274 			break;
2275 
2276 		/*
2277 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2278 		 * enter the CLOSING state.
2279 		 */
2280 		case TCPS_FIN_WAIT_1:
2281 			tp->t_state = TCPS_CLOSING;
2282 			break;
2283 
2284 		/*
2285 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2286 		 * starting the time-wait timer, turning off the other
2287 		 * standard timers.
2288 		 */
2289 		case TCPS_FIN_WAIT_2:
2290 			tp->t_state = TCPS_TIME_WAIT;
2291 			tcp_canceltimers(tp);
2292 			/* Shorten TIME_WAIT [RFC-1644, p.28] */
2293 			if (tp->cc_recv != 0 &&
2294 			    (ticks - tp->t_starttime) < tcp_msl) {
2295 				callout_reset(tp->tt_2msl,
2296 					      tp->t_rxtcur * TCPTV_TWTRUNC,
2297 					      tcp_timer_2msl, tp);
2298 				/* For transaction client, force ACK now. */
2299 				tp->t_flags |= TF_ACKNOW;
2300 			}
2301 			else
2302 				callout_reset(tp->tt_2msl, 2 * tcp_msl,
2303 					      tcp_timer_2msl, tp);
2304 			soisdisconnected(so);
2305 			break;
2306 
2307 		/*
2308 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2309 		 */
2310 		case TCPS_TIME_WAIT:
2311 			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2312 				      tcp_timer_2msl, tp);
2313 			break;
2314 		}
2315 	}
2316 #ifdef TCPDEBUG
2317 	if (so->so_options & SO_DEBUG)
2318 		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2319 			  &tcp_savetcp, 0);
2320 #endif
2321 
2322 	/*
2323 	 * Return any desired output.
2324 	 */
2325 	if (needoutput || (tp->t_flags & TF_ACKNOW))
2326 		(void) tcp_output(tp);
2327 	return;
2328 
2329 dropafterack:
2330 	/*
2331 	 * Generate an ACK dropping incoming segment if it occupies
2332 	 * sequence space, where the ACK reflects our state.
2333 	 *
2334 	 * We can now skip the test for the RST flag since all
2335 	 * paths to this code happen after packets containing
2336 	 * RST have been dropped.
2337 	 *
2338 	 * In the SYN-RECEIVED state, don't send an ACK unless the
2339 	 * segment we received passes the SYN-RECEIVED ACK test.
2340 	 * If it fails send a RST.  This breaks the loop in the
2341 	 * "LAND" DoS attack, and also prevents an ACK storm
2342 	 * between two listening ports that have been sent forged
2343 	 * SYN segments, each with the source address of the other.
2344 	 */
2345 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2346 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2347 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2348 		rstreason = BANDLIM_RST_OPENPORT;
2349 		goto dropwithreset;
2350 	}
2351 #ifdef TCPDEBUG
2352 	if (so->so_options & SO_DEBUG)
2353 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2354 			  &tcp_savetcp, 0);
2355 #endif
2356 	m_freem(m);
2357 	tp->t_flags |= TF_ACKNOW;
2358 	(void) tcp_output(tp);
2359 	return;
2360 
2361 dropwithreset:
2362 	/*
2363 	 * Generate a RST, dropping incoming segment.
2364 	 * Make ACK acceptable to originator of segment.
2365 	 * Don't bother to respond if destination was broadcast/multicast.
2366 	 */
2367 	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2368 		goto drop;
2369 	if (isipv6) {
2370 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2371 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2372 			goto drop;
2373 	} else {
2374 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2375 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2376 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2377 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2378 			goto drop;
2379 	}
2380 	/* IPv6 anycast check is done at tcp6_input() */
2381 
2382 	/*
2383 	 * Perform bandwidth limiting.
2384 	 */
2385 #ifdef ICMP_BANDLIM
2386 	if (badport_bandlim(rstreason) < 0)
2387 		goto drop;
2388 #endif
2389 
2390 #ifdef TCPDEBUG
2391 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2392 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2393 			  &tcp_savetcp, 0);
2394 #endif
2395 	if (thflags & TH_ACK)
2396 		/* mtod() below is safe as long as hdr dropping is delayed */
2397 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2398 			    TH_RST);
2399 	else {
2400 		if (thflags & TH_SYN)
2401 			tlen++;
2402 		/* mtod() below is safe as long as hdr dropping is delayed */
2403 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2404 			    (tcp_seq)0, TH_RST|TH_ACK);
2405 	}
2406 	return;
2407 
2408 drop:
2409 	/*
2410 	 * Drop space held by incoming segment and return.
2411 	 */
2412 #ifdef TCPDEBUG
2413 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2414 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2415 			  &tcp_savetcp, 0);
2416 #endif
2417 	m_freem(m);
2418 	return;
2419 }
2420 
2421 /*
2422  * Parse TCP options and place in tcpopt.
2423  */
2424 static void
2425 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2426 {
2427 	int opt, optlen;
2428 
2429 	to->to_flags = 0;
2430 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2431 		opt = cp[0];
2432 		if (opt == TCPOPT_EOL)
2433 			break;
2434 		if (opt == TCPOPT_NOP)
2435 			optlen = 1;
2436 		else {
2437 			if (cnt < 2)
2438 				break;
2439 			optlen = cp[1];
2440 			if (optlen < 2 || optlen > cnt)
2441 				break;
2442 		}
2443 		switch (opt) {
2444 		case TCPOPT_MAXSEG:
2445 			if (optlen != TCPOLEN_MAXSEG)
2446 				continue;
2447 			if (!is_syn)
2448 				continue;
2449 			to->to_flags |= TOF_MSS;
2450 			bcopy(cp + 2, &to->to_mss, sizeof(to->to_mss));
2451 			to->to_mss = ntohs(to->to_mss);
2452 			break;
2453 		case TCPOPT_WINDOW:
2454 			if (optlen != TCPOLEN_WINDOW)
2455 				continue;
2456 			if (!is_syn)
2457 				continue;
2458 			to->to_flags |= TOF_SCALE;
2459 			to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2460 			break;
2461 		case TCPOPT_TIMESTAMP:
2462 			if (optlen != TCPOLEN_TIMESTAMP)
2463 				continue;
2464 			to->to_flags |= TOF_TS;
2465 			bcopy(cp + 2, &to->to_tsval, sizeof(to->to_tsval));
2466 			to->to_tsval = ntohl(to->to_tsval);
2467 			bcopy(cp + 6, &to->to_tsecr, sizeof(to->to_tsecr));
2468 			to->to_tsecr = ntohl(to->to_tsecr);
2469 			break;
2470 		case TCPOPT_CC:
2471 			if (optlen != TCPOLEN_CC)
2472 				continue;
2473 			to->to_flags |= TOF_CC;
2474 			bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
2475 			to->to_cc = ntohl(to->to_cc);
2476 			break;
2477 		case TCPOPT_CCNEW:
2478 			if (optlen != TCPOLEN_CC)
2479 				continue;
2480 			if (!is_syn)
2481 				continue;
2482 			to->to_flags |= TOF_CCNEW;
2483 			bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
2484 			to->to_cc = ntohl(to->to_cc);
2485 			break;
2486 		case TCPOPT_CCECHO:
2487 			if (optlen != TCPOLEN_CC)
2488 				continue;
2489 			if (!is_syn)
2490 				continue;
2491 			to->to_flags |= TOF_CCECHO;
2492 			bcopy(cp + 2, &to->to_ccecho, sizeof(to->to_ccecho));
2493 			to->to_ccecho = ntohl(to->to_ccecho);
2494 			break;
2495 		default:
2496 			continue;
2497 		}
2498 	}
2499 }
2500 
2501 /*
2502  * Pull out of band byte out of a segment so
2503  * it doesn't appear in the user's data queue.
2504  * It is still reflected in the segment length for
2505  * sequencing purposes.
2506  * "off" is the delayed to be dropped hdrlen.
2507  */
2508 static void
2509 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2510 {
2511 	int cnt = off + th->th_urp - 1;
2512 
2513 	while (cnt >= 0) {
2514 		if (m->m_len > cnt) {
2515 			char *cp = mtod(m, caddr_t) + cnt;
2516 			struct tcpcb *tp = sototcpcb(so);
2517 
2518 			tp->t_iobc = *cp;
2519 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2520 			bcopy(cp + 1, cp, m->m_len - cnt - 1);
2521 			m->m_len--;
2522 			if (m->m_flags & M_PKTHDR)
2523 				m->m_pkthdr.len--;
2524 			return;
2525 		}
2526 		cnt -= m->m_len;
2527 		m = m->m_next;
2528 		if (m == 0)
2529 			break;
2530 	}
2531 	panic("tcp_pulloutofband");
2532 }
2533 
2534 /*
2535  * Collect new round-trip time estimate
2536  * and update averages and current timeout.
2537  */
2538 static void
2539 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2540 {
2541 	int delta;
2542 
2543 	tcpstat.tcps_rttupdated++;
2544 	tp->t_rttupdated++;
2545 	if (tp->t_srtt != 0) {
2546 		/*
2547 		 * srtt is stored as fixed point with 5 bits after the
2548 		 * binary point (i.e., scaled by 8).  The following magic
2549 		 * is equivalent to the smoothing algorithm in rfc793 with
2550 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2551 		 * point).  Adjust rtt to origin 0.
2552 		 */
2553 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2554 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2555 
2556 		if ((tp->t_srtt += delta) <= 0)
2557 			tp->t_srtt = 1;
2558 
2559 		/*
2560 		 * We accumulate a smoothed rtt variance (actually, a
2561 		 * smoothed mean difference), then set the retransmit
2562 		 * timer to smoothed rtt + 4 times the smoothed variance.
2563 		 * rttvar is stored as fixed point with 4 bits after the
2564 		 * binary point (scaled by 16).  The following is
2565 		 * equivalent to rfc793 smoothing with an alpha of .75
2566 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2567 		 * rfc793's wired-in beta.
2568 		 */
2569 		if (delta < 0)
2570 			delta = -delta;
2571 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2572 		if ((tp->t_rttvar += delta) <= 0)
2573 			tp->t_rttvar = 1;
2574 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2575 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2576 	} else {
2577 		/*
2578 		 * No rtt measurement yet - use the unsmoothed rtt.
2579 		 * Set the variance to half the rtt (so our first
2580 		 * retransmit happens at 3*rtt).
2581 		 */
2582 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2583 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2584 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2585 	}
2586 	tp->t_rtttime = 0;
2587 	tp->t_rxtshift = 0;
2588 
2589 	/*
2590 	 * the retransmit should happen at rtt + 4 * rttvar.
2591 	 * Because of the way we do the smoothing, srtt and rttvar
2592 	 * will each average +1/2 tick of bias.  When we compute
2593 	 * the retransmit timer, we want 1/2 tick of rounding and
2594 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2595 	 * firing of the timer.  The bias will give us exactly the
2596 	 * 1.5 tick we need.  But, because the bias is
2597 	 * statistical, we have to test that we don't drop below
2598 	 * the minimum feasible timer (which is 2 ticks).
2599 	 */
2600 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2601 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2602 
2603 	/*
2604 	 * We received an ack for a packet that wasn't retransmitted;
2605 	 * it is probably safe to discard any error indications we've
2606 	 * received recently.  This isn't quite right, but close enough
2607 	 * for now (a route might have failed after we sent a segment,
2608 	 * and the return path might not be symmetrical).
2609 	 */
2610 	tp->t_softerror = 0;
2611 }
2612 
2613 /*
2614  * Determine a reasonable value for maxseg size.
2615  * If the route is known, check route for mtu.
2616  * If none, use an mss that can be handled on the outgoing
2617  * interface without forcing IP to fragment; if bigger than
2618  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2619  * to utilize large mbufs.  If no route is found, route has no mtu,
2620  * or the destination isn't local, use a default, hopefully conservative
2621  * size (usually 512 or the default IP max size, but no more than the mtu
2622  * of the interface), as we can't discover anything about intervening
2623  * gateways or networks.  We also initialize the congestion/slow start
2624  * window to be a single segment if the destination isn't local.
2625  * While looking at the routing entry, we also initialize other path-dependent
2626  * parameters from pre-set or cached values in the routing entry.
2627  *
2628  * Also take into account the space needed for options that we
2629  * send regularly.  Make maxseg shorter by that amount to assure
2630  * that we can send maxseg amount of data even when the options
2631  * are present.  Store the upper limit of the length of options plus
2632  * data in maxopd.
2633  *
2634  * NOTE that this routine is only called when we process an incoming
2635  * segment, for outgoing segments only tcp_mssopt is called.
2636  *
2637  * In case of T/TCP, we call this routine during implicit connection
2638  * setup as well (offer = -1), to initialize maxseg from the cached
2639  * MSS of our peer.
2640  */
2641 void
2642 tcp_mss(struct tcpcb *tp, int offer)
2643 {
2644 	struct rtentry *rt;
2645 	struct ifnet *ifp;
2646 	int rtt, mss;
2647 	u_long bufsize;
2648 	struct inpcb *inp = tp->t_inpcb;
2649 	struct socket *so;
2650 	struct rmxp_tao *taop;
2651 	int origoffer = offer;
2652 #ifdef INET6
2653 	boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2654 	size_t min_protoh = isipv6 ?
2655 			    sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2656 			    sizeof(struct tcpiphdr);
2657 #else
2658 	const boolean_t isipv6 = FALSE;
2659 	const size_t min_protoh = sizeof(struct tcpiphdr);
2660 #endif
2661 
2662 	if (isipv6)
2663 		rt = tcp_rtlookup6(&inp->inp_inc);
2664 	else
2665 		rt = tcp_rtlookup(&inp->inp_inc);
2666 	if (rt == NULL) {
2667 		tp->t_maxopd = tp->t_maxseg =
2668 		    (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2669 		return;
2670 	}
2671 	ifp = rt->rt_ifp;
2672 	so = inp->inp_socket;
2673 
2674 	taop = rmx_taop(rt->rt_rmx);
2675 	/*
2676 	 * Offer == -1 means that we didn't receive SYN yet,
2677 	 * use cached value in that case;
2678 	 */
2679 	if (offer == -1)
2680 		offer = taop->tao_mssopt;
2681 	/*
2682 	 * Offer == 0 means that there was no MSS on the SYN segment,
2683 	 * in this case we use tcp_mssdflt.
2684 	 */
2685 	if (offer == 0)
2686 		offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2687 	else
2688 		/*
2689 		 * Sanity check: make sure that maxopd will be large
2690 		 * enough to allow some data on segments even is the
2691 		 * all the option space is used (40bytes).  Otherwise
2692 		 * funny things may happen in tcp_output.
2693 		 */
2694 		offer = max(offer, 64);
2695 	taop->tao_mssopt = offer;
2696 
2697 	/*
2698 	 * While we're here, check if there's an initial rtt
2699 	 * or rttvar.  Convert from the route-table units
2700 	 * to scaled multiples of the slow timeout timer.
2701 	 */
2702 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2703 		/*
2704 		 * XXX the lock bit for RTT indicates that the value
2705 		 * is also a minimum value; this is subject to time.
2706 		 */
2707 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2708 			tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2709 		tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2710 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2711 		tcpstat.tcps_usedrtt++;
2712 		if (rt->rt_rmx.rmx_rttvar) {
2713 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2714 			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2715 			tcpstat.tcps_usedrttvar++;
2716 		} else {
2717 			/* default variation is +- 1 rtt */
2718 			tp->t_rttvar =
2719 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2720 		}
2721 		TCPT_RANGESET(tp->t_rxtcur,
2722 			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2723 			      tp->t_rttmin, TCPTV_REXMTMAX);
2724 	}
2725 	/*
2726 	 * if there's an mtu associated with the route, use it
2727 	 * else, use the link mtu.
2728 	 */
2729 	if (rt->rt_rmx.rmx_mtu)
2730 		mss = rt->rt_rmx.rmx_mtu - min_protoh;
2731 	else {
2732 		if (isipv6) {
2733 			mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2734 				min_protoh;
2735 			if (!in6_localaddr(&inp->in6p_faddr))
2736 				mss = min(mss, tcp_v6mssdflt);
2737 		} else {
2738 			mss = ifp->if_mtu - min_protoh;
2739 			if (!in_localaddr(inp->inp_faddr))
2740 				mss = min(mss, tcp_mssdflt);
2741 		}
2742 	}
2743 	mss = min(mss, offer);
2744 	/*
2745 	 * maxopd stores the maximum length of data AND options
2746 	 * in a segment; maxseg is the amount of data in a normal
2747 	 * segment.  We need to store this value (maxopd) apart
2748 	 * from maxseg, because now every segment carries options
2749 	 * and thus we normally have somewhat less data in segments.
2750 	 */
2751 	tp->t_maxopd = mss;
2752 
2753 	/*
2754 	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2755 	 * were received yet.  In this case we just guess, otherwise
2756 	 * we do the same as before T/TCP.
2757 	 */
2758 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2759 	    (origoffer == -1 ||
2760 	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2761 		mss -= TCPOLEN_TSTAMP_APPA;
2762 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2763 	    (origoffer == -1 ||
2764 	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2765 		mss -= TCPOLEN_CC_APPA;
2766 
2767 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
2768 		if (mss > MCLBYTES)
2769 			mss &= ~(MCLBYTES-1);
2770 #else
2771 		if (mss > MCLBYTES)
2772 			mss = mss / MCLBYTES * MCLBYTES;
2773 #endif
2774 	/*
2775 	 * If there's a pipesize, change the socket buffer
2776 	 * to that size.  Make the socket buffers an integral
2777 	 * number of mss units; if the mss is larger than
2778 	 * the socket buffer, decrease the mss.
2779 	 */
2780 #ifdef RTV_SPIPE
2781 	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2782 #endif
2783 		bufsize = so->so_snd.sb_hiwat;
2784 	if (bufsize < mss)
2785 		mss = bufsize;
2786 	else {
2787 		bufsize = roundup(bufsize, mss);
2788 		if (bufsize > sb_max)
2789 			bufsize = sb_max;
2790 		if (bufsize > so->so_snd.sb_hiwat)
2791 			(void)sbreserve(&so->so_snd, bufsize, so, NULL);
2792 	}
2793 	tp->t_maxseg = mss;
2794 
2795 #ifdef RTV_RPIPE
2796 	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2797 #endif
2798 		bufsize = so->so_rcv.sb_hiwat;
2799 	if (bufsize > mss) {
2800 		bufsize = roundup(bufsize, mss);
2801 		if (bufsize > sb_max)
2802 			bufsize = sb_max;
2803 		if (bufsize > so->so_rcv.sb_hiwat)
2804 			(void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2805 	}
2806 
2807 	/*
2808 	 * Set the slow-start flight size depending on whether this
2809 	 * is a local network or not.
2810 	 */
2811 	if (tcp_do_rfc3390)
2812 		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2813 	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2814 		 (!isipv6 && in_localaddr(inp->inp_faddr)))
2815 		tp->snd_cwnd = mss * ss_fltsz_local;
2816 	else
2817 		tp->snd_cwnd = mss * ss_fltsz;
2818 
2819 	if (rt->rt_rmx.rmx_ssthresh) {
2820 		/*
2821 		 * There's some sort of gateway or interface
2822 		 * buffer limit on the path.  Use this to set
2823 		 * the slow start threshhold, but set the
2824 		 * threshold to no less than 2*mss.
2825 		 */
2826 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2827 		tcpstat.tcps_usedssthresh++;
2828 	}
2829 }
2830 
2831 /*
2832  * Determine the MSS option to send on an outgoing SYN.
2833  */
2834 int
2835 tcp_mssopt(struct tcpcb *tp)
2836 {
2837 	struct rtentry *rt;
2838 #ifdef INET6
2839 	boolean_t isipv6 =
2840 	    ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2841 	int min_protoh = isipv6 ?
2842 			     sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2843 			     sizeof(struct tcpiphdr);
2844 #else
2845 	const boolean_t isipv6 = FALSE;
2846 	const size_t min_protoh = sizeof(struct tcpiphdr);
2847 #endif
2848 
2849 	if (isipv6)
2850 		rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2851 	else
2852 		rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2853 	if (rt == NULL)
2854 		return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2855 
2856 	return (rt->rt_ifp->if_mtu - min_protoh);
2857 }
2858 
2859 
2860 /*
2861  * When a partial ack arrives, force the retransmission of the
2862  * next unacknowledged segment.  Do not clear tp->t_dupacks.
2863  * By setting snd_nxt to ti_ack, this forces retransmission timer to
2864  * be started again.
2865  */
2866 static void
2867 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
2868 {
2869 	tcp_seq onxt = tp->snd_nxt;
2870 	u_long  ocwnd = tp->snd_cwnd;
2871 
2872 	callout_stop(tp->tt_rexmt);
2873 	tp->t_rtttime = 0;
2874 	tp->snd_nxt = th->th_ack;
2875 	/*
2876 	 * Set snd_cwnd to one segment beyond acknowledged offset
2877 	 * (tp->snd_una has not yet been updated when this function is called.)
2878 	 */
2879 	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2880 	tp->t_flags |= TF_ACKNOW;
2881 	(void) tcp_output(tp);
2882 	tp->snd_cwnd = ocwnd;
2883 	if (SEQ_GT(onxt, tp->snd_nxt))
2884 		tp->snd_nxt = onxt;
2885 	/*
2886 	 * Partial window deflation.  Relies on fact that tp->snd_una
2887 	 * not updated yet.
2888 	 */
2889 	tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2890 }
2891