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