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