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