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