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