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