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