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