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