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