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