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