xref: /freebsd/sys/netinet/tcp_reass.c (revision 2b743a9e9ddc6736208dc8ca1ce06ce64ad20a19)
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 		/* Initial send window, already scaled. */
1159 		tp->snd_wnd = th->th_win;
1160 		if (to.to_flags & TOF_MSS)
1161 			tcp_mss(tp, to.to_mss);
1162 		if (tp->sack_enable) {
1163 			if (!(to.to_flags & TOF_SACK))
1164 				tp->sack_enable = 0;
1165 			else
1166 				tp->t_flags |= TF_SACK_PERMIT;
1167 		}
1168 
1169 	}
1170 
1171 	/*
1172 	 * Header prediction: check for the two common cases
1173 	 * of a uni-directional data xfer.  If the packet has
1174 	 * no control flags, is in-sequence, the window didn't
1175 	 * change and we're not retransmitting, it's a
1176 	 * candidate.  If the length is zero and the ack moved
1177 	 * forward, we're the sender side of the xfer.  Just
1178 	 * free the data acked & wake any higher level process
1179 	 * that was blocked waiting for space.  If the length
1180 	 * is non-zero and the ack didn't move, we're the
1181 	 * receiver side.  If we're getting packets in-order
1182 	 * (the reassembly queue is empty), add the data to
1183 	 * the socket buffer and note that we need a delayed ack.
1184 	 * Make sure that the hidden state-flags are also off.
1185 	 * Since we check for TCPS_ESTABLISHED above, it can only
1186 	 * be TH_NEEDSYN.
1187 	 */
1188 	if (tp->t_state == TCPS_ESTABLISHED &&
1189 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1190 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1191 	    ((to.to_flags & TOF_TS) == 0 ||
1192 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1193 	     th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd &&
1194 	     tp->snd_nxt == tp->snd_max) {
1195 
1196 		/*
1197 		 * If last ACK falls within this segment's sequence numbers,
1198 		 * record the timestamp.
1199 		 * NOTE that the test is modified according to the latest
1200 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1201 		 */
1202 		if ((to.to_flags & TOF_TS) != 0 &&
1203 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1204 			tp->ts_recent_age = ticks;
1205 			tp->ts_recent = to.to_tsval;
1206 		}
1207 
1208 		if (tlen == 0) {
1209 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1210 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1211 			    tp->snd_cwnd >= tp->snd_wnd &&
1212 			    ((!tcp_do_newreno && !tp->sack_enable &&
1213 			      tp->t_dupacks < tcprexmtthresh) ||
1214 			     ((tcp_do_newreno || tp->sack_enable) &&
1215 			      !IN_FASTRECOVERY(tp) && to.to_nsacks == 0 &&
1216 			      TAILQ_EMPTY(&tp->snd_holes)))) {
1217 				KASSERT(headlocked, ("headlocked"));
1218 				INP_INFO_WUNLOCK(&tcbinfo);
1219 				headlocked = 0;
1220 				/*
1221 				 * this is a pure ack for outstanding data.
1222 				 */
1223 				++tcpstat.tcps_predack;
1224 				/*
1225 				 * "bad retransmit" recovery
1226 				 */
1227 				if (tp->t_rxtshift == 1 &&
1228 				    ticks < tp->t_badrxtwin) {
1229 					++tcpstat.tcps_sndrexmitbad;
1230 					tp->snd_cwnd = tp->snd_cwnd_prev;
1231 					tp->snd_ssthresh =
1232 					    tp->snd_ssthresh_prev;
1233 					tp->snd_recover = tp->snd_recover_prev;
1234 					if (tp->t_flags & TF_WASFRECOVERY)
1235 					    ENTER_FASTRECOVERY(tp);
1236 					tp->snd_nxt = tp->snd_max;
1237 					tp->t_badrxtwin = 0;
1238 				}
1239 
1240 				/*
1241 				 * Recalculate the transmit timer / rtt.
1242 				 *
1243 				 * Some boxes send broken timestamp replies
1244 				 * during the SYN+ACK phase, ignore
1245 				 * timestamps of 0 or we could calculate a
1246 				 * huge RTT and blow up the retransmit timer.
1247 				 */
1248 				if ((to.to_flags & TOF_TS) != 0 &&
1249 				    to.to_tsecr) {
1250 					if (!tp->t_rttlow ||
1251 					    tp->t_rttlow > ticks - to.to_tsecr)
1252 						tp->t_rttlow = ticks - to.to_tsecr;
1253 					tcp_xmit_timer(tp,
1254 					    ticks - to.to_tsecr + 1);
1255 				} else if (tp->t_rtttime &&
1256 					    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1257 					if (!tp->t_rttlow ||
1258 					    tp->t_rttlow > ticks - tp->t_rtttime)
1259 						tp->t_rttlow = ticks - tp->t_rtttime;
1260 					tcp_xmit_timer(tp,
1261 							ticks - tp->t_rtttime);
1262 				}
1263 				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1264 				acked = th->th_ack - tp->snd_una;
1265 				tcpstat.tcps_rcvackpack++;
1266 				tcpstat.tcps_rcvackbyte += acked;
1267 				sbdrop(&so->so_snd, acked);
1268 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1269 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1270 					tp->snd_recover = th->th_ack - 1;
1271 				tp->snd_una = th->th_ack;
1272 				/*
1273 				 * pull snd_wl2 up to prevent seq wrap relative
1274 				 * to th_ack.
1275 				 */
1276 				tp->snd_wl2 = th->th_ack;
1277 				tp->t_dupacks = 0;
1278 				m_freem(m);
1279 				ND6_HINT(tp); /* some progress has been done */
1280 
1281 				/*
1282 				 * If all outstanding data are acked, stop
1283 				 * retransmit timer, otherwise restart timer
1284 				 * using current (possibly backed-off) value.
1285 				 * If process is waiting for space,
1286 				 * wakeup/selwakeup/signal.  If data
1287 				 * are ready to send, let tcp_output
1288 				 * decide between more output or persist.
1289 
1290 #ifdef TCPDEBUG
1291 				if (so->so_options & SO_DEBUG)
1292 					tcp_trace(TA_INPUT, ostate, tp,
1293 					    (void *)tcp_saveipgen,
1294 					    &tcp_savetcp, 0);
1295 #endif
1296 				 */
1297 				if (tp->snd_una == tp->snd_max)
1298 					callout_stop(tp->tt_rexmt);
1299 				else if (!callout_active(tp->tt_persist))
1300 					callout_reset(tp->tt_rexmt,
1301 						      tp->t_rxtcur,
1302 						      tcp_timer_rexmt, tp);
1303 
1304 				sowwakeup(so);
1305 				if (so->so_snd.sb_cc)
1306 					(void) tcp_output(tp);
1307 				goto check_delack;
1308 			}
1309 		} else if (th->th_ack == tp->snd_una &&
1310 		    LIST_EMPTY(&tp->t_segq) &&
1311 		    tlen <= sbspace(&so->so_rcv)) {
1312 			int newsize = 0;	/* automatic sockbuf scaling */
1313 
1314 			KASSERT(headlocked, ("headlocked"));
1315 			INP_INFO_WUNLOCK(&tcbinfo);
1316 			headlocked = 0;
1317 			/*
1318 			 * this is a pure, in-sequence data packet
1319 			 * with nothing on the reassembly queue and
1320 			 * we have enough buffer space to take it.
1321 			 */
1322 			/* Clean receiver SACK report if present */
1323 			if (tp->sack_enable && tp->rcv_numsacks)
1324 				tcp_clean_sackreport(tp);
1325 			++tcpstat.tcps_preddat;
1326 			tp->rcv_nxt += tlen;
1327 			/*
1328 			 * Pull snd_wl1 up to prevent seq wrap relative to
1329 			 * th_seq.
1330 			 */
1331 			tp->snd_wl1 = th->th_seq;
1332 			/*
1333 			 * Pull rcv_up up to prevent seq wrap relative to
1334 			 * rcv_nxt.
1335 			 */
1336 			tp->rcv_up = tp->rcv_nxt;
1337 			tcpstat.tcps_rcvpack++;
1338 			tcpstat.tcps_rcvbyte += tlen;
1339 			ND6_HINT(tp);	/* some progress has been done */
1340 #ifdef TCPDEBUG
1341 			if (so->so_options & SO_DEBUG)
1342 				tcp_trace(TA_INPUT, ostate, tp,
1343 				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
1344 #endif
1345 		/*
1346 		 * Automatic sizing of receive socket buffer.  Often the send
1347 		 * buffer size is not optimally adjusted to the actual network
1348 		 * conditions at hand (delay bandwidth product).  Setting the
1349 		 * buffer size too small limits throughput on links with high
1350 		 * bandwidth and high delay (eg. trans-continental/oceanic links).
1351 		 *
1352 		 * On the receive side the socket buffer memory is only rarely
1353 		 * used to any significant extent.  This allows us to be much
1354 		 * more aggressive in scaling the receive socket buffer.  For
1355 		 * the case that the buffer space is actually used to a large
1356 		 * extent and we run out of kernel memory we can simply drop
1357 		 * the new segments; TCP on the sender will just retransmit it
1358 		 * later.  Setting the buffer size too big may only consume too
1359 		 * much kernel memory if the application doesn't read() from
1360 		 * the socket or packet loss or reordering makes use of the
1361 		 * reassembly queue.
1362 		 *
1363 		 * The criteria to step up the receive buffer one notch are:
1364 		 *  1. the number of bytes received during the time it takes
1365 		 *     one timestamp to be reflected back to us (the RTT);
1366 		 *  2. received bytes per RTT is within seven eighth of the
1367 		 *     current socket buffer size;
1368 		 *  3. receive buffer size has not hit maximal automatic size;
1369 		 *
1370 		 * This algorithm does one step per RTT at most and only if
1371 		 * we receive a bulk stream w/o packet losses or reorderings.
1372 		 * Shrinking the buffer during idle times is not necessary as
1373 		 * it doesn't consume any memory when idle.
1374 		 *
1375 		 * TODO: Only step up if the application is actually serving
1376 		 * the buffer to better manage the socket buffer resources.
1377 		 */
1378 			if (tcp_do_autorcvbuf &&
1379 			    to.to_tsecr &&
1380 			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1381 				if (to.to_tsecr > tp->rfbuf_ts &&
1382 				    to.to_tsecr - tp->rfbuf_ts < hz) {
1383 					if (tp->rfbuf_cnt >
1384 					    (so->so_rcv.sb_hiwat / 8 * 7) &&
1385 					    so->so_rcv.sb_hiwat <
1386 					    tcp_autorcvbuf_max) {
1387 						newsize =
1388 						    min(so->so_rcv.sb_hiwat +
1389 						    tcp_autorcvbuf_inc,
1390 						    tcp_autorcvbuf_max);
1391 					}
1392 					/* Start over with next RTT. */
1393 					tp->rfbuf_ts = 0;
1394 					tp->rfbuf_cnt = 0;
1395 				} else
1396 					tp->rfbuf_cnt += tlen;	/* add up */
1397 			}
1398 
1399 			/* Add data to socket buffer. */
1400 			SOCKBUF_LOCK(&so->so_rcv);
1401 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1402 				m_freem(m);
1403 			} else {
1404 				/*
1405 				 * Set new socket buffer size.
1406 				 * Give up when limit is reached.
1407 				 */
1408 				if (newsize)
1409 					if (!sbreserve_locked(&so->so_rcv,
1410 					    newsize, so, curthread))
1411 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1412 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1413 				sbappendstream_locked(&so->so_rcv, m);
1414 			}
1415 			sorwakeup_locked(so);
1416 			if (DELAY_ACK(tp)) {
1417 				tp->t_flags |= TF_DELACK;
1418 			} else {
1419 				tp->t_flags |= TF_ACKNOW;
1420 				tcp_output(tp);
1421 			}
1422 			goto check_delack;
1423 		}
1424 	}
1425 
1426 	/*
1427 	 * Calculate amount of space in receive window,
1428 	 * and then do TCP input processing.
1429 	 * Receive window is amount of space in rcv queue,
1430 	 * but not less than advertised window.
1431 	 */
1432 	{ int win;
1433 
1434 	win = sbspace(&so->so_rcv);
1435 	if (win < 0)
1436 		win = 0;
1437 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1438 	}
1439 
1440 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
1441 	tp->rfbuf_ts = 0;
1442 	tp->rfbuf_cnt = 0;
1443 
1444 	switch (tp->t_state) {
1445 
1446 	/*
1447 	 * If the state is SYN_RECEIVED:
1448 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1449 	 */
1450 	case TCPS_SYN_RECEIVED:
1451 		if ((thflags & TH_ACK) &&
1452 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1453 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1454 				rstreason = BANDLIM_RST_OPENPORT;
1455 				goto dropwithreset;
1456 		}
1457 		break;
1458 
1459 	/*
1460 	 * If the state is SYN_SENT:
1461 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1462 	 *	if seg contains a RST, then drop the connection.
1463 	 *	if seg does not contain SYN, then drop it.
1464 	 * Otherwise this is an acceptable SYN segment
1465 	 *	initialize tp->rcv_nxt and tp->irs
1466 	 *	if seg contains ack then advance tp->snd_una
1467 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1468 	 *	arrange for segment to be acked (eventually)
1469 	 *	continue processing rest of data/controls, beginning with URG
1470 	 */
1471 	case TCPS_SYN_SENT:
1472 		if ((thflags & TH_ACK) &&
1473 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1474 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1475 			rstreason = BANDLIM_UNLIMITED;
1476 			goto dropwithreset;
1477 		}
1478 		if (thflags & TH_RST) {
1479 			if (thflags & TH_ACK) {
1480 				KASSERT(headlocked, ("tcp_input: after_listen"
1481 				    ": tcp_drop.2: head not locked"));
1482 				tp = tcp_drop(tp, ECONNREFUSED);
1483 			}
1484 			goto drop;
1485 		}
1486 		if ((thflags & TH_SYN) == 0)
1487 			goto drop;
1488 
1489 		tp->irs = th->th_seq;
1490 		tcp_rcvseqinit(tp);
1491 		if (thflags & TH_ACK) {
1492 			tcpstat.tcps_connects++;
1493 			soisconnected(so);
1494 #ifdef MAC
1495 			SOCK_LOCK(so);
1496 			mac_set_socket_peer_from_mbuf(m, so);
1497 			SOCK_UNLOCK(so);
1498 #endif
1499 			/* Do window scaling on this connection? */
1500 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1501 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1502 				tp->rcv_scale = tp->request_r_scale;
1503 			}
1504 			tp->rcv_adv += tp->rcv_wnd;
1505 			tp->snd_una++;		/* SYN is acked */
1506 			/*
1507 			 * If there's data, delay ACK; if there's also a FIN
1508 			 * ACKNOW will be turned on later.
1509 			 */
1510 			if (DELAY_ACK(tp) && tlen != 0)
1511 				callout_reset(tp->tt_delack, tcp_delacktime,
1512 				    tcp_timer_delack, tp);
1513 			else
1514 				tp->t_flags |= TF_ACKNOW;
1515 			/*
1516 			 * Received <SYN,ACK> in SYN_SENT[*] state.
1517 			 * Transitions:
1518 			 *	SYN_SENT  --> ESTABLISHED
1519 			 *	SYN_SENT* --> FIN_WAIT_1
1520 			 */
1521 			tp->t_starttime = ticks;
1522 			if (tp->t_flags & TF_NEEDFIN) {
1523 				tp->t_state = TCPS_FIN_WAIT_1;
1524 				tp->t_flags &= ~TF_NEEDFIN;
1525 				thflags &= ~TH_SYN;
1526 			} else {
1527 				tp->t_state = TCPS_ESTABLISHED;
1528 				callout_reset(tp->tt_keep, tcp_keepidle,
1529 					      tcp_timer_keep, tp);
1530 			}
1531 		} else {
1532 			/*
1533 			 * Received initial SYN in SYN-SENT[*] state =>
1534 			 * simultaneous open.  If segment contains CC option
1535 			 * and there is a cached CC, apply TAO test.
1536 			 * If it succeeds, connection is * half-synchronized.
1537 			 * Otherwise, do 3-way handshake:
1538 			 *        SYN-SENT -> SYN-RECEIVED
1539 			 *        SYN-SENT* -> SYN-RECEIVED*
1540 			 * If there was no CC option, clear cached CC value.
1541 			 */
1542 			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1543 			callout_stop(tp->tt_rexmt);
1544 			tp->t_state = TCPS_SYN_RECEIVED;
1545 		}
1546 
1547 #if 0 /* T/TCP */
1548 trimthenstep6:
1549 #endif
1550 		KASSERT(headlocked, ("tcp_input: trimthenstep6: head not "
1551 		    "locked"));
1552 		INP_LOCK_ASSERT(inp);
1553 
1554 		/*
1555 		 * Advance th->th_seq to correspond to first data byte.
1556 		 * If data, trim to stay within window,
1557 		 * dropping FIN if necessary.
1558 		 */
1559 		th->th_seq++;
1560 		if (tlen > tp->rcv_wnd) {
1561 			todrop = tlen - tp->rcv_wnd;
1562 			m_adj(m, -todrop);
1563 			tlen = tp->rcv_wnd;
1564 			thflags &= ~TH_FIN;
1565 			tcpstat.tcps_rcvpackafterwin++;
1566 			tcpstat.tcps_rcvbyteafterwin += todrop;
1567 		}
1568 		tp->snd_wl1 = th->th_seq - 1;
1569 		tp->rcv_up = th->th_seq;
1570 		/*
1571 		 * Client side of transaction: already sent SYN and data.
1572 		 * If the remote host used T/TCP to validate the SYN,
1573 		 * our data will be ACK'd; if so, enter normal data segment
1574 		 * processing in the middle of step 5, ack processing.
1575 		 * Otherwise, goto step 6.
1576 		 */
1577 		if (thflags & TH_ACK)
1578 			goto process_ACK;
1579 
1580 		goto step6;
1581 
1582 	/*
1583 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1584 	 *      do normal processing.
1585 	 *
1586 	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
1587 	 */
1588 	case TCPS_LAST_ACK:
1589 	case TCPS_CLOSING:
1590 	case TCPS_TIME_WAIT:
1591 		KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1592 		break;  /* continue normal processing */
1593 	}
1594 
1595 	/*
1596 	 * States other than LISTEN or SYN_SENT.
1597 	 * First check the RST flag and sequence number since reset segments
1598 	 * are exempt from the timestamp and connection count tests.  This
1599 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1600 	 * below which allowed reset segments in half the sequence space
1601 	 * to fall though and be processed (which gives forged reset
1602 	 * segments with a random sequence number a 50 percent chance of
1603 	 * killing a connection).
1604 	 * Then check timestamp, if present.
1605 	 * Then check the connection count, if present.
1606 	 * Then check that at least some bytes of segment are within
1607 	 * receive window.  If segment begins before rcv_nxt,
1608 	 * drop leading data (and SYN); if nothing left, just ack.
1609 	 *
1610 	 *
1611 	 * If the RST bit is set, check the sequence number to see
1612 	 * if this is a valid reset segment.
1613 	 * RFC 793 page 37:
1614 	 *   In all states except SYN-SENT, all reset (RST) segments
1615 	 *   are validated by checking their SEQ-fields.  A reset is
1616 	 *   valid if its sequence number is in the window.
1617 	 * Note: this does not take into account delayed ACKs, so
1618 	 *   we should test against last_ack_sent instead of rcv_nxt.
1619 	 *   The sequence number in the reset segment is normally an
1620 	 *   echo of our outgoing acknowlegement numbers, but some hosts
1621 	 *   send a reset with the sequence number at the rightmost edge
1622 	 *   of our receive window, and we have to handle this case.
1623 	 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1624 	 *   that brute force RST attacks are possible.  To combat this,
1625 	 *   we use a much stricter check while in the ESTABLISHED state,
1626 	 *   only accepting RSTs where the sequence number is equal to
1627 	 *   last_ack_sent.  In all other states (the states in which a
1628 	 *   RST is more likely), the more permissive check is used.
1629 	 * If we have multiple segments in flight, the intial reset
1630 	 * segment sequence numbers will be to the left of last_ack_sent,
1631 	 * but they will eventually catch up.
1632 	 * In any case, it never made sense to trim reset segments to
1633 	 * fit the receive window since RFC 1122 says:
1634 	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1635 	 *
1636 	 *    A TCP SHOULD allow a received RST segment to include data.
1637 	 *
1638 	 *    DISCUSSION
1639 	 *         It has been suggested that a RST segment could contain
1640 	 *         ASCII text that encoded and explained the cause of the
1641 	 *         RST.  No standard has yet been established for such
1642 	 *         data.
1643 	 *
1644 	 * If the reset segment passes the sequence number test examine
1645 	 * the state:
1646 	 *    SYN_RECEIVED STATE:
1647 	 *	If passive open, return to LISTEN state.
1648 	 *	If active open, inform user that connection was refused.
1649 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1650 	 *	Inform user that connection was reset, and close tcb.
1651 	 *    CLOSING, LAST_ACK STATES:
1652 	 *	Close the tcb.
1653 	 *    TIME_WAIT STATE:
1654 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1655 	 *      RFC 1337.
1656 	 */
1657 	if (thflags & TH_RST) {
1658 		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1659 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
1660 		    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
1661 			switch (tp->t_state) {
1662 
1663 			case TCPS_SYN_RECEIVED:
1664 				so->so_error = ECONNREFUSED;
1665 				goto close;
1666 
1667 			case TCPS_ESTABLISHED:
1668 				if (tp->last_ack_sent != th->th_seq &&
1669 			 	    tcp_insecure_rst == 0) {
1670 					tcpstat.tcps_badrst++;
1671 					goto drop;
1672 				}
1673 			case TCPS_FIN_WAIT_1:
1674 			case TCPS_FIN_WAIT_2:
1675 			case TCPS_CLOSE_WAIT:
1676 				so->so_error = ECONNRESET;
1677 			close:
1678 				tp->t_state = TCPS_CLOSED;
1679 				tcpstat.tcps_drops++;
1680 				KASSERT(headlocked, ("tcp_input: "
1681 				    "trimthenstep6: tcp_close: head not "
1682 				    "locked"));
1683 				tp = tcp_close(tp);
1684 				break;
1685 
1686 			case TCPS_CLOSING:
1687 			case TCPS_LAST_ACK:
1688 				KASSERT(headlocked, ("trimthenstep6: "
1689 				    "tcp_close.2: head not locked"));
1690 				tp = tcp_close(tp);
1691 				break;
1692 
1693 			case TCPS_TIME_WAIT:
1694 				KASSERT(tp->t_state != TCPS_TIME_WAIT,
1695 				    ("timewait"));
1696 				break;
1697 			}
1698 		}
1699 		goto drop;
1700 	}
1701 
1702 	/*
1703 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1704 	 * and it's less than ts_recent, drop it.
1705 	 */
1706 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1707 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1708 
1709 		/* Check to see if ts_recent is over 24 days old.  */
1710 		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1711 			/*
1712 			 * Invalidate ts_recent.  If this segment updates
1713 			 * ts_recent, the age will be reset later and ts_recent
1714 			 * will get a valid value.  If it does not, setting
1715 			 * ts_recent to zero will at least satisfy the
1716 			 * requirement that zero be placed in the timestamp
1717 			 * echo reply when ts_recent isn't valid.  The
1718 			 * age isn't reset until we get a valid ts_recent
1719 			 * because we don't want out-of-order segments to be
1720 			 * dropped when ts_recent is old.
1721 			 */
1722 			tp->ts_recent = 0;
1723 		} else {
1724 			tcpstat.tcps_rcvduppack++;
1725 			tcpstat.tcps_rcvdupbyte += tlen;
1726 			tcpstat.tcps_pawsdrop++;
1727 			if (tlen)
1728 				goto dropafterack;
1729 			goto drop;
1730 		}
1731 	}
1732 
1733 	/*
1734 	 * In the SYN-RECEIVED state, validate that the packet belongs to
1735 	 * this connection before trimming the data to fit the receive
1736 	 * window.  Check the sequence number versus IRS since we know
1737 	 * the sequence numbers haven't wrapped.  This is a partial fix
1738 	 * for the "LAND" DoS attack.
1739 	 */
1740 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1741 		rstreason = BANDLIM_RST_OPENPORT;
1742 		goto dropwithreset;
1743 	}
1744 
1745 	todrop = tp->rcv_nxt - th->th_seq;
1746 	if (todrop > 0) {
1747 		if (thflags & TH_SYN) {
1748 			thflags &= ~TH_SYN;
1749 			th->th_seq++;
1750 			if (th->th_urp > 1)
1751 				th->th_urp--;
1752 			else
1753 				thflags &= ~TH_URG;
1754 			todrop--;
1755 		}
1756 		/*
1757 		 * Following if statement from Stevens, vol. 2, p. 960.
1758 		 */
1759 		if (todrop > tlen
1760 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1761 			/*
1762 			 * Any valid FIN must be to the left of the window.
1763 			 * At this point the FIN must be a duplicate or out
1764 			 * of sequence; drop it.
1765 			 */
1766 			thflags &= ~TH_FIN;
1767 
1768 			/*
1769 			 * Send an ACK to resynchronize and drop any data.
1770 			 * But keep on processing for RST or ACK.
1771 			 */
1772 			tp->t_flags |= TF_ACKNOW;
1773 			todrop = tlen;
1774 			tcpstat.tcps_rcvduppack++;
1775 			tcpstat.tcps_rcvdupbyte += todrop;
1776 		} else {
1777 			tcpstat.tcps_rcvpartduppack++;
1778 			tcpstat.tcps_rcvpartdupbyte += todrop;
1779 		}
1780 		drop_hdrlen += todrop;	/* drop from the top afterwards */
1781 		th->th_seq += todrop;
1782 		tlen -= todrop;
1783 		if (th->th_urp > todrop)
1784 			th->th_urp -= todrop;
1785 		else {
1786 			thflags &= ~TH_URG;
1787 			th->th_urp = 0;
1788 		}
1789 	}
1790 
1791 	/*
1792 	 * If new data are received on a connection after the
1793 	 * user processes are gone, then RST the other end.
1794 	 */
1795 	if ((so->so_state & SS_NOFDREF) &&
1796 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1797 		KASSERT(headlocked, ("trimthenstep6: tcp_close.3: head not "
1798 		    "locked"));
1799 		tp = tcp_close(tp);
1800 		tcpstat.tcps_rcvafterclose++;
1801 		rstreason = BANDLIM_UNLIMITED;
1802 		goto dropwithreset;
1803 	}
1804 
1805 	/*
1806 	 * If segment ends after window, drop trailing data
1807 	 * (and PUSH and FIN); if nothing left, just ACK.
1808 	 */
1809 	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1810 	if (todrop > 0) {
1811 		tcpstat.tcps_rcvpackafterwin++;
1812 		if (todrop >= tlen) {
1813 			tcpstat.tcps_rcvbyteafterwin += tlen;
1814 			/*
1815 			 * If a new connection request is received
1816 			 * while in TIME_WAIT, drop the old connection
1817 			 * and start over if the sequence numbers
1818 			 * are above the previous ones.
1819 			 */
1820 			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1821 			if (thflags & TH_SYN &&
1822 			    tp->t_state == TCPS_TIME_WAIT &&
1823 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1824 				KASSERT(headlocked, ("trimthenstep6: "
1825 				    "tcp_close.4: head not locked"));
1826 				tp = tcp_close(tp);
1827 				goto findpcb;
1828 			}
1829 			/*
1830 			 * If window is closed can only take segments at
1831 			 * window edge, and have to drop data and PUSH from
1832 			 * incoming segments.  Continue processing, but
1833 			 * remember to ack.  Otherwise, drop segment
1834 			 * and ack.
1835 			 */
1836 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1837 				tp->t_flags |= TF_ACKNOW;
1838 				tcpstat.tcps_rcvwinprobe++;
1839 			} else
1840 				goto dropafterack;
1841 		} else
1842 			tcpstat.tcps_rcvbyteafterwin += todrop;
1843 		m_adj(m, -todrop);
1844 		tlen -= todrop;
1845 		thflags &= ~(TH_PUSH|TH_FIN);
1846 	}
1847 
1848 	/*
1849 	 * If last ACK falls within this segment's sequence numbers,
1850 	 * record its timestamp.
1851 	 * NOTE:
1852 	 * 1) That the test incorporates suggestions from the latest
1853 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
1854 	 * 2) That updating only on newer timestamps interferes with
1855 	 *    our earlier PAWS tests, so this check should be solely
1856 	 *    predicated on the sequence space of this segment.
1857 	 * 3) That we modify the segment boundary check to be
1858 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
1859 	 *    instead of RFC1323's
1860 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
1861 	 *    This modified check allows us to overcome RFC1323's
1862 	 *    limitations as described in Stevens TCP/IP Illustrated
1863 	 *    Vol. 2 p.869. In such cases, we can still calculate the
1864 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
1865 	 */
1866 	if ((to.to_flags & TOF_TS) != 0 &&
1867 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1868 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1869 		((thflags & (TH_SYN|TH_FIN)) != 0))) {
1870 		tp->ts_recent_age = ticks;
1871 		tp->ts_recent = to.to_tsval;
1872 	}
1873 
1874 	/*
1875 	 * If a SYN is in the window, then this is an
1876 	 * error and we send an RST and drop the connection.
1877 	 */
1878 	if (thflags & TH_SYN) {
1879 		KASSERT(headlocked, ("tcp_input: tcp_drop: trimthenstep6: "
1880 		    "head not locked"));
1881 		tp = tcp_drop(tp, ECONNRESET);
1882 		rstreason = BANDLIM_UNLIMITED;
1883 		goto drop;
1884 	}
1885 
1886 	/*
1887 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1888 	 * flag is on (half-synchronized state), then queue data for
1889 	 * later processing; else drop segment and return.
1890 	 */
1891 	if ((thflags & TH_ACK) == 0) {
1892 		if (tp->t_state == TCPS_SYN_RECEIVED ||
1893 		    (tp->t_flags & TF_NEEDSYN))
1894 			goto step6;
1895 		else if (tp->t_flags & TF_ACKNOW)
1896 			goto dropafterack;
1897 		else
1898 			goto drop;
1899 	}
1900 
1901 	/*
1902 	 * Ack processing.
1903 	 */
1904 	switch (tp->t_state) {
1905 
1906 	/*
1907 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1908 	 * ESTABLISHED state and continue processing.
1909 	 * The ACK was checked above.
1910 	 */
1911 	case TCPS_SYN_RECEIVED:
1912 
1913 		tcpstat.tcps_connects++;
1914 		soisconnected(so);
1915 		/* Do window scaling? */
1916 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1917 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1918 			tp->rcv_scale = tp->request_r_scale;
1919 			tp->snd_wnd = tiwin;
1920 		}
1921 		/*
1922 		 * Make transitions:
1923 		 *      SYN-RECEIVED  -> ESTABLISHED
1924 		 *      SYN-RECEIVED* -> FIN-WAIT-1
1925 		 */
1926 		tp->t_starttime = ticks;
1927 		if (tp->t_flags & TF_NEEDFIN) {
1928 			tp->t_state = TCPS_FIN_WAIT_1;
1929 			tp->t_flags &= ~TF_NEEDFIN;
1930 		} else {
1931 			tp->t_state = TCPS_ESTABLISHED;
1932 			callout_reset(tp->tt_keep, tcp_keepidle,
1933 				      tcp_timer_keep, tp);
1934 		}
1935 		/*
1936 		 * If segment contains data or ACK, will call tcp_reass()
1937 		 * later; if not, do so now to pass queued data to user.
1938 		 */
1939 		if (tlen == 0 && (thflags & TH_FIN) == 0)
1940 			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1941 			    (struct mbuf *)0);
1942 		tp->snd_wl1 = th->th_seq - 1;
1943 		/* FALLTHROUGH */
1944 
1945 	/*
1946 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1947 	 * ACKs.  If the ack is in the range
1948 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1949 	 * then advance tp->snd_una to th->th_ack and drop
1950 	 * data from the retransmission queue.  If this ACK reflects
1951 	 * more up to date window information we update our window information.
1952 	 */
1953 	case TCPS_ESTABLISHED:
1954 	case TCPS_FIN_WAIT_1:
1955 	case TCPS_FIN_WAIT_2:
1956 	case TCPS_CLOSE_WAIT:
1957 	case TCPS_CLOSING:
1958 	case TCPS_LAST_ACK:
1959 	case TCPS_TIME_WAIT:
1960 		KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1961 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1962 			tcpstat.tcps_rcvacktoomuch++;
1963 			goto dropafterack;
1964 		}
1965 		if (tp->sack_enable &&
1966 		    (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes)))
1967 			tcp_sack_doack(tp, &to, th->th_ack);
1968 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1969 			if (tlen == 0 && tiwin == tp->snd_wnd) {
1970 				tcpstat.tcps_rcvdupack++;
1971 				/*
1972 				 * If we have outstanding data (other than
1973 				 * a window probe), this is a completely
1974 				 * duplicate ack (ie, window info didn't
1975 				 * change), the ack is the biggest we've
1976 				 * seen and we've seen exactly our rexmt
1977 				 * threshhold of them, assume a packet
1978 				 * has been dropped and retransmit it.
1979 				 * Kludge snd_nxt & the congestion
1980 				 * window so we send only this one
1981 				 * packet.
1982 				 *
1983 				 * We know we're losing at the current
1984 				 * window size so do congestion avoidance
1985 				 * (set ssthresh to half the current window
1986 				 * and pull our congestion window back to
1987 				 * the new ssthresh).
1988 				 *
1989 				 * Dup acks mean that packets have left the
1990 				 * network (they're now cached at the receiver)
1991 				 * so bump cwnd by the amount in the receiver
1992 				 * to keep a constant cwnd packets in the
1993 				 * network.
1994 				 */
1995 				if (!callout_active(tp->tt_rexmt) ||
1996 				    th->th_ack != tp->snd_una)
1997 					tp->t_dupacks = 0;
1998 				else if (++tp->t_dupacks > tcprexmtthresh ||
1999 					 ((tcp_do_newreno || tp->sack_enable) &&
2000 					  IN_FASTRECOVERY(tp))) {
2001                                         if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
2002 						int awnd;
2003 
2004 						/*
2005 						 * Compute the amount of data in flight first.
2006 						 * We can inject new data into the pipe iff
2007 						 * we have less than 1/2 the original window's
2008 						 * worth of data in flight.
2009 						 */
2010 						awnd = (tp->snd_nxt - tp->snd_fack) +
2011 							tp->sackhint.sack_bytes_rexmit;
2012 						if (awnd < tp->snd_ssthresh) {
2013 							tp->snd_cwnd += tp->t_maxseg;
2014 							if (tp->snd_cwnd > tp->snd_ssthresh)
2015 								tp->snd_cwnd = tp->snd_ssthresh;
2016 						}
2017 					} else
2018 						tp->snd_cwnd += tp->t_maxseg;
2019 					(void) tcp_output(tp);
2020 					goto drop;
2021 				} else if (tp->t_dupacks == tcprexmtthresh) {
2022 					tcp_seq onxt = tp->snd_nxt;
2023 					u_int win;
2024 
2025 					/*
2026 					 * If we're doing sack, check to
2027 					 * see if we're already in sack
2028 					 * recovery. If we're not doing sack,
2029 					 * check to see if we're in newreno
2030 					 * recovery.
2031 					 */
2032 					if (tp->sack_enable) {
2033 						if (IN_FASTRECOVERY(tp)) {
2034 							tp->t_dupacks = 0;
2035 							break;
2036 						}
2037 					} else if (tcp_do_newreno) {
2038 						if (SEQ_LEQ(th->th_ack,
2039 						    tp->snd_recover)) {
2040 							tp->t_dupacks = 0;
2041 							break;
2042 						}
2043 					}
2044 					win = min(tp->snd_wnd, tp->snd_cwnd) /
2045 					    2 / tp->t_maxseg;
2046 					if (win < 2)
2047 						win = 2;
2048 					tp->snd_ssthresh = win * tp->t_maxseg;
2049 					ENTER_FASTRECOVERY(tp);
2050 					tp->snd_recover = tp->snd_max;
2051 					callout_stop(tp->tt_rexmt);
2052 					tp->t_rtttime = 0;
2053 					if (tp->sack_enable) {
2054 						tcpstat.tcps_sack_recovery_episode++;
2055 						tp->sack_newdata = tp->snd_nxt;
2056 						tp->snd_cwnd = tp->t_maxseg;
2057 						(void) tcp_output(tp);
2058 						goto drop;
2059 					}
2060 					tp->snd_nxt = th->th_ack;
2061 					tp->snd_cwnd = tp->t_maxseg;
2062 					(void) tcp_output(tp);
2063 					KASSERT(tp->snd_limited <= 2,
2064 					    ("tp->snd_limited too big"));
2065 					tp->snd_cwnd = tp->snd_ssthresh +
2066 					     tp->t_maxseg *
2067 					     (tp->t_dupacks - tp->snd_limited);
2068 					if (SEQ_GT(onxt, tp->snd_nxt))
2069 						tp->snd_nxt = onxt;
2070 					goto drop;
2071 				} else if (tcp_do_rfc3042) {
2072 					u_long oldcwnd = tp->snd_cwnd;
2073 					tcp_seq oldsndmax = tp->snd_max;
2074 					u_int sent;
2075 
2076 					KASSERT(tp->t_dupacks == 1 ||
2077 					    tp->t_dupacks == 2,
2078 					    ("dupacks not 1 or 2"));
2079 					if (tp->t_dupacks == 1)
2080 						tp->snd_limited = 0;
2081 					tp->snd_cwnd =
2082 					    (tp->snd_nxt - tp->snd_una) +
2083 					    (tp->t_dupacks - tp->snd_limited) *
2084 					    tp->t_maxseg;
2085 					(void) tcp_output(tp);
2086 					sent = tp->snd_max - oldsndmax;
2087 					if (sent > tp->t_maxseg) {
2088 						KASSERT((tp->t_dupacks == 2 &&
2089 						    tp->snd_limited == 0) ||
2090 						   (sent == tp->t_maxseg + 1 &&
2091 						    tp->t_flags & TF_SENTFIN),
2092 						    ("sent too much"));
2093 						tp->snd_limited = 2;
2094 					} else if (sent > 0)
2095 						++tp->snd_limited;
2096 					tp->snd_cwnd = oldcwnd;
2097 					goto drop;
2098 				}
2099 			} else
2100 				tp->t_dupacks = 0;
2101 			break;
2102 		}
2103 
2104 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2105 
2106 		/*
2107 		 * If the congestion window was inflated to account
2108 		 * for the other side's cached packets, retract it.
2109 		 */
2110 		if (tcp_do_newreno || tp->sack_enable) {
2111 			if (IN_FASTRECOVERY(tp)) {
2112 				if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2113 					if (tp->sack_enable)
2114 						tcp_sack_partialack(tp, th);
2115 					else
2116 						tcp_newreno_partial_ack(tp, th);
2117 				} else {
2118 					/*
2119 					 * Out of fast recovery.
2120 					 * Window inflation should have left us
2121 					 * with approximately snd_ssthresh
2122 					 * outstanding data.
2123 					 * But in case we would be inclined to
2124 					 * send a burst, better to do it via
2125 					 * the slow start mechanism.
2126 					 */
2127 					if (SEQ_GT(th->th_ack +
2128 							tp->snd_ssthresh,
2129 						   tp->snd_max))
2130 						tp->snd_cwnd = tp->snd_max -
2131 								th->th_ack +
2132 								tp->t_maxseg;
2133 					else
2134 						tp->snd_cwnd = tp->snd_ssthresh;
2135 				}
2136 			}
2137 		} else {
2138 			if (tp->t_dupacks >= tcprexmtthresh &&
2139 			    tp->snd_cwnd > tp->snd_ssthresh)
2140 				tp->snd_cwnd = tp->snd_ssthresh;
2141 		}
2142 		tp->t_dupacks = 0;
2143 		/*
2144 		 * If we reach this point, ACK is not a duplicate,
2145 		 *     i.e., it ACKs something we sent.
2146 		 */
2147 		if (tp->t_flags & TF_NEEDSYN) {
2148 			/*
2149 			 * T/TCP: Connection was half-synchronized, and our
2150 			 * SYN has been ACK'd (so connection is now fully
2151 			 * synchronized).  Go to non-starred state,
2152 			 * increment snd_una for ACK of SYN, and check if
2153 			 * we can do window scaling.
2154 			 */
2155 			tp->t_flags &= ~TF_NEEDSYN;
2156 			tp->snd_una++;
2157 			/* Do window scaling? */
2158 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2159 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2160 				tp->rcv_scale = tp->request_r_scale;
2161 				/* Send window already scaled. */
2162 			}
2163 		}
2164 
2165 process_ACK:
2166 		KASSERT(headlocked, ("tcp_input: process_ACK: head not "
2167 		    "locked"));
2168 		INP_LOCK_ASSERT(inp);
2169 
2170 		acked = th->th_ack - tp->snd_una;
2171 		tcpstat.tcps_rcvackpack++;
2172 		tcpstat.tcps_rcvackbyte += acked;
2173 
2174 		/*
2175 		 * If we just performed our first retransmit, and the ACK
2176 		 * arrives within our recovery window, then it was a mistake
2177 		 * to do the retransmit in the first place.  Recover our
2178 		 * original cwnd and ssthresh, and proceed to transmit where
2179 		 * we left off.
2180 		 */
2181 		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2182 			++tcpstat.tcps_sndrexmitbad;
2183 			tp->snd_cwnd = tp->snd_cwnd_prev;
2184 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
2185 			tp->snd_recover = tp->snd_recover_prev;
2186 			if (tp->t_flags & TF_WASFRECOVERY)
2187 				ENTER_FASTRECOVERY(tp);
2188 			tp->snd_nxt = tp->snd_max;
2189 			tp->t_badrxtwin = 0;	/* XXX probably not required */
2190 		}
2191 
2192 		/*
2193 		 * If we have a timestamp reply, update smoothed
2194 		 * round trip time.  If no timestamp is present but
2195 		 * transmit timer is running and timed sequence
2196 		 * number was acked, update smoothed round trip time.
2197 		 * Since we now have an rtt measurement, cancel the
2198 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2199 		 * Recompute the initial retransmit timer.
2200 		 *
2201 		 * Some boxes send broken timestamp replies
2202 		 * during the SYN+ACK phase, ignore
2203 		 * timestamps of 0 or we could calculate a
2204 		 * huge RTT and blow up the retransmit timer.
2205 		 */
2206 		if ((to.to_flags & TOF_TS) != 0 &&
2207 		    to.to_tsecr) {
2208 			if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2209 				tp->t_rttlow = ticks - to.to_tsecr;
2210 			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2211 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2212 			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2213 				tp->t_rttlow = ticks - tp->t_rtttime;
2214 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2215 		}
2216 		tcp_xmit_bandwidth_limit(tp, th->th_ack);
2217 
2218 		/*
2219 		 * If all outstanding data is acked, stop retransmit
2220 		 * timer and remember to restart (more output or persist).
2221 		 * If there is more data to be acked, restart retransmit
2222 		 * timer, using current (possibly backed-off) value.
2223 		 */
2224 		if (th->th_ack == tp->snd_max) {
2225 			callout_stop(tp->tt_rexmt);
2226 			needoutput = 1;
2227 		} else if (!callout_active(tp->tt_persist))
2228 			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2229 				      tcp_timer_rexmt, tp);
2230 
2231 		/*
2232 		 * If no data (only SYN) was ACK'd,
2233 		 *    skip rest of ACK processing.
2234 		 */
2235 		if (acked == 0)
2236 			goto step6;
2237 
2238 		/*
2239 		 * When new data is acked, open the congestion window.
2240 		 * If the window gives us less than ssthresh packets
2241 		 * in flight, open exponentially (maxseg per packet).
2242 		 * Otherwise open linearly: maxseg per window
2243 		 * (maxseg^2 / cwnd per packet).
2244 		 */
2245 		if ((!tcp_do_newreno && !tp->sack_enable) ||
2246 		    !IN_FASTRECOVERY(tp)) {
2247 			register u_int cw = tp->snd_cwnd;
2248 			register u_int incr = tp->t_maxseg;
2249 			if (cw > tp->snd_ssthresh)
2250 				incr = incr * incr / cw;
2251 			tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2252 		}
2253 		SOCKBUF_LOCK(&so->so_snd);
2254 		if (acked > so->so_snd.sb_cc) {
2255 			tp->snd_wnd -= so->so_snd.sb_cc;
2256 			sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2257 			ourfinisacked = 1;
2258 		} else {
2259 			sbdrop_locked(&so->so_snd, acked);
2260 			tp->snd_wnd -= acked;
2261 			ourfinisacked = 0;
2262 		}
2263 		sowwakeup_locked(so);
2264 		/* detect una wraparound */
2265 		if ((tcp_do_newreno || tp->sack_enable) &&
2266 		    !IN_FASTRECOVERY(tp) &&
2267 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
2268 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2269 			tp->snd_recover = th->th_ack - 1;
2270 		if ((tcp_do_newreno || tp->sack_enable) &&
2271 		    IN_FASTRECOVERY(tp) &&
2272 		    SEQ_GEQ(th->th_ack, tp->snd_recover))
2273 			EXIT_FASTRECOVERY(tp);
2274 		tp->snd_una = th->th_ack;
2275 		if (tp->sack_enable) {
2276 			if (SEQ_GT(tp->snd_una, tp->snd_recover))
2277 				tp->snd_recover = tp->snd_una;
2278 		}
2279 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2280 			tp->snd_nxt = tp->snd_una;
2281 
2282 		switch (tp->t_state) {
2283 
2284 		/*
2285 		 * In FIN_WAIT_1 STATE in addition to the processing
2286 		 * for the ESTABLISHED state if our FIN is now acknowledged
2287 		 * then enter FIN_WAIT_2.
2288 		 */
2289 		case TCPS_FIN_WAIT_1:
2290 			if (ourfinisacked) {
2291 				/*
2292 				 * If we can't receive any more
2293 				 * data, then closing user can proceed.
2294 				 * Starting the timer is contrary to the
2295 				 * specification, but if we don't get a FIN
2296 				 * we'll hang forever.
2297 				 */
2298 		/* XXXjl
2299 		 * we should release the tp also, and use a
2300 		 * compressed state.
2301 		 */
2302 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2303 					int timeout;
2304 
2305 					soisdisconnected(so);
2306 					timeout = (tcp_fast_finwait2_recycle) ?
2307 						tcp_finwait2_timeout : tcp_maxidle;
2308 					callout_reset(tp->tt_2msl, timeout,
2309 						      tcp_timer_2msl, tp);
2310 				}
2311 				tp->t_state = TCPS_FIN_WAIT_2;
2312 			}
2313 			break;
2314 
2315 		/*
2316 		 * In CLOSING STATE in addition to the processing for
2317 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2318 		 * then enter the TIME-WAIT state, otherwise ignore
2319 		 * the segment.
2320 		 */
2321 		case TCPS_CLOSING:
2322 			if (ourfinisacked) {
2323 				KASSERT(headlocked, ("tcp_input: process_ACK: "
2324 				    "head not locked"));
2325 				tcp_twstart(tp);
2326 				INP_INFO_WUNLOCK(&tcbinfo);
2327 				m_freem(m);
2328 				return;
2329 			}
2330 			break;
2331 
2332 		/*
2333 		 * In LAST_ACK, we may still be waiting for data to drain
2334 		 * and/or to be acked, as well as for the ack of our FIN.
2335 		 * If our FIN is now acknowledged, delete the TCB,
2336 		 * enter the closed state and return.
2337 		 */
2338 		case TCPS_LAST_ACK:
2339 			if (ourfinisacked) {
2340 				KASSERT(headlocked, ("tcp_input: process_ACK:"
2341 				    " tcp_close: head not locked"));
2342 				tp = tcp_close(tp);
2343 				goto drop;
2344 			}
2345 			break;
2346 
2347 		/*
2348 		 * In TIME_WAIT state the only thing that should arrive
2349 		 * is a retransmission of the remote FIN.  Acknowledge
2350 		 * it and restart the finack timer.
2351 		 */
2352 		case TCPS_TIME_WAIT:
2353 			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2354 			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2355 				      tcp_timer_2msl, tp);
2356 			goto dropafterack;
2357 		}
2358 	}
2359 
2360 step6:
2361 	KASSERT(headlocked, ("tcp_input: step6: head not locked"));
2362 	INP_LOCK_ASSERT(inp);
2363 
2364 	/*
2365 	 * Update window information.
2366 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2367 	 */
2368 	if ((thflags & TH_ACK) &&
2369 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2370 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2371 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2372 		/* keep track of pure window updates */
2373 		if (tlen == 0 &&
2374 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2375 			tcpstat.tcps_rcvwinupd++;
2376 		tp->snd_wnd = tiwin;
2377 		tp->snd_wl1 = th->th_seq;
2378 		tp->snd_wl2 = th->th_ack;
2379 		if (tp->snd_wnd > tp->max_sndwnd)
2380 			tp->max_sndwnd = tp->snd_wnd;
2381 		needoutput = 1;
2382 	}
2383 
2384 	/*
2385 	 * Process segments with URG.
2386 	 */
2387 	if ((thflags & TH_URG) && th->th_urp &&
2388 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2389 		/*
2390 		 * This is a kludge, but if we receive and accept
2391 		 * random urgent pointers, we'll crash in
2392 		 * soreceive.  It's hard to imagine someone
2393 		 * actually wanting to send this much urgent data.
2394 		 */
2395 		SOCKBUF_LOCK(&so->so_rcv);
2396 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2397 			th->th_urp = 0;			/* XXX */
2398 			thflags &= ~TH_URG;		/* XXX */
2399 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
2400 			goto dodata;			/* XXX */
2401 		}
2402 		/*
2403 		 * If this segment advances the known urgent pointer,
2404 		 * then mark the data stream.  This should not happen
2405 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2406 		 * a FIN has been received from the remote side.
2407 		 * In these states we ignore the URG.
2408 		 *
2409 		 * According to RFC961 (Assigned Protocols),
2410 		 * the urgent pointer points to the last octet
2411 		 * of urgent data.  We continue, however,
2412 		 * to consider it to indicate the first octet
2413 		 * of data past the urgent section as the original
2414 		 * spec states (in one of two places).
2415 		 */
2416 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2417 			tp->rcv_up = th->th_seq + th->th_urp;
2418 			so->so_oobmark = so->so_rcv.sb_cc +
2419 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2420 			if (so->so_oobmark == 0)
2421 				so->so_rcv.sb_state |= SBS_RCVATMARK;
2422 			sohasoutofband(so);
2423 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2424 		}
2425 		SOCKBUF_UNLOCK(&so->so_rcv);
2426 		/*
2427 		 * Remove out of band data so doesn't get presented to user.
2428 		 * This can happen independent of advancing the URG pointer,
2429 		 * but if two URG's are pending at once, some out-of-band
2430 		 * data may creep in... ick.
2431 		 */
2432 		if (th->th_urp <= (u_long)tlen &&
2433 		    !(so->so_options & SO_OOBINLINE)) {
2434 			/* hdr drop is delayed */
2435 			tcp_pulloutofband(so, th, m, drop_hdrlen);
2436 		}
2437 	} else {
2438 		/*
2439 		 * If no out of band data is expected,
2440 		 * pull receive urgent pointer along
2441 		 * with the receive window.
2442 		 */
2443 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2444 			tp->rcv_up = tp->rcv_nxt;
2445 	}
2446 dodata:							/* XXX */
2447 	KASSERT(headlocked, ("tcp_input: dodata: head not locked"));
2448 	INP_LOCK_ASSERT(inp);
2449 
2450 	/*
2451 	 * Process the segment text, merging it into the TCP sequencing queue,
2452 	 * and arranging for acknowledgment of receipt if necessary.
2453 	 * This process logically involves adjusting tp->rcv_wnd as data
2454 	 * is presented to the user (this happens in tcp_usrreq.c,
2455 	 * case PRU_RCVD).  If a FIN has already been received on this
2456 	 * connection then we just ignore the text.
2457 	 */
2458 	if ((tlen || (thflags & TH_FIN)) &&
2459 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2460 		tcp_seq save_start = th->th_seq;
2461 		tcp_seq save_end = th->th_seq + tlen;
2462 		m_adj(m, drop_hdrlen);	/* delayed header drop */
2463 		/*
2464 		 * Insert segment which includes th into TCP reassembly queue
2465 		 * with control block tp.  Set thflags to whether reassembly now
2466 		 * includes a segment with FIN.  This handles the common case
2467 		 * inline (segment is the next to be received on an established
2468 		 * connection, and the queue is empty), avoiding linkage into
2469 		 * and removal from the queue and repetition of various
2470 		 * conversions.
2471 		 * Set DELACK for segments received in order, but ack
2472 		 * immediately when segments are out of order (so
2473 		 * fast retransmit can work).
2474 		 */
2475 		if (th->th_seq == tp->rcv_nxt &&
2476 		    LIST_EMPTY(&tp->t_segq) &&
2477 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2478 			if (DELAY_ACK(tp))
2479 				tp->t_flags |= TF_DELACK;
2480 			else
2481 				tp->t_flags |= TF_ACKNOW;
2482 			tp->rcv_nxt += tlen;
2483 			thflags = th->th_flags & TH_FIN;
2484 			tcpstat.tcps_rcvpack++;
2485 			tcpstat.tcps_rcvbyte += tlen;
2486 			ND6_HINT(tp);
2487 			SOCKBUF_LOCK(&so->so_rcv);
2488 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2489 				m_freem(m);
2490 			else
2491 				sbappendstream_locked(&so->so_rcv, m);
2492 			sorwakeup_locked(so);
2493 		} else {
2494 			thflags = tcp_reass(tp, th, &tlen, m);
2495 			tp->t_flags |= TF_ACKNOW;
2496 		}
2497 		if (tlen > 0 && tp->sack_enable)
2498 			tcp_update_sack_list(tp, save_start, save_end);
2499 		/*
2500 		 * Note the amount of data that peer has sent into
2501 		 * our window, in order to estimate the sender's
2502 		 * buffer size.
2503 		 */
2504 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2505 	} else {
2506 		m_freem(m);
2507 		thflags &= ~TH_FIN;
2508 	}
2509 
2510 	/*
2511 	 * If FIN is received ACK the FIN and let the user know
2512 	 * that the connection is closing.
2513 	 */
2514 	if (thflags & TH_FIN) {
2515 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2516 			socantrcvmore(so);
2517 			/*
2518 			 * If connection is half-synchronized
2519 			 * (ie NEEDSYN flag on) then delay ACK,
2520 			 * so it may be piggybacked when SYN is sent.
2521 			 * Otherwise, since we received a FIN then no
2522 			 * more input can be expected, send ACK now.
2523 			 */
2524 			if (tp->t_flags & TF_NEEDSYN)
2525 				tp->t_flags |= TF_DELACK;
2526 			else
2527 				tp->t_flags |= TF_ACKNOW;
2528 			tp->rcv_nxt++;
2529 		}
2530 		switch (tp->t_state) {
2531 
2532 		/*
2533 		 * In SYN_RECEIVED and ESTABLISHED STATES
2534 		 * enter the CLOSE_WAIT state.
2535 		 */
2536 		case TCPS_SYN_RECEIVED:
2537 			tp->t_starttime = ticks;
2538 			/*FALLTHROUGH*/
2539 		case TCPS_ESTABLISHED:
2540 			tp->t_state = TCPS_CLOSE_WAIT;
2541 			break;
2542 
2543 		/*
2544 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2545 		 * enter the CLOSING state.
2546 		 */
2547 		case TCPS_FIN_WAIT_1:
2548 			tp->t_state = TCPS_CLOSING;
2549 			break;
2550 
2551 		/*
2552 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2553 		 * starting the time-wait timer, turning off the other
2554 		 * standard timers.
2555 		 */
2556 		case TCPS_FIN_WAIT_2:
2557 			KASSERT(headlocked == 1, ("tcp_input: dodata: "
2558 			    "TCP_FIN_WAIT_2: head not locked"));
2559 			tcp_twstart(tp);
2560 			INP_INFO_WUNLOCK(&tcbinfo);
2561 			return;
2562 
2563 		/*
2564 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2565 		 */
2566 		case TCPS_TIME_WAIT:
2567 			KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2568 			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2569 				      tcp_timer_2msl, tp);
2570 			break;
2571 		}
2572 	}
2573 	INP_INFO_WUNLOCK(&tcbinfo);
2574 	headlocked = 0;
2575 #ifdef TCPDEBUG
2576 	if (so->so_options & SO_DEBUG)
2577 		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2578 			  &tcp_savetcp, 0);
2579 #endif
2580 
2581 	/*
2582 	 * Return any desired output.
2583 	 */
2584 	if (needoutput || (tp->t_flags & TF_ACKNOW))
2585 		(void) tcp_output(tp);
2586 
2587 check_delack:
2588 	KASSERT(headlocked == 0, ("tcp_input: check_delack: head locked"));
2589 	INP_LOCK_ASSERT(inp);
2590 	if (tp->t_flags & TF_DELACK) {
2591 		tp->t_flags &= ~TF_DELACK;
2592 		callout_reset(tp->tt_delack, tcp_delacktime,
2593 		    tcp_timer_delack, tp);
2594 	}
2595 	INP_UNLOCK(inp);
2596 	return;
2597 
2598 dropafterack:
2599 	KASSERT(headlocked, ("tcp_input: dropafterack: head not locked"));
2600 	/*
2601 	 * Generate an ACK dropping incoming segment if it occupies
2602 	 * sequence space, where the ACK reflects our state.
2603 	 *
2604 	 * We can now skip the test for the RST flag since all
2605 	 * paths to this code happen after packets containing
2606 	 * RST have been dropped.
2607 	 *
2608 	 * In the SYN-RECEIVED state, don't send an ACK unless the
2609 	 * segment we received passes the SYN-RECEIVED ACK test.
2610 	 * If it fails send a RST.  This breaks the loop in the
2611 	 * "LAND" DoS attack, and also prevents an ACK storm
2612 	 * between two listening ports that have been sent forged
2613 	 * SYN segments, each with the source address of the other.
2614 	 */
2615 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2616 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2617 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2618 		rstreason = BANDLIM_RST_OPENPORT;
2619 		goto dropwithreset;
2620 	}
2621 #ifdef TCPDEBUG
2622 	if (so->so_options & SO_DEBUG)
2623 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2624 			  &tcp_savetcp, 0);
2625 #endif
2626 	KASSERT(headlocked, ("headlocked should be 1"));
2627 	INP_INFO_WUNLOCK(&tcbinfo);
2628 	tp->t_flags |= TF_ACKNOW;
2629 	(void) tcp_output(tp);
2630 	INP_UNLOCK(inp);
2631 	m_freem(m);
2632 	return;
2633 
2634 dropwithreset:
2635 	KASSERT(headlocked, ("tcp_input: dropwithreset: head not locked"));
2636 	/*
2637 	 * Generate a RST, dropping incoming segment.
2638 	 * Make ACK acceptable to originator of segment.
2639 	 * Don't bother to respond if destination was broadcast/multicast.
2640 	 */
2641 	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2642 		goto drop;
2643 	if (isipv6) {
2644 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2645 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2646 			goto drop;
2647 	} else {
2648 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2649 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2650 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2651 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2652 			goto drop;
2653 	}
2654 	/* IPv6 anycast check is done at tcp6_input() */
2655 
2656 	/*
2657 	 * Perform bandwidth limiting.
2658 	 */
2659 	if (badport_bandlim(rstreason) < 0)
2660 		goto drop;
2661 
2662 #ifdef TCPDEBUG
2663 	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2664 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2665 			  &tcp_savetcp, 0);
2666 #endif
2667 
2668 	if (thflags & TH_ACK)
2669 		/* mtod() below is safe as long as hdr dropping is delayed */
2670 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2671 			    TH_RST);
2672 	else {
2673 		if (thflags & TH_SYN)
2674 			tlen++;
2675 		/* mtod() below is safe as long as hdr dropping is delayed */
2676 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2677 			    (tcp_seq)0, TH_RST|TH_ACK);
2678 	}
2679 
2680 	if (tp != NULL)
2681 		INP_UNLOCK(inp);
2682 	if (headlocked)
2683 		INP_INFO_WUNLOCK(&tcbinfo);
2684 	return;
2685 
2686 drop:
2687 	/*
2688 	 * Drop space held by incoming segment and return.
2689 	 */
2690 #ifdef TCPDEBUG
2691 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2692 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2693 			  &tcp_savetcp, 0);
2694 #endif
2695 	if (tp != NULL)
2696 		INP_UNLOCK(inp);
2697 	if (headlocked)
2698 		INP_INFO_WUNLOCK(&tcbinfo);
2699 	m_freem(m);
2700 	return;
2701 }
2702 
2703 /*
2704  * Parse TCP options and place in tcpopt.
2705  */
2706 static void
2707 tcp_dooptions(to, cp, cnt, flags)
2708 	struct tcpopt *to;
2709 	u_char *cp;
2710 	int cnt;
2711 	int flags;
2712 {
2713 	int opt, optlen;
2714 
2715 	to->to_flags = 0;
2716 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2717 		opt = cp[0];
2718 		if (opt == TCPOPT_EOL)
2719 			break;
2720 		if (opt == TCPOPT_NOP)
2721 			optlen = 1;
2722 		else {
2723 			if (cnt < 2)
2724 				break;
2725 			optlen = cp[1];
2726 			if (optlen < 2 || optlen > cnt)
2727 				break;
2728 		}
2729 		switch (opt) {
2730 		case TCPOPT_MAXSEG:
2731 			if (optlen != TCPOLEN_MAXSEG)
2732 				continue;
2733 			if (!(flags & TO_SYN))
2734 				continue;
2735 			to->to_flags |= TOF_MSS;
2736 			bcopy((char *)cp + 2,
2737 			    (char *)&to->to_mss, sizeof(to->to_mss));
2738 			to->to_mss = ntohs(to->to_mss);
2739 			break;
2740 		case TCPOPT_WINDOW:
2741 			if (optlen != TCPOLEN_WINDOW)
2742 				continue;
2743 			if (!(flags & TO_SYN))
2744 				continue;
2745 			to->to_flags |= TOF_SCALE;
2746 			to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2747 			break;
2748 		case TCPOPT_TIMESTAMP:
2749 			if (optlen != TCPOLEN_TIMESTAMP)
2750 				continue;
2751 			to->to_flags |= TOF_TS;
2752 			bcopy((char *)cp + 2,
2753 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2754 			to->to_tsval = ntohl(to->to_tsval);
2755 			bcopy((char *)cp + 6,
2756 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2757 			to->to_tsecr = ntohl(to->to_tsecr);
2758 			break;
2759 #ifdef TCP_SIGNATURE
2760 		/*
2761 		 * XXX In order to reply to a host which has set the
2762 		 * TCP_SIGNATURE option in its initial SYN, we have to
2763 		 * record the fact that the option was observed here
2764 		 * for the syncache code to perform the correct response.
2765 		 */
2766 		case TCPOPT_SIGNATURE:
2767 			if (optlen != TCPOLEN_SIGNATURE)
2768 				continue;
2769 			to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2770 			break;
2771 #endif
2772 		case TCPOPT_SACK_PERMITTED:
2773 			if (optlen != TCPOLEN_SACK_PERMITTED)
2774 				continue;
2775 			if (!(flags & TO_SYN))
2776 				continue;
2777 			if (!tcp_do_sack)
2778 				continue;
2779 			to->to_flags |= TOF_SACK;
2780 			break;
2781 		case TCPOPT_SACK:
2782 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2783 				continue;
2784 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2785 			to->to_sacks = cp + 2;
2786 			tcpstat.tcps_sack_rcv_blocks++;
2787 			break;
2788 		default:
2789 			continue;
2790 		}
2791 	}
2792 }
2793 
2794 /*
2795  * Pull out of band byte out of a segment so
2796  * it doesn't appear in the user's data queue.
2797  * It is still reflected in the segment length for
2798  * sequencing purposes.
2799  */
2800 static void
2801 tcp_pulloutofband(so, th, m, off)
2802 	struct socket *so;
2803 	struct tcphdr *th;
2804 	register struct mbuf *m;
2805 	int off;		/* delayed to be droped hdrlen */
2806 {
2807 	int cnt = off + th->th_urp - 1;
2808 
2809 	while (cnt >= 0) {
2810 		if (m->m_len > cnt) {
2811 			char *cp = mtod(m, caddr_t) + cnt;
2812 			struct tcpcb *tp = sototcpcb(so);
2813 
2814 			tp->t_iobc = *cp;
2815 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2816 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2817 			m->m_len--;
2818 			if (m->m_flags & M_PKTHDR)
2819 				m->m_pkthdr.len--;
2820 			return;
2821 		}
2822 		cnt -= m->m_len;
2823 		m = m->m_next;
2824 		if (m == 0)
2825 			break;
2826 	}
2827 	panic("tcp_pulloutofband");
2828 }
2829 
2830 /*
2831  * Collect new round-trip time estimate
2832  * and update averages and current timeout.
2833  */
2834 static void
2835 tcp_xmit_timer(tp, rtt)
2836 	register struct tcpcb *tp;
2837 	int rtt;
2838 {
2839 	register int delta;
2840 
2841 	INP_LOCK_ASSERT(tp->t_inpcb);
2842 
2843 	tcpstat.tcps_rttupdated++;
2844 	tp->t_rttupdated++;
2845 	if (tp->t_srtt != 0) {
2846 		/*
2847 		 * srtt is stored as fixed point with 5 bits after the
2848 		 * binary point (i.e., scaled by 8).  The following magic
2849 		 * is equivalent to the smoothing algorithm in rfc793 with
2850 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2851 		 * point).  Adjust rtt to origin 0.
2852 		 */
2853 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2854 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2855 
2856 		if ((tp->t_srtt += delta) <= 0)
2857 			tp->t_srtt = 1;
2858 
2859 		/*
2860 		 * We accumulate a smoothed rtt variance (actually, a
2861 		 * smoothed mean difference), then set the retransmit
2862 		 * timer to smoothed rtt + 4 times the smoothed variance.
2863 		 * rttvar is stored as fixed point with 4 bits after the
2864 		 * binary point (scaled by 16).  The following is
2865 		 * equivalent to rfc793 smoothing with an alpha of .75
2866 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2867 		 * rfc793's wired-in beta.
2868 		 */
2869 		if (delta < 0)
2870 			delta = -delta;
2871 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2872 		if ((tp->t_rttvar += delta) <= 0)
2873 			tp->t_rttvar = 1;
2874 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2875 		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2876 	} else {
2877 		/*
2878 		 * No rtt measurement yet - use the unsmoothed rtt.
2879 		 * Set the variance to half the rtt (so our first
2880 		 * retransmit happens at 3*rtt).
2881 		 */
2882 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2883 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2884 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2885 	}
2886 	tp->t_rtttime = 0;
2887 	tp->t_rxtshift = 0;
2888 
2889 	/*
2890 	 * the retransmit should happen at rtt + 4 * rttvar.
2891 	 * Because of the way we do the smoothing, srtt and rttvar
2892 	 * will each average +1/2 tick of bias.  When we compute
2893 	 * the retransmit timer, we want 1/2 tick of rounding and
2894 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2895 	 * firing of the timer.  The bias will give us exactly the
2896 	 * 1.5 tick we need.  But, because the bias is
2897 	 * statistical, we have to test that we don't drop below
2898 	 * the minimum feasible timer (which is 2 ticks).
2899 	 */
2900 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2901 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2902 
2903 	/*
2904 	 * We received an ack for a packet that wasn't retransmitted;
2905 	 * it is probably safe to discard any error indications we've
2906 	 * received recently.  This isn't quite right, but close enough
2907 	 * for now (a route might have failed after we sent a segment,
2908 	 * and the return path might not be symmetrical).
2909 	 */
2910 	tp->t_softerror = 0;
2911 }
2912 
2913 /*
2914  * Determine a reasonable value for maxseg size.
2915  * If the route is known, check route for mtu.
2916  * If none, use an mss that can be handled on the outgoing
2917  * interface without forcing IP to fragment; if bigger than
2918  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2919  * to utilize large mbufs.  If no route is found, route has no mtu,
2920  * or the destination isn't local, use a default, hopefully conservative
2921  * size (usually 512 or the default IP max size, but no more than the mtu
2922  * of the interface), as we can't discover anything about intervening
2923  * gateways or networks.  We also initialize the congestion/slow start
2924  * window to be a single segment if the destination isn't local.
2925  * While looking at the routing entry, we also initialize other path-dependent
2926  * parameters from pre-set or cached values in the routing entry.
2927  *
2928  * Also take into account the space needed for options that we
2929  * send regularly.  Make maxseg shorter by that amount to assure
2930  * that we can send maxseg amount of data even when the options
2931  * are present.  Store the upper limit of the length of options plus
2932  * data in maxopd.
2933  *
2934  *
2935  * In case of T/TCP, we call this routine during implicit connection
2936  * setup as well (offer = -1), to initialize maxseg from the cached
2937  * MSS of our peer.
2938  *
2939  * NOTE that this routine is only called when we process an incoming
2940  * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2941  */
2942 void
2943 tcp_mss(tp, offer)
2944 	struct tcpcb *tp;
2945 	int offer;
2946 {
2947 	int rtt, mss;
2948 	u_long bufsize;
2949 	u_long maxmtu;
2950 	struct inpcb *inp = tp->t_inpcb;
2951 	struct socket *so;
2952 	struct hc_metrics_lite metrics;
2953 	int origoffer = offer;
2954 	int mtuflags = 0;
2955 #ifdef INET6
2956 	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2957 	size_t min_protoh = isipv6 ?
2958 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2959 			    sizeof (struct tcpiphdr);
2960 #else
2961 	const size_t min_protoh = sizeof(struct tcpiphdr);
2962 #endif
2963 
2964 	/* initialize */
2965 #ifdef INET6
2966 	if (isipv6) {
2967 		maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2968 		tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2969 	} else
2970 #endif
2971 	{
2972 		maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2973 		tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2974 	}
2975 	so = inp->inp_socket;
2976 
2977 	/*
2978 	 * no route to sender, stay with default mss and return
2979 	 */
2980 	if (maxmtu == 0)
2981 		return;
2982 
2983 	/* what have we got? */
2984 	switch (offer) {
2985 		case 0:
2986 			/*
2987 			 * Offer == 0 means that there was no MSS on the SYN
2988 			 * segment, in this case we use tcp_mssdflt.
2989 			 */
2990 			offer =
2991 #ifdef INET6
2992 				isipv6 ? tcp_v6mssdflt :
2993 #endif
2994 				tcp_mssdflt;
2995 			break;
2996 
2997 		case -1:
2998 			/*
2999 			 * Offer == -1 means that we didn't receive SYN yet.
3000 			 */
3001 			/* FALLTHROUGH */
3002 
3003 		default:
3004 			/*
3005 			 * Prevent DoS attack with too small MSS. Round up
3006 			 * to at least minmss.
3007 			 */
3008 			offer = max(offer, tcp_minmss);
3009 			/*
3010 			 * Sanity check: make sure that maxopd will be large
3011 			 * enough to allow some data on segments even if the
3012 			 * all the option space is used (40bytes).  Otherwise
3013 			 * funny things may happen in tcp_output.
3014 			 */
3015 			offer = max(offer, 64);
3016 	}
3017 
3018 	/*
3019 	 * rmx information is now retrieved from tcp_hostcache
3020 	 */
3021 	tcp_hc_get(&inp->inp_inc, &metrics);
3022 
3023 	/*
3024 	 * if there's a discovered mtu int tcp hostcache, use it
3025 	 * else, use the link mtu.
3026 	 */
3027 	if (metrics.rmx_mtu)
3028 		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3029 	else {
3030 #ifdef INET6
3031 		if (isipv6) {
3032 			mss = maxmtu - min_protoh;
3033 			if (!path_mtu_discovery &&
3034 			    !in6_localaddr(&inp->in6p_faddr))
3035 				mss = min(mss, tcp_v6mssdflt);
3036 		} else
3037 #endif
3038 		{
3039 			mss = maxmtu - min_protoh;
3040 			if (!path_mtu_discovery &&
3041 			    !in_localaddr(inp->inp_faddr))
3042 				mss = min(mss, tcp_mssdflt);
3043 		}
3044 	}
3045 	mss = min(mss, offer);
3046 
3047 	/*
3048 	 * maxopd stores the maximum length of data AND options
3049 	 * in a segment; maxseg is the amount of data in a normal
3050 	 * segment.  We need to store this value (maxopd) apart
3051 	 * from maxseg, because now every segment carries options
3052 	 * and thus we normally have somewhat less data in segments.
3053 	 */
3054 	tp->t_maxopd = mss;
3055 
3056 	/*
3057 	 * origoffer==-1 indicates, that no segments were received yet.
3058 	 * In this case we just guess.
3059 	 */
3060 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3061 	    (origoffer == -1 ||
3062 	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3063 		mss -= TCPOLEN_TSTAMP_APPA;
3064 	tp->t_maxseg = mss;
3065 
3066 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
3067 		if (mss > MCLBYTES)
3068 			mss &= ~(MCLBYTES-1);
3069 #else
3070 		if (mss > MCLBYTES)
3071 			mss = mss / MCLBYTES * MCLBYTES;
3072 #endif
3073 	tp->t_maxseg = mss;
3074 
3075 	/*
3076 	 * If there's a pipesize, change the socket buffer to that size,
3077 	 * don't change if sb_hiwat is different than default (then it
3078 	 * has been changed on purpose with setsockopt).
3079 	 * Make the socket buffers an integral number of mss units;
3080 	 * if the mss is larger than the socket buffer, decrease the mss.
3081 	 */
3082 	SOCKBUF_LOCK(&so->so_snd);
3083 	if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3084 		bufsize = metrics.rmx_sendpipe;
3085 	else
3086 		bufsize = so->so_snd.sb_hiwat;
3087 	if (bufsize < mss)
3088 		mss = bufsize;
3089 	else {
3090 		bufsize = roundup(bufsize, mss);
3091 		if (bufsize > sb_max)
3092 			bufsize = sb_max;
3093 		if (bufsize > so->so_snd.sb_hiwat)
3094 			(void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3095 	}
3096 	SOCKBUF_UNLOCK(&so->so_snd);
3097 	tp->t_maxseg = mss;
3098 
3099 	SOCKBUF_LOCK(&so->so_rcv);
3100 	if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3101 		bufsize = metrics.rmx_recvpipe;
3102 	else
3103 		bufsize = so->so_rcv.sb_hiwat;
3104 	if (bufsize > mss) {
3105 		bufsize = roundup(bufsize, mss);
3106 		if (bufsize > sb_max)
3107 			bufsize = sb_max;
3108 		if (bufsize > so->so_rcv.sb_hiwat)
3109 			(void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3110 	}
3111 	SOCKBUF_UNLOCK(&so->so_rcv);
3112 	/*
3113 	 * While we're here, check the others too
3114 	 */
3115 	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3116 		tp->t_srtt = rtt;
3117 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3118 		tcpstat.tcps_usedrtt++;
3119 		if (metrics.rmx_rttvar) {
3120 			tp->t_rttvar = metrics.rmx_rttvar;
3121 			tcpstat.tcps_usedrttvar++;
3122 		} else {
3123 			/* default variation is +- 1 rtt */
3124 			tp->t_rttvar =
3125 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3126 		}
3127 		TCPT_RANGESET(tp->t_rxtcur,
3128 			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3129 			      tp->t_rttmin, TCPTV_REXMTMAX);
3130 	}
3131 	if (metrics.rmx_ssthresh) {
3132 		/*
3133 		 * There's some sort of gateway or interface
3134 		 * buffer limit on the path.  Use this to set
3135 		 * the slow start threshhold, but set the
3136 		 * threshold to no less than 2*mss.
3137 		 */
3138 		tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3139 		tcpstat.tcps_usedssthresh++;
3140 	}
3141 	if (metrics.rmx_bandwidth)
3142 		tp->snd_bandwidth = metrics.rmx_bandwidth;
3143 
3144 	/*
3145 	 * Set the slow-start flight size depending on whether this
3146 	 * is a local network or not.
3147 	 *
3148 	 * Extend this so we cache the cwnd too and retrieve it here.
3149 	 * Make cwnd even bigger than RFC3390 suggests but only if we
3150 	 * have previous experience with the remote host. Be careful
3151 	 * not make cwnd bigger than remote receive window or our own
3152 	 * send socket buffer. Maybe put some additional upper bound
3153 	 * on the retrieved cwnd. Should do incremental updates to
3154 	 * hostcache when cwnd collapses so next connection doesn't
3155 	 * overloads the path again.
3156 	 *
3157 	 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3158 	 * We currently check only in syncache_socket for that.
3159 	 */
3160 #define TCP_METRICS_CWND
3161 #ifdef TCP_METRICS_CWND
3162 	if (metrics.rmx_cwnd)
3163 		tp->snd_cwnd = max(mss,
3164 				min(metrics.rmx_cwnd / 2,
3165 				 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3166 	else
3167 #endif
3168 	if (tcp_do_rfc3390)
3169 		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3170 #ifdef INET6
3171 	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3172 		 (!isipv6 && in_localaddr(inp->inp_faddr)))
3173 #else
3174 	else if (in_localaddr(inp->inp_faddr))
3175 #endif
3176 		tp->snd_cwnd = mss * ss_fltsz_local;
3177 	else
3178 		tp->snd_cwnd = mss * ss_fltsz;
3179 
3180 	/* Check the interface for TSO capabilities. */
3181 	if (mtuflags & CSUM_TSO)
3182 		tp->t_flags |= TF_TSO;
3183 }
3184 
3185 /*
3186  * Determine the MSS option to send on an outgoing SYN.
3187  */
3188 int
3189 tcp_mssopt(inc)
3190 	struct in_conninfo *inc;
3191 {
3192 	int mss = 0;
3193 	u_long maxmtu = 0;
3194 	u_long thcmtu = 0;
3195 	size_t min_protoh;
3196 #ifdef INET6
3197 	int isipv6 = inc->inc_isipv6 ? 1 : 0;
3198 #endif
3199 
3200 	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3201 
3202 #ifdef INET6
3203 	if (isipv6) {
3204 		mss = tcp_v6mssdflt;
3205 		maxmtu = tcp_maxmtu6(inc, NULL);
3206 		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3207 		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3208 	} else
3209 #endif
3210 	{
3211 		mss = tcp_mssdflt;
3212 		maxmtu = tcp_maxmtu(inc, NULL);
3213 		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3214 		min_protoh = sizeof(struct tcpiphdr);
3215 	}
3216 	if (maxmtu && thcmtu)
3217 		mss = min(maxmtu, thcmtu) - min_protoh;
3218 	else if (maxmtu || thcmtu)
3219 		mss = max(maxmtu, thcmtu) - min_protoh;
3220 
3221 	return (mss);
3222 }
3223 
3224 
3225 /*
3226  * On a partial ack arrives, force the retransmission of the
3227  * next unacknowledged segment.  Do not clear tp->t_dupacks.
3228  * By setting snd_nxt to ti_ack, this forces retransmission timer to
3229  * be started again.
3230  */
3231 static void
3232 tcp_newreno_partial_ack(tp, th)
3233 	struct tcpcb *tp;
3234 	struct tcphdr *th;
3235 {
3236 	tcp_seq onxt = tp->snd_nxt;
3237 	u_long  ocwnd = tp->snd_cwnd;
3238 
3239 	callout_stop(tp->tt_rexmt);
3240 	tp->t_rtttime = 0;
3241 	tp->snd_nxt = th->th_ack;
3242 	/*
3243 	 * Set snd_cwnd to one segment beyond acknowledged offset.
3244 	 * (tp->snd_una has not yet been updated when this function is called.)
3245 	 */
3246 	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3247 	tp->t_flags |= TF_ACKNOW;
3248 	(void) tcp_output(tp);
3249 	tp->snd_cwnd = ocwnd;
3250 	if (SEQ_GT(onxt, tp->snd_nxt))
3251 		tp->snd_nxt = onxt;
3252 	/*
3253 	 * Partial window deflation.  Relies on fact that tp->snd_una
3254 	 * not updated yet.
3255 	 */
3256 	if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3257 		tp->snd_cwnd -= th->th_ack - tp->snd_una;
3258 	else
3259 		tp->snd_cwnd = 0;
3260 	tp->snd_cwnd += tp->t_maxseg;
3261 }
3262 
3263 /*
3264  * Returns 1 if the TIME_WAIT state was killed and we should start over,
3265  * looking for a pcb in the listen state.  Returns 0 otherwise.
3266  */
3267 static int
3268 tcp_timewait(inp, to, th, m, tlen)
3269 	struct inpcb *inp;
3270 	struct tcpopt *to;
3271 	struct tcphdr *th;
3272 	struct mbuf *m;
3273 	int tlen;
3274 {
3275 	struct tcptw *tw;
3276 	int thflags;
3277 	tcp_seq seq;
3278 #ifdef INET6
3279 	int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3280 #else
3281 	const int isipv6 = 0;
3282 #endif
3283 
3284 	/* tcbinfo lock required for tcp_twclose(), tcp_timer_2msl_reset(). */
3285 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
3286 	INP_LOCK_ASSERT(inp);
3287 
3288 	/*
3289 	 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
3290 	 * still present.  This is undesirable, but temporarily necessary
3291 	 * until we work out how to handle inpcb's who's timewait state has
3292 	 * been removed.
3293 	 */
3294 	tw = intotw(inp);
3295 	if (tw == NULL)
3296 		goto drop;
3297 
3298 	thflags = th->th_flags;
3299 
3300 	/*
3301 	 * NOTE: for FIN_WAIT_2 (to be added later),
3302 	 * must validate sequence number before accepting RST
3303 	 */
3304 
3305 	/*
3306 	 * If the segment contains RST:
3307 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
3308 	 *      RFC 1337.
3309 	 */
3310 	if (thflags & TH_RST)
3311 		goto drop;
3312 
3313 #if 0
3314 /* PAWS not needed at the moment */
3315 	/*
3316 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3317 	 * and it's less than ts_recent, drop it.
3318 	 */
3319 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3320 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3321 		if ((thflags & TH_ACK) == 0)
3322 			goto drop;
3323 		goto ack;
3324 	}
3325 	/*
3326 	 * ts_recent is never updated because we never accept new segments.
3327 	 */
3328 #endif
3329 
3330 	/*
3331 	 * If a new connection request is received
3332 	 * while in TIME_WAIT, drop the old connection
3333 	 * and start over if the sequence numbers
3334 	 * are above the previous ones.
3335 	 */
3336 	if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3337 		tcp_twclose(tw, 0);
3338 		return (1);
3339 	}
3340 
3341 	/*
3342 	 * Drop the the segment if it does not contain an ACK.
3343 	 */
3344 	if ((thflags & TH_ACK) == 0)
3345 		goto drop;
3346 
3347 	/*
3348 	 * Reset the 2MSL timer if this is a duplicate FIN.
3349 	 */
3350 	if (thflags & TH_FIN) {
3351 		seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3352 		if (seq + 1 == tw->rcv_nxt)
3353 			tcp_timer_2msl_reset(tw, 1);
3354 	}
3355 
3356 	/*
3357 	 * Acknowledge the segment if it has data or is not a duplicate ACK.
3358 	 */
3359 	if (thflags != TH_ACK || tlen != 0 ||
3360 	    th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3361 		tcp_twrespond(tw, TH_ACK);
3362 	goto drop;
3363 
3364 	/*
3365 	 * Generate a RST, dropping incoming segment.
3366 	 * Make ACK acceptable to originator of segment.
3367 	 * Don't bother to respond if destination was broadcast/multicast.
3368 	 */
3369 	if (m->m_flags & (M_BCAST|M_MCAST))
3370 		goto drop;
3371 	if (isipv6) {
3372 		struct ip6_hdr *ip6;
3373 
3374 		/* IPv6 anycast check is done at tcp6_input() */
3375 		ip6 = mtod(m, struct ip6_hdr *);
3376 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3377 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3378 			goto drop;
3379 	} else {
3380 		struct ip *ip;
3381 
3382 		ip = mtod(m, struct ip *);
3383 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3384 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3385 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3386 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3387 			goto drop;
3388 	}
3389 	if (thflags & TH_ACK) {
3390 		tcp_respond(NULL,
3391 		    mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3392 	} else {
3393 		seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3394 		tcp_respond(NULL,
3395 		    mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
3396 	}
3397 	INP_UNLOCK(inp);
3398 	return (0);
3399 
3400 drop:
3401 	INP_UNLOCK(inp);
3402 	m_freem(m);
3403 	return (0);
3404 }
3405