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