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