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