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