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