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