xref: /netbsd-src/sys/netinet/tcp_input.c (revision 3b435a73967be44dfb4a27315acd72bfacde430c)
1 /*	$NetBSD: tcp_input.c,v 1.96 1999/09/23 02:21:30 itojun Exp $	*/
2 
3 /*
4 %%% portions-copyright-nrl-95
5 Portions of this software are Copyright 1995-1998 by Randall Atkinson,
6 Ronald Lee, Daniel McDonald, Bao Phan, and Chris Winters. All Rights
7 Reserved. All rights under this copyright have been assigned to the US
8 Naval Research Laboratory (NRL). The NRL Copyright Notice and License
9 Agreement Version 1.1 (January 17, 1995) applies to these portions of the
10 software.
11 You should have received a copy of the license with this software. If you
12 didn't get a copy, you may request one from <license@ipv6.nrl.navy.mil>.
13 
14 */
15 
16 /*
17  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
18  * All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  * 3. Neither the name of the project nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  */
44 
45 /*-
46  * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
47  * All rights reserved.
48  *
49  * This code is derived from software contributed to The NetBSD Foundation
50  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
51  * Facility, NASA Ames Research Center.
52  *
53  * Redistribution and use in source and binary forms, with or without
54  * modification, are permitted provided that the following conditions
55  * are met:
56  * 1. Redistributions of source code must retain the above copyright
57  *    notice, this list of conditions and the following disclaimer.
58  * 2. Redistributions in binary form must reproduce the above copyright
59  *    notice, this list of conditions and the following disclaimer in the
60  *    documentation and/or other materials provided with the distribution.
61  * 3. All advertising materials mentioning features or use of this software
62  *    must display the following acknowledgement:
63  *	This product includes software developed by the NetBSD
64  *	Foundation, Inc. and its contributors.
65  * 4. Neither the name of The NetBSD Foundation nor the names of its
66  *    contributors may be used to endorse or promote products derived
67  *    from this software without specific prior written permission.
68  *
69  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
70  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
71  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
72  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
73  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
74  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
75  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
76  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
77  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
78  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
79  * POSSIBILITY OF SUCH DAMAGE.
80  */
81 
82 /*
83  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
84  *	The Regents of the University of California.  All rights reserved.
85  *
86  * Redistribution and use in source and binary forms, with or without
87  * modification, are permitted provided that the following conditions
88  * are met:
89  * 1. Redistributions of source code must retain the above copyright
90  *    notice, this list of conditions and the following disclaimer.
91  * 2. Redistributions in binary form must reproduce the above copyright
92  *    notice, this list of conditions and the following disclaimer in the
93  *    documentation and/or other materials provided with the distribution.
94  * 3. All advertising materials mentioning features or use of this software
95  *    must display the following acknowledgement:
96  *	This product includes software developed by the University of
97  *	California, Berkeley and its contributors.
98  * 4. Neither the name of the University nor the names of its contributors
99  *    may be used to endorse or promote products derived from this software
100  *    without specific prior written permission.
101  *
102  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
103  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
104  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
105  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
106  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
107  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
108  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
109  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
110  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
111  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
112  * SUCH DAMAGE.
113  *
114  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
115  */
116 
117 /*
118  *	TODO list for SYN cache stuff:
119  *
120  *	Find room for a "state" field, which is needed to keep a
121  *	compressed state for TIME_WAIT TCBs.  It's been noted already
122  *	that this is fairly important for very high-volume web and
123  *	mail servers, which use a large number of short-lived
124  *	connections.
125  */
126 
127 #include "opt_inet.h"
128 #include "opt_ipsec.h"
129 
130 #include <sys/param.h>
131 #include <sys/systm.h>
132 #include <sys/malloc.h>
133 #include <sys/mbuf.h>
134 #include <sys/protosw.h>
135 #include <sys/socket.h>
136 #include <sys/socketvar.h>
137 #include <sys/errno.h>
138 #include <sys/syslog.h>
139 #include <sys/pool.h>
140 #include <sys/domain.h>
141 
142 #include <net/if.h>
143 #include <net/route.h>
144 #include <net/if_types.h>
145 
146 #include <netinet/in.h>
147 #include <netinet/in_systm.h>
148 #include <netinet/ip.h>
149 #include <netinet/in_pcb.h>
150 #include <netinet/ip_var.h>
151 
152 #ifdef INET6
153 #ifndef INET
154 #include <netinet/in.h>
155 #endif
156 #include <netinet/ip6.h>
157 #include <netinet6/in6_pcb.h>
158 #include <netinet6/ip6_var.h>
159 #include <netinet6/in6_var.h>
160 #include <netinet/icmp6.h>
161 #endif
162 
163 #include <netinet/tcp.h>
164 #include <netinet/tcp_fsm.h>
165 #include <netinet/tcp_seq.h>
166 #include <netinet/tcp_timer.h>
167 #include <netinet/tcp_var.h>
168 #include <netinet/tcpip.h>
169 #include <netinet/tcp_debug.h>
170 
171 #include <machine/stdarg.h>
172 
173 #ifdef IPSEC
174 #include <netinet6/ipsec.h>
175 #include <netkey/key.h>
176 #include <netkey/key_debug.h>
177 #endif /*IPSEC*/
178 #ifdef INET6
179 #include "faith.h"
180 #endif
181 
182 int	tcprexmtthresh = 3;
183 int	tcp_log_refused;
184 
185 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
186 
187 /* for modulo comparisons of timestamps */
188 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
189 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
190 
191 /*
192  * Macro to compute ACK transmission behavior.  Delay the ACK unless
193  * we have already delayed an ACK (must send an ACK every two segments).
194  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
195  * option is enabled.
196  */
197 #define	TCP_SETUP_ACK(tp, th) \
198 do { \
199 	if ((tp)->t_flags & TF_DELACK || \
200 	    (tcp_ack_on_push && (th)->th_flags & TH_PUSH)) \
201 		tp->t_flags |= TF_ACKNOW; \
202 	else \
203 		TCP_SET_DELACK(tp); \
204 } while (0)
205 
206 int
207 tcp_reass(tp, th, m, tlen)
208 	register struct tcpcb *tp;
209 	register struct tcphdr *th;
210 	struct mbuf *m;
211 	int *tlen;
212 {
213 	register struct ipqent *p, *q, *nq, *tiqe = NULL;
214 	struct socket *so = NULL;
215 	int pkt_flags;
216 	tcp_seq pkt_seq;
217 	unsigned pkt_len;
218 	u_long rcvpartdupbyte = 0;
219 	u_long rcvoobyte;
220 
221 	if (tp->t_inpcb)
222 		so = tp->t_inpcb->inp_socket;
223 #ifdef INET6
224 	else if (tp->t_in6pcb)
225 		so = tp->t_in6pcb->in6p_socket;
226 #endif
227 
228 	TCP_REASS_LOCK_CHECK(tp);
229 
230 	/*
231 	 * Call with th==0 after become established to
232 	 * force pre-ESTABLISHED data up to user socket.
233 	 */
234 	if (th == 0)
235 		goto present;
236 
237 	rcvoobyte = *tlen;
238 	/*
239 	 * Copy these to local variables because the tcpiphdr
240 	 * gets munged while we are collapsing mbufs.
241 	 */
242 	pkt_seq = th->th_seq;
243 	pkt_len = *tlen;
244 	pkt_flags = th->th_flags;
245 	/*
246 	 * Find a segment which begins after this one does.
247 	 */
248 	for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
249 		nq = q->ipqe_q.le_next;
250 		/*
251 		 * If the received segment is just right after this
252 		 * fragment, merge the two together and then check
253 		 * for further overlaps.
254 		 */
255 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
256 #ifdef TCPREASS_DEBUG
257 			printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
258 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
259 			       q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
260 #endif
261 			pkt_len += q->ipqe_len;
262 			pkt_flags |= q->ipqe_flags;
263 			pkt_seq = q->ipqe_seq;
264 			m_cat(q->ipqe_m, m);
265 			m = q->ipqe_m;
266 			goto free_ipqe;
267 		}
268 		/*
269 		 * If the received segment is completely past this
270 		 * fragment, we need to go the next fragment.
271 		 */
272 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
273 			p = q;
274 			continue;
275 		}
276 		/*
277 		 * If the fragment is past the received segment,
278 		 * it (or any following) can't be concatenated.
279 		 */
280 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
281 			break;
282 		/*
283 		 * We've received all the data in this segment before.
284 		 * mark it as a duplicate and return.
285 		 */
286 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
287 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
288 			tcpstat.tcps_rcvduppack++;
289 			tcpstat.tcps_rcvdupbyte += pkt_len;
290 			m_freem(m);
291 			if (tiqe != NULL)
292 				pool_put(&ipqent_pool, tiqe);
293 			return (0);
294 		}
295 		/*
296 		 * Received segment completely overlaps this fragment
297 		 * so we drop the fragment (this keeps the temporal
298 		 * ordering of segments correct).
299 		 */
300 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
301 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
302 			rcvpartdupbyte += q->ipqe_len;
303 			m_freem(q->ipqe_m);
304 			goto free_ipqe;
305 		}
306 		/*
307 		 * RX'ed segment extends past the end of the
308 		 * fragment.  Drop the overlapping bytes.  Then
309 		 * merge the fragment and segment then treat as
310 		 * a longer received packet.
311 		 */
312 		if (SEQ_LT(q->ipqe_seq, pkt_seq)
313 		    && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
314 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
315 #ifdef TCPREASS_DEBUG
316 			printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
317 			       tp, overlap,
318 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
319 #endif
320 			m_adj(m, overlap);
321 			rcvpartdupbyte += overlap;
322 			m_cat(q->ipqe_m, m);
323 			m = q->ipqe_m;
324 			pkt_seq = q->ipqe_seq;
325 			pkt_len += q->ipqe_len - overlap;
326 			rcvoobyte -= overlap;
327 			goto free_ipqe;
328 		}
329 		/*
330 		 * RX'ed segment extends past the front of the
331 		 * fragment.  Drop the overlapping bytes on the
332 		 * received packet.  The packet will then be
333 		 * contatentated with this fragment a bit later.
334 		 */
335 		if (SEQ_GT(q->ipqe_seq, pkt_seq)
336 		    && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
337 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
338 #ifdef TCPREASS_DEBUG
339 			printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
340 			       tp, overlap,
341 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
342 #endif
343 			m_adj(m, -overlap);
344 			pkt_len -= overlap;
345 			rcvpartdupbyte += overlap;
346 			rcvoobyte -= overlap;
347 		}
348 		/*
349 		 * If the received segment immediates precedes this
350 		 * fragment then tack the fragment onto this segment
351 		 * and reinsert the data.
352 		 */
353 		if (q->ipqe_seq == pkt_seq + pkt_len) {
354 #ifdef TCPREASS_DEBUG
355 			printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
356 			       tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
357 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
358 #endif
359 			pkt_len += q->ipqe_len;
360 			pkt_flags |= q->ipqe_flags;
361 			m_cat(m, q->ipqe_m);
362 			LIST_REMOVE(q, ipqe_q);
363 			LIST_REMOVE(q, ipqe_timeq);
364 			if (tiqe == NULL) {
365 			    tiqe = q;
366 			} else {
367 			    pool_put(&ipqent_pool, q);
368 			}
369 			break;
370 		}
371 		/*
372 		 * If the fragment is before the segment, remember it.
373 		 * When this loop is terminated, p will contain the
374 		 * pointer to fragment that is right before the received
375 		 * segment.
376 		 */
377 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
378 			p = q;
379 
380 		continue;
381 
382 		/*
383 		 * This is a common operation.  It also will allow
384 		 * to save doing a malloc/free in most instances.
385 		 */
386 	  free_ipqe:
387 		LIST_REMOVE(q, ipqe_q);
388 		LIST_REMOVE(q, ipqe_timeq);
389 		if (tiqe == NULL) {
390 		    tiqe = q;
391 		} else {
392 		    pool_put(&ipqent_pool, q);
393 		}
394 	}
395 
396 	/*
397 	 * Allocate a new queue entry since the received segment did not
398 	 * collapse onto any other out-of-order block; thus we are allocating
399 	 * a new block.  If it had collapsed, tiqe would not be NULL and
400 	 * we would be reusing it.
401 	 * XXX If we can't, just drop the packet.  XXX
402 	 */
403 	if (tiqe == NULL) {
404 		tiqe = pool_get(&ipqent_pool, PR_NOWAIT);
405 		if (tiqe == NULL) {
406 			tcpstat.tcps_rcvmemdrop++;
407 			m_freem(m);
408 			return (0);
409 		}
410 	}
411 
412 	/*
413 	 * Update the counters.
414 	 */
415 	tcpstat.tcps_rcvoopack++;
416 	tcpstat.tcps_rcvoobyte += rcvoobyte;
417 	if (rcvpartdupbyte) {
418 	    tcpstat.tcps_rcvpartduppack++;
419 	    tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
420 	}
421 
422 	/*
423 	 * Insert the new fragment queue entry into both queues.
424 	 */
425 	tiqe->ipqe_m = m;
426 	tiqe->ipqe_seq = pkt_seq;
427 	tiqe->ipqe_len = pkt_len;
428 	tiqe->ipqe_flags = pkt_flags;
429 	if (p == NULL) {
430 		LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
431 #ifdef TCPREASS_DEBUG
432 		if (tiqe->ipqe_seq != tp->rcv_nxt)
433 			printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
434 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
435 #endif
436 	} else {
437 		LIST_INSERT_AFTER(p, tiqe, ipqe_q);
438 #ifdef TCPREASS_DEBUG
439 		printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
440 		       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
441 		       p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
442 #endif
443 	}
444 
445 	LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
446 
447 present:
448 	/*
449 	 * Present data to user, advancing rcv_nxt through
450 	 * completed sequence space.
451 	 */
452 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
453 		return (0);
454 	q = tp->segq.lh_first;
455 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
456 		return (0);
457 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
458 		return (0);
459 
460 	tp->rcv_nxt += q->ipqe_len;
461 	pkt_flags = q->ipqe_flags & TH_FIN;
462 
463 	LIST_REMOVE(q, ipqe_q);
464 	LIST_REMOVE(q, ipqe_timeq);
465 	if (so->so_state & SS_CANTRCVMORE)
466 		m_freem(q->ipqe_m);
467 	else
468 		sbappend(&so->so_rcv, q->ipqe_m);
469 	pool_put(&ipqent_pool, q);
470 	sorwakeup(so);
471 	return (pkt_flags);
472 }
473 
474 #if defined(INET6) && !defined(TCP6)
475 int
476 tcp6_input(mp, offp, proto)
477 	struct mbuf **mp;
478 	int *offp, proto;
479 {
480 	struct mbuf *m = *mp;
481 
482 #if defined(NFAITH) && 0 < NFAITH
483 	if (m->m_pkthdr.rcvif) {
484 		if (m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
485 			/* XXX send icmp6 host/port unreach? */
486 			m_freem(m);
487 			return IPPROTO_DONE;
488 		}
489 	}
490 #endif
491 
492 	/*
493 	 * draft-itojun-ipv6-tcp-to-anycast
494 	 * better place to put this in?
495 	 */
496 	if (m->m_flags & M_ANYCAST6) {
497 		if (m->m_len >= sizeof(struct ip6_hdr)) {
498 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
499 			icmp6_error(m, ICMP6_DST_UNREACH,
500 				ICMP6_DST_UNREACH_ADDR,
501 				(caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
502 		} else
503 			m_freem(m);
504 		return IPPROTO_DONE;
505 	}
506 
507 	tcp_input(m, *offp, proto);
508 	return IPPROTO_DONE;
509 }
510 #endif
511 
512 /*
513  * TCP input routine, follows pages 65-76 of the
514  * protocol specification dated September, 1981 very closely.
515  */
516 void
517 #if __STDC__
518 tcp_input(struct mbuf *m, ...)
519 #else
520 tcp_input(m, va_alist)
521 	register struct mbuf *m;
522 #endif
523 {
524 	int proto;
525 	register struct tcphdr *th;
526 	struct ip *ip;
527 	register struct inpcb *inp;
528 #ifdef INET6
529 	struct ip6_hdr *ip6;
530 	register struct in6pcb *in6p;
531 #endif
532 	caddr_t optp = NULL;
533 	int optlen = 0;
534 	int len, tlen, toff, hdroptlen = 0;
535 	register struct tcpcb *tp = 0;
536 	register int tiflags;
537 	struct socket *so = NULL;
538 	int todrop, acked, ourfinisacked, needoutput = 0;
539 	short ostate = 0;
540 	int iss = 0;
541 	u_long tiwin;
542 	struct tcp_opt_info opti;
543 	int off, iphlen;
544 	va_list ap;
545 	int af;		/* af on the wire */
546 	struct mbuf *tcp_saveti = NULL;
547 
548 	va_start(ap, m);
549 	toff = va_arg(ap, int);
550 	proto = va_arg(ap, int);
551 	va_end(ap);
552 
553 	tcpstat.tcps_rcvtotal++;
554 
555 	bzero(&opti, sizeof(opti));
556 	opti.ts_present = 0;
557 	opti.maxseg = 0;
558 
559 	/*
560 	 * Get IP and TCP header together in first mbuf.
561 	 * Note: IP leaves IP header in first mbuf.
562 	 */
563 	ip = mtod(m, struct ip *);
564 #ifdef INET6
565 	ip6 = NULL;
566 #endif
567 	switch (ip->ip_v) {
568 	case 4:
569 		af = AF_INET;
570 		iphlen = sizeof(struct ip);
571 		/* would like to get rid of this... */
572 		if (toff > sizeof (struct ip)) {
573 			ip_stripoptions(m, (struct mbuf *)0);
574 			toff = sizeof(struct ip);
575 		}
576 		if (m->m_len < toff + sizeof (struct tcphdr)) {
577 			if ((m = m_pullup(m, toff + sizeof (struct tcphdr))) == 0) {
578 				tcpstat.tcps_rcvshort++;
579 				return;
580 			}
581 		}
582 		ip = mtod(m, struct ip *);
583 		th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
584 
585 		/*
586 		 * Checksum extended TCP header and data.
587 		 */
588 		len = ip->ip_len;
589 		tlen = len - toff;
590 	    {
591 		struct ipovly *ipov;
592 		ipov = (struct ipovly *)ip;
593 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
594 		ipov->ih_len = htons(tlen);
595 	    }
596 		if (in_cksum(m, len) != 0) {
597 			tcpstat.tcps_rcvbadsum++;
598 			goto drop;
599 		}
600 		break;
601 #ifdef INET6
602 	case 6:
603 		ip = NULL;
604 		iphlen = sizeof(struct ip6_hdr);
605 		af = AF_INET6;
606 		if (m->m_len < toff + sizeof(struct tcphdr)) {
607 			m = m_pullup(m, toff + sizeof(struct tcphdr));	/*XXX*/
608 			if (m == NULL) {
609 				tcpstat.tcps_rcvshort++;
610 				return;
611 			}
612 		}
613 		ip6 = mtod(m, struct ip6_hdr *);
614 		th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
615 
616 		/*
617 		 * Checksum extended TCP header and data.
618 		 */
619 		len = m->m_pkthdr.len;
620 		tlen = len - toff;
621 		if (in6_cksum(m, IPPROTO_TCP, toff, tlen)) {
622 			tcpstat.tcps_rcvbadsum++;
623 			goto drop;
624 		}
625 		break;
626 #endif
627 	default:
628 		m_freem(m);
629 		return;
630 	}
631 
632 	/*
633 	 * Check that TCP offset makes sense,
634 	 * pull out TCP options and adjust length.		XXX
635 	 */
636 	off = th->th_off << 2;
637 	if (off < sizeof (struct tcphdr) || off > tlen) {
638 		tcpstat.tcps_rcvbadoff++;
639 		goto drop;
640 	}
641 	tlen -= off;
642 
643 	/*
644 	 * tcp_input() has been modified to use tlen to mean the TCP data
645 	 * length throughout the function.  Other functions can use
646 	 * m->m_pkthdr.len as the basis for calculating the TCP data length.
647 	 * rja
648 	 */
649 
650 	if (off > sizeof (struct tcphdr)) {
651 		if (m->m_len < toff + off) {
652 			if ((m = m_pullup(m, toff + off)) == 0) {
653 				tcpstat.tcps_rcvshort++;
654 				return;
655 			}
656 			switch (af) {
657 			case AF_INET:
658 				ip = mtod(m, struct ip *);
659 				break;
660 #ifdef INET6
661 			case AF_INET6:
662 				ip6 = mtod(m, struct ip6_hdr *);
663 				break;
664 #endif
665 			}
666 			th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
667 		}
668 		optlen = off - sizeof (struct tcphdr);
669 		optp = mtod(m, caddr_t) + toff + sizeof (struct tcphdr);
670 		/*
671 		 * Do quick retrieval of timestamp options ("options
672 		 * prediction?").  If timestamp is the only option and it's
673 		 * formatted as recommended in RFC 1323 appendix A, we
674 		 * quickly get the values now and not bother calling
675 		 * tcp_dooptions(), etc.
676 		 */
677 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
678 		     (optlen > TCPOLEN_TSTAMP_APPA &&
679 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
680 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
681 		     (th->th_flags & TH_SYN) == 0) {
682 			opti.ts_present = 1;
683 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
684 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
685 			optp = NULL;	/* we've parsed the options */
686 		}
687 	}
688 	tiflags = th->th_flags;
689 
690 	/*
691 	 * Convert TCP protocol specific fields to host format.
692 	 */
693 	NTOHL(th->th_seq);
694 	NTOHL(th->th_ack);
695 	NTOHS(th->th_win);
696 	NTOHS(th->th_urp);
697 
698 	/*
699 	 * Locate pcb for segment.
700 	 */
701 findpcb:
702 	inp = NULL;
703 #ifdef INET6
704 	in6p = NULL;
705 #endif
706 	switch (af) {
707 	case AF_INET:
708 		inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
709 		    ip->ip_dst, th->th_dport);
710 		if (inp == 0) {
711 			++tcpstat.tcps_pcbhashmiss;
712 			inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
713 		}
714 #if defined(INET6) && !defined(TCP6)
715 		if (inp == 0) {
716 			struct in6_addr s, d;
717 
718 			/* mapped addr case */
719 			bzero(&s, sizeof(s));
720 			s.s6_addr16[5] = htons(0xffff);
721 			bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
722 			bzero(&d, sizeof(d));
723 			d.s6_addr16[5] = htons(0xffff);
724 			bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
725 			in6p = in6_pcblookup_connect(&tcb6, &s, th->th_sport,
726 				&d, th->th_dport, 0);
727 			if (in6p == 0) {
728 				++tcpstat.tcps_pcbhashmiss;
729 				in6p = in6_pcblookup_bind(&tcb6, &d,
730 					th->th_dport, 0);
731 			}
732 		}
733 #endif
734 #ifndef INET6
735 		if (inp == 0)
736 #else
737 		if (inp == 0 && in6p == 0)
738 #endif
739 		{
740 			++tcpstat.tcps_noport;
741 			if (tcp_log_refused && (tiflags & TH_SYN)) {
742 #ifndef INET6
743 				char src[4*sizeof "123"];
744 				char dst[4*sizeof "123"];
745 #else
746 				char src[INET6_ADDRSTRLEN];
747 				char dst[INET6_ADDRSTRLEN];
748 #endif
749 				if (ip) {
750 					strcpy(src, inet_ntoa(ip->ip_src));
751 					strcpy(dst, inet_ntoa(ip->ip_dst));
752 				}
753 #ifdef INET6
754 				else if (ip6) {
755 					strcpy(src, ip6_sprintf(&ip6->ip6_src));
756 					strcpy(dst, ip6_sprintf(&ip6->ip6_dst));
757 				}
758 #endif
759 				else {
760 					strcpy(src, "(unknown)");
761 					strcpy(dst, "(unknown)");
762 				}
763 				log(LOG_INFO,
764 				    "Connection attempt to TCP %s:%d from %s:%d\n",
765 				    dst, ntohs(th->th_dport),
766 				    src, ntohs(th->th_sport));
767 			}
768 			goto dropwithreset;
769 		}
770 #ifdef IPSEC
771 		if (inp && ipsec4_in_reject(m, inp)) {
772 			ipsecstat.in_polvio++;
773 			goto drop;
774 		}
775 #ifdef INET6
776 		else if (in6p && ipsec4_in_reject_so(m, in6p->in6p_socket)) {
777 			ipsecstat.in_polvio++;
778 			goto drop;
779 		}
780 #endif
781 #endif /*IPSEC*/
782 		break;
783 #if defined(INET6) && !defined(TCP6)
784 	case AF_INET6:
785 	    {
786 		int faith;
787 
788 #if defined(NFAITH) && NFAITH > 0
789 		if (m->m_pkthdr.rcvif
790 		 && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
791 			faith = 1;
792 		} else
793 			faith = 0;
794 #else
795 		faith = 0;
796 #endif
797 		in6p = in6_pcblookup_connect(&tcb6, &ip6->ip6_src, th->th_sport,
798 			&ip6->ip6_dst, th->th_dport, faith);
799 		if (in6p == NULL) {
800 			++tcpstat.tcps_pcbhashmiss;
801 			in6p = in6_pcblookup_bind(&tcb6, &ip6->ip6_dst,
802 				th->th_dport, faith);
803 		}
804 		if (in6p == NULL) {
805 			++tcpstat.tcps_noport;
806 			goto dropwithreset;
807 		}
808 #ifdef IPSEC
809 		if (ipsec6_in_reject(m, in6p)) {
810 			ipsec6stat.in_polvio++;
811 			goto drop;
812 		}
813 #endif /*IPSEC*/
814 		break;
815 	    }
816 #endif
817 	}
818 
819 	/*
820 	 * If the state is CLOSED (i.e., TCB does not exist) then
821 	 * all data in the incoming segment is discarded.
822 	 * If the TCB exists but is in CLOSED state, it is embryonic,
823 	 * but should either do a listen or a connect soon.
824 	 */
825 	tp = NULL;
826 	so = NULL;
827 	if (inp) {
828 		tp = intotcpcb(inp);
829 		so = inp->inp_socket;
830 	}
831 #ifdef INET6
832 	else if (in6p) {
833 		tp = in6totcpcb(in6p);
834 		so = in6p->in6p_socket;
835 	}
836 #endif
837 	if (tp == 0) {
838 		goto dropwithreset;
839 	}
840 	if (tp->t_state == TCPS_CLOSED)
841 		goto drop;
842 
843 	/* Unscale the window into a 32-bit value. */
844 	if ((tiflags & TH_SYN) == 0)
845 		tiwin = th->th_win << tp->snd_scale;
846 	else
847 		tiwin = th->th_win;
848 
849 #ifdef INET6
850 	/* save packet options if user wanted */
851 	if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
852 		if (in6p->in6p_options) {
853 			m_freem(in6p->in6p_options);
854 			in6p->in6p_options = 0;
855 		}
856 		ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
857 	}
858 #endif
859 
860 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
861 		union syn_cache_sa src;
862 		union syn_cache_sa dst;
863 
864 		bzero(&src, sizeof(src));
865 		bzero(&dst, sizeof(dst));
866 		switch (af) {
867 		case AF_INET:
868 			src.sin.sin_len = sizeof(struct sockaddr_in);
869 			src.sin.sin_family = AF_INET;
870 			src.sin.sin_addr = ip->ip_src;
871 			src.sin.sin_port = th->th_sport;
872 
873 			dst.sin.sin_len = sizeof(struct sockaddr_in);
874 			dst.sin.sin_family = AF_INET;
875 			dst.sin.sin_addr = ip->ip_dst;
876 			dst.sin.sin_port = th->th_dport;
877 			break;
878 #ifdef INET6
879 		case AF_INET6:
880 			src.sin6.sin6_len = sizeof(struct sockaddr_in6);
881 			src.sin6.sin6_family = AF_INET6;
882 			src.sin6.sin6_addr = ip6->ip6_src;
883 			src.sin6.sin6_port = th->th_sport;
884 
885 			dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
886 			dst.sin6.sin6_family = AF_INET6;
887 			dst.sin6.sin6_addr = ip6->ip6_dst;
888 			dst.sin6.sin6_port = th->th_dport;
889 			break;
890 #endif /* INET6 */
891 		default:
892 			goto badsyn;	/*sanity*/
893 		}
894 
895 		if (so->so_options & SO_DEBUG) {
896 			ostate = tp->t_state;
897 			tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
898 			if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
899 				m_freem(tcp_saveti);
900 				tcp_saveti = NULL;
901 			} else {
902 				tcp_saveti->m_len += sizeof(struct tcphdr);
903 				bcopy(th, mtod(tcp_saveti, caddr_t) + iphlen,
904 					sizeof(struct tcphdr));
905 			}
906 			if (tcp_saveti) {
907 				/*
908 				 * need to recover version # field, which was
909 				 * overwritten on ip_cksum computation.
910 				 */
911 				struct ip *sip;
912 				sip = mtod(tcp_saveti, struct ip *);
913 				switch (af) {
914 				case AF_INET:
915 					sip->ip_v = 4;
916 					break;
917 #ifdef INET6
918 				case AF_INET6:
919 					sip->ip_v = 6;
920 					break;
921 #endif
922 				}
923 			}
924 		}
925 		if (so->so_options & SO_ACCEPTCONN) {
926   			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
927 				if (tiflags & TH_RST) {
928 					syn_cache_reset(&src.sa, &dst.sa, th);
929 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
930 				    (TH_ACK|TH_SYN)) {
931 					/*
932 					 * Received a SYN,ACK.  This should
933 					 * never happen while we are in
934 					 * LISTEN.  Send an RST.
935 					 */
936 					goto badsyn;
937 				} else if (tiflags & TH_ACK) {
938 					so = syn_cache_get(&src.sa, &dst.sa,
939 						th, toff, tlen, so, m);
940 					if (so == NULL) {
941 						/*
942 						 * We don't have a SYN for
943 						 * this ACK; send an RST.
944 						 */
945 						goto badsyn;
946 					} else if (so ==
947 					    (struct socket *)(-1)) {
948 						/*
949 						 * We were unable to create
950 						 * the connection.  If the
951 						 * 3-way handshake was
952 						 * completed, and RST has
953 						 * been sent to the peer.
954 						 * Since the mbuf might be
955 						 * in use for the reply,
956 						 * do not free it.
957 						 */
958 						m = NULL;
959 					} else {
960 						/*
961 						 * We have created a
962 						 * full-blown connection.
963 						 */
964 						tp = NULL;
965 						inp = NULL;
966 #ifdef INET6
967 						in6p = NULL;
968 #endif
969 						switch (so->so_proto->pr_domain->dom_family) {
970 						case AF_INET:
971 							inp = sotoinpcb(so);
972 							tp = intotcpcb(inp);
973 							break;
974 #ifdef INET6
975 						case AF_INET6:
976 							in6p = sotoin6pcb(so);
977 							tp = in6totcpcb(in6p);
978 							break;
979 #endif
980 						}
981 						if (tp == NULL)
982 							goto badsyn;	/*XXX*/
983 						tiwin <<= tp->snd_scale;
984 						goto after_listen;
985 					}
986   				} else {
987 					/*
988 					 * None of RST, SYN or ACK was set.
989 					 * This is an invalid packet for a
990 					 * TCB in LISTEN state.  Send a RST.
991 					 */
992 					goto badsyn;
993 				}
994   			} else {
995 				/*
996 				 * Received a SYN.
997 				 */
998 
999 				/*
1000 				 * LISTEN socket received a SYN
1001 				 * from itself?  This can't possibly
1002 				 * be valid; drop the packet.
1003 				 */
1004 				if (th->th_sport == th->th_dport) {
1005 					int i;
1006 
1007 					switch (af) {
1008 					case AF_INET:
1009 						i = in_hosteq(ip->ip_src, ip->ip_dst);
1010 						break;
1011 #ifdef INET6
1012 					case AF_INET6:
1013 						i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1014 						break;
1015 #endif
1016 					default:
1017 						i = 1;
1018 					}
1019 					if (i) {
1020 						tcpstat.tcps_badsyn++;
1021 						goto drop;
1022 					}
1023 				}
1024 
1025 				/*
1026 				 * SYN looks ok; create compressed TCP
1027 				 * state for it.
1028 				 */
1029 				if (so->so_qlen <= so->so_qlimit &&
1030 				    syn_cache_add(&src.sa, &dst.sa, th, tlen,
1031 						so, m, optp, optlen, &opti))
1032 					m = NULL;
1033 			}
1034 			goto drop;
1035 		}
1036 	}
1037 
1038 after_listen:
1039 #ifdef DIAGNOSTIC
1040 	/*
1041 	 * Should not happen now that all embryonic connections
1042 	 * are handled with compressed state.
1043 	 */
1044 	if (tp->t_state == TCPS_LISTEN)
1045 		panic("tcp_input: TCPS_LISTEN");
1046 #endif
1047 
1048 	/*
1049 	 * Segment received on connection.
1050 	 * Reset idle time and keep-alive timer.
1051 	 */
1052 	tp->t_idle = 0;
1053 	if (TCPS_HAVEESTABLISHED(tp->t_state))
1054 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1055 
1056 	/*
1057 	 * Process options.
1058 	 */
1059 	if (optp)
1060 		tcp_dooptions(tp, optp, optlen, th, &opti);
1061 
1062 	/*
1063 	 * Header prediction: check for the two common cases
1064 	 * of a uni-directional data xfer.  If the packet has
1065 	 * no control flags, is in-sequence, the window didn't
1066 	 * change and we're not retransmitting, it's a
1067 	 * candidate.  If the length is zero and the ack moved
1068 	 * forward, we're the sender side of the xfer.  Just
1069 	 * free the data acked & wake any higher level process
1070 	 * that was blocked waiting for space.  If the length
1071 	 * is non-zero and the ack didn't move, we're the
1072 	 * receiver side.  If we're getting packets in-order
1073 	 * (the reassembly queue is empty), add the data to
1074 	 * the socket buffer and note that we need a delayed ack.
1075 	 */
1076 	if (tp->t_state == TCPS_ESTABLISHED &&
1077 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1078 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1079 	    th->th_seq == tp->rcv_nxt &&
1080 	    tiwin && tiwin == tp->snd_wnd &&
1081 	    tp->snd_nxt == tp->snd_max) {
1082 
1083 		/*
1084 		 * If last ACK falls within this segment's sequence numbers,
1085 		 *  record the timestamp.
1086 		 */
1087 		if (opti.ts_present &&
1088 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1089 		    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen)) {
1090 			tp->ts_recent_age = tcp_now;
1091 			tp->ts_recent = opti.ts_val;
1092 		}
1093 
1094 		if (tlen == 0) {
1095 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1096 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1097 			    tp->snd_cwnd >= tp->snd_wnd &&
1098 			    tp->t_dupacks < tcprexmtthresh) {
1099 				/*
1100 				 * this is a pure ack for outstanding data.
1101 				 */
1102 				++tcpstat.tcps_predack;
1103 				if (opti.ts_present && opti.ts_ecr)
1104 					tcp_xmit_timer(tp,
1105 					    tcp_now - opti.ts_ecr + 1);
1106 				else if (tp->t_rtt &&
1107 				    SEQ_GT(th->th_ack, tp->t_rtseq))
1108 					tcp_xmit_timer(tp, tp->t_rtt);
1109 				acked = th->th_ack - tp->snd_una;
1110 				tcpstat.tcps_rcvackpack++;
1111 				tcpstat.tcps_rcvackbyte += acked;
1112 				sbdrop(&so->so_snd, acked);
1113 				/*
1114 				 * We want snd_recover to track snd_una to
1115 				 * avoid sequence wraparound problems for
1116 				 * very large transfers.
1117 				 */
1118 				tp->snd_una = tp->snd_recover = th->th_ack;
1119 				m_freem(m);
1120 
1121 				/*
1122 				 * If all outstanding data are acked, stop
1123 				 * retransmit timer, otherwise restart timer
1124 				 * using current (possibly backed-off) value.
1125 				 * If process is waiting for space,
1126 				 * wakeup/selwakeup/signal.  If data
1127 				 * are ready to send, let tcp_output
1128 				 * decide between more output or persist.
1129 				 */
1130 				if (tp->snd_una == tp->snd_max)
1131 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
1132 				else if (TCP_TIMER_ISARMED(tp,
1133 				    TCPT_PERSIST) == 0)
1134 					TCP_TIMER_ARM(tp, TCPT_REXMT,
1135 					    tp->t_rxtcur);
1136 
1137 				sowwakeup(so);
1138 				if (so->so_snd.sb_cc)
1139 					(void) tcp_output(tp);
1140 				if (tcp_saveti)
1141 					m_freem(tcp_saveti);
1142 				return;
1143 			}
1144 		} else if (th->th_ack == tp->snd_una &&
1145 		    tp->segq.lh_first == NULL &&
1146 		    tlen <= sbspace(&so->so_rcv)) {
1147 			/*
1148 			 * this is a pure, in-sequence data packet
1149 			 * with nothing on the reassembly queue and
1150 			 * we have enough buffer space to take it.
1151 			 */
1152 			++tcpstat.tcps_preddat;
1153 			tp->rcv_nxt += tlen;
1154 			tcpstat.tcps_rcvpack++;
1155 			tcpstat.tcps_rcvbyte += tlen;
1156 			/*
1157 			 * Drop TCP, IP headers and TCP options then add data
1158 			 * to socket buffer.
1159 			 */
1160 			m->m_data += toff + off;
1161 			m->m_len -= (toff + off);
1162 			sbappend(&so->so_rcv, m);
1163 			sorwakeup(so);
1164 			TCP_SETUP_ACK(tp, th);
1165 			if (tp->t_flags & TF_ACKNOW)
1166 				(void) tcp_output(tp);
1167 			if (tcp_saveti)
1168 				m_freem(tcp_saveti);
1169 			return;
1170 		}
1171 	}
1172 
1173 	/*
1174 	 * Drop TCP, IP headers and TCP options.
1175 	 */
1176 	hdroptlen  = toff + off;
1177 	m->m_data += hdroptlen;
1178 	m->m_len  -= hdroptlen;
1179 
1180 	/*
1181 	 * Calculate amount of space in receive window,
1182 	 * and then do TCP input processing.
1183 	 * Receive window is amount of space in rcv queue,
1184 	 * but not less than advertised window.
1185 	 */
1186 	{ int win;
1187 
1188 	win = sbspace(&so->so_rcv);
1189 	if (win < 0)
1190 		win = 0;
1191 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1192 	}
1193 
1194 	switch (tp->t_state) {
1195 
1196 	/*
1197 	 * If the state is SYN_SENT:
1198 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1199 	 *	if seg contains a RST, then drop the connection.
1200 	 *	if seg does not contain SYN, then drop it.
1201 	 * Otherwise this is an acceptable SYN segment
1202 	 *	initialize tp->rcv_nxt and tp->irs
1203 	 *	if seg contains ack then advance tp->snd_una
1204 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1205 	 *	arrange for segment to be acked (eventually)
1206 	 *	continue processing rest of data/controls, beginning with URG
1207 	 */
1208 	case TCPS_SYN_SENT:
1209 		if ((tiflags & TH_ACK) &&
1210 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1211 		     SEQ_GT(th->th_ack, tp->snd_max)))
1212 			goto dropwithreset;
1213 		if (tiflags & TH_RST) {
1214 			if (tiflags & TH_ACK)
1215 				tp = tcp_drop(tp, ECONNREFUSED);
1216 			goto drop;
1217 		}
1218 		if ((tiflags & TH_SYN) == 0)
1219 			goto drop;
1220 		if (tiflags & TH_ACK) {
1221 			tp->snd_una = tp->snd_recover = th->th_ack;
1222 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1223 				tp->snd_nxt = tp->snd_una;
1224 		}
1225 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
1226 		tp->irs = th->th_seq;
1227 		tcp_rcvseqinit(tp);
1228 		tp->t_flags |= TF_ACKNOW;
1229 		tcp_mss_from_peer(tp, opti.maxseg);
1230 
1231 		/*
1232 		 * Initialize the initial congestion window.  If we
1233 		 * had to retransmit the SYN, we must initialize cwnd
1234 		 * to 1 segment (i.e. the Loss Window).
1235 		 */
1236 		if (tp->t_flags & TF_SYN_REXMT)
1237 			tp->snd_cwnd = tp->t_peermss;
1238 		else
1239 			tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win,
1240 			    tp->t_peermss);
1241 
1242 		tcp_rmx_rtt(tp);
1243 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
1244 			tcpstat.tcps_connects++;
1245 			soisconnected(so);
1246 			tcp_established(tp);
1247 			/* Do window scaling on this connection? */
1248 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1249 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1250 				tp->snd_scale = tp->requested_s_scale;
1251 				tp->rcv_scale = tp->request_r_scale;
1252 			}
1253 			TCP_REASS_LOCK(tp);
1254 			(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1255 			TCP_REASS_UNLOCK(tp);
1256 			/*
1257 			 * if we didn't have to retransmit the SYN,
1258 			 * use its rtt as our initial srtt & rtt var.
1259 			 */
1260 			if (tp->t_rtt)
1261 				tcp_xmit_timer(tp, tp->t_rtt);
1262 		} else
1263 			tp->t_state = TCPS_SYN_RECEIVED;
1264 
1265 		/*
1266 		 * Advance th->th_seq to correspond to first data byte.
1267 		 * If data, trim to stay within window,
1268 		 * dropping FIN if necessary.
1269 		 */
1270 		th->th_seq++;
1271 		if (tlen > tp->rcv_wnd) {
1272 			todrop = tlen - tp->rcv_wnd;
1273 			m_adj(m, -todrop);
1274 			tlen = tp->rcv_wnd;
1275 			tiflags &= ~TH_FIN;
1276 			tcpstat.tcps_rcvpackafterwin++;
1277 			tcpstat.tcps_rcvbyteafterwin += todrop;
1278 		}
1279 		tp->snd_wl1 = th->th_seq - 1;
1280 		tp->rcv_up = th->th_seq;
1281 		goto step6;
1282 
1283 	/*
1284 	 * If the state is SYN_RECEIVED:
1285 	 *	If seg contains an ACK, but not for our SYN, drop the input
1286 	 *	and generate an RST.  See page 36, rfc793
1287 	 */
1288 	case TCPS_SYN_RECEIVED:
1289 		if ((tiflags & TH_ACK) &&
1290 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1291 		     SEQ_GT(th->th_ack, tp->snd_max)))
1292 			goto dropwithreset;
1293 		break;
1294 	}
1295 
1296 	/*
1297 	 * States other than LISTEN or SYN_SENT.
1298 	 * First check timestamp, if present.
1299 	 * Then check that at least some bytes of segment are within
1300 	 * receive window.  If segment begins before rcv_nxt,
1301 	 * drop leading data (and SYN); if nothing left, just ack.
1302 	 *
1303 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1304 	 * and it's less than ts_recent, drop it.
1305 	 */
1306 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1307 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
1308 
1309 		/* Check to see if ts_recent is over 24 days old.  */
1310 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1311 			/*
1312 			 * Invalidate ts_recent.  If this segment updates
1313 			 * ts_recent, the age will be reset later and ts_recent
1314 			 * will get a valid value.  If it does not, setting
1315 			 * ts_recent to zero will at least satisfy the
1316 			 * requirement that zero be placed in the timestamp
1317 			 * echo reply when ts_recent isn't valid.  The
1318 			 * age isn't reset until we get a valid ts_recent
1319 			 * because we don't want out-of-order segments to be
1320 			 * dropped when ts_recent is old.
1321 			 */
1322 			tp->ts_recent = 0;
1323 		} else {
1324 			tcpstat.tcps_rcvduppack++;
1325 			tcpstat.tcps_rcvdupbyte += tlen;
1326 			tcpstat.tcps_pawsdrop++;
1327 			goto dropafterack;
1328 		}
1329 	}
1330 
1331 	todrop = tp->rcv_nxt - th->th_seq;
1332 	if (todrop > 0) {
1333 		if (tiflags & TH_SYN) {
1334 			tiflags &= ~TH_SYN;
1335 			th->th_seq++;
1336 			if (th->th_urp > 1)
1337 				th->th_urp--;
1338 			else {
1339 				tiflags &= ~TH_URG;
1340 				th->th_urp = 0;
1341 			}
1342 			todrop--;
1343 		}
1344 		if (todrop > tlen ||
1345 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1346 			/*
1347 			 * Any valid FIN must be to the left of the window.
1348 			 * At this point the FIN must be a duplicate or
1349 			 * out of sequence; drop it.
1350 			 */
1351 			tiflags &= ~TH_FIN;
1352 			/*
1353 			 * Send an ACK to resynchronize and drop any data.
1354 			 * But keep on processing for RST or ACK.
1355 			 */
1356 			tp->t_flags |= TF_ACKNOW;
1357 			todrop = tlen;
1358 			tcpstat.tcps_rcvdupbyte += todrop;
1359 			tcpstat.tcps_rcvduppack++;
1360 		} else {
1361 			tcpstat.tcps_rcvpartduppack++;
1362 			tcpstat.tcps_rcvpartdupbyte += todrop;
1363 		}
1364 		m_adj(m, todrop);
1365 		th->th_seq += todrop;
1366 		tlen -= todrop;
1367 		if (th->th_urp > todrop)
1368 			th->th_urp -= todrop;
1369 		else {
1370 			tiflags &= ~TH_URG;
1371 			th->th_urp = 0;
1372 		}
1373 	}
1374 
1375 	/*
1376 	 * If new data are received on a connection after the
1377 	 * user processes are gone, then RST the other end.
1378 	 */
1379 	if ((so->so_state & SS_NOFDREF) &&
1380 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1381 		tp = tcp_close(tp);
1382 		tcpstat.tcps_rcvafterclose++;
1383 		goto dropwithreset;
1384 	}
1385 
1386 	/*
1387 	 * If segment ends after window, drop trailing data
1388 	 * (and PUSH and FIN); if nothing left, just ACK.
1389 	 */
1390 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1391 	if (todrop > 0) {
1392 		tcpstat.tcps_rcvpackafterwin++;
1393 		if (todrop >= tlen) {
1394 			tcpstat.tcps_rcvbyteafterwin += tlen;
1395 			/*
1396 			 * If a new connection request is received
1397 			 * while in TIME_WAIT, drop the old connection
1398 			 * and start over if the sequence numbers
1399 			 * are above the previous ones.
1400 			 */
1401 			if (tiflags & TH_SYN &&
1402 			    tp->t_state == TCPS_TIME_WAIT &&
1403 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1404 				iss = tcp_new_iss(tp, sizeof(struct tcpcb),
1405 						  tp->snd_nxt);
1406 				tp = tcp_close(tp);
1407 				/*
1408 				 * We have already advanced the mbuf
1409 				 * pointers past the IP+TCP headers and
1410 				 * options.  Restore those pointers before
1411 				 * attempting to use the TCP header again.
1412 				 */
1413 				m->m_data -= hdroptlen;
1414 				m->m_len  += hdroptlen;
1415 				hdroptlen = 0;
1416 				goto findpcb;
1417 			}
1418 			/*
1419 			 * If window is closed can only take segments at
1420 			 * window edge, and have to drop data and PUSH from
1421 			 * incoming segments.  Continue processing, but
1422 			 * remember to ack.  Otherwise, drop segment
1423 			 * and ack.
1424 			 */
1425 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1426 				tp->t_flags |= TF_ACKNOW;
1427 				tcpstat.tcps_rcvwinprobe++;
1428 			} else
1429 				goto dropafterack;
1430 		} else
1431 			tcpstat.tcps_rcvbyteafterwin += todrop;
1432 		m_adj(m, -todrop);
1433 		tlen -= todrop;
1434 		tiflags &= ~(TH_PUSH|TH_FIN);
1435 	}
1436 
1437 	/*
1438 	 * If last ACK falls within this segment's sequence numbers,
1439 	 * and the timestamp is newer, record it.
1440 	 */
1441 	if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
1442 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1443 	    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
1444 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1445 		tp->ts_recent_age = tcp_now;
1446 		tp->ts_recent = opti.ts_val;
1447 	}
1448 
1449 	/*
1450 	 * If the RST bit is set examine the state:
1451 	 *    SYN_RECEIVED STATE:
1452 	 *	If passive open, return to LISTEN state.
1453 	 *	If active open, inform user that connection was refused.
1454 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1455 	 *	Inform user that connection was reset, and close tcb.
1456 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
1457 	 *	Close the tcb.
1458 	 */
1459 	if (tiflags&TH_RST) switch (tp->t_state) {
1460 
1461 	case TCPS_SYN_RECEIVED:
1462 		so->so_error = ECONNREFUSED;
1463 		goto close;
1464 
1465 	case TCPS_ESTABLISHED:
1466 	case TCPS_FIN_WAIT_1:
1467 	case TCPS_FIN_WAIT_2:
1468 	case TCPS_CLOSE_WAIT:
1469 		so->so_error = ECONNRESET;
1470 	close:
1471 		tp->t_state = TCPS_CLOSED;
1472 		tcpstat.tcps_drops++;
1473 		tp = tcp_close(tp);
1474 		goto drop;
1475 
1476 	case TCPS_CLOSING:
1477 	case TCPS_LAST_ACK:
1478 	case TCPS_TIME_WAIT:
1479 		tp = tcp_close(tp);
1480 		goto drop;
1481 	}
1482 
1483 	/*
1484 	 * If a SYN is in the window, then this is an
1485 	 * error and we send an RST and drop the connection.
1486 	 */
1487 	if (tiflags & TH_SYN) {
1488 		tp = tcp_drop(tp, ECONNRESET);
1489 		goto dropwithreset;
1490 	}
1491 
1492 	/*
1493 	 * If the ACK bit is off we drop the segment and return.
1494 	 */
1495 	if ((tiflags & TH_ACK) == 0) {
1496 		if (tp->t_flags & TF_ACKNOW)
1497 			goto dropafterack;
1498 		else
1499 			goto drop;
1500 	}
1501 
1502 	/*
1503 	 * Ack processing.
1504 	 */
1505 	switch (tp->t_state) {
1506 
1507 	/*
1508 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
1509 	 * ESTABLISHED state and continue processing, otherwise
1510 	 * send an RST.
1511 	 */
1512 	case TCPS_SYN_RECEIVED:
1513 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
1514 		    SEQ_GT(th->th_ack, tp->snd_max))
1515 			goto dropwithreset;
1516 		tcpstat.tcps_connects++;
1517 		soisconnected(so);
1518 		tcp_established(tp);
1519 		/* Do window scaling? */
1520 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1521 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1522 			tp->snd_scale = tp->requested_s_scale;
1523 			tp->rcv_scale = tp->request_r_scale;
1524 		}
1525 		TCP_REASS_LOCK(tp);
1526 		(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1527 		TCP_REASS_UNLOCK(tp);
1528 		tp->snd_wl1 = th->th_seq - 1;
1529 		/* fall into ... */
1530 
1531 	/*
1532 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1533 	 * ACKs.  If the ack is in the range
1534 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1535 	 * then advance tp->snd_una to th->th_ack and drop
1536 	 * data from the retransmission queue.  If this ACK reflects
1537 	 * more up to date window information we update our window information.
1538 	 */
1539 	case TCPS_ESTABLISHED:
1540 	case TCPS_FIN_WAIT_1:
1541 	case TCPS_FIN_WAIT_2:
1542 	case TCPS_CLOSE_WAIT:
1543 	case TCPS_CLOSING:
1544 	case TCPS_LAST_ACK:
1545 	case TCPS_TIME_WAIT:
1546 
1547 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1548 			if (tlen == 0 && tiwin == tp->snd_wnd) {
1549 				tcpstat.tcps_rcvdupack++;
1550 				/*
1551 				 * If we have outstanding data (other than
1552 				 * a window probe), this is a completely
1553 				 * duplicate ack (ie, window info didn't
1554 				 * change), the ack is the biggest we've
1555 				 * seen and we've seen exactly our rexmt
1556 				 * threshhold of them, assume a packet
1557 				 * has been dropped and retransmit it.
1558 				 * Kludge snd_nxt & the congestion
1559 				 * window so we send only this one
1560 				 * packet.
1561 				 *
1562 				 * We know we're losing at the current
1563 				 * window size so do congestion avoidance
1564 				 * (set ssthresh to half the current window
1565 				 * and pull our congestion window back to
1566 				 * the new ssthresh).
1567 				 *
1568 				 * Dup acks mean that packets have left the
1569 				 * network (they're now cached at the receiver)
1570 				 * so bump cwnd by the amount in the receiver
1571 				 * to keep a constant cwnd packets in the
1572 				 * network.
1573 				 */
1574 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
1575 				    th->th_ack != tp->snd_una)
1576 					tp->t_dupacks = 0;
1577 				else if (++tp->t_dupacks == tcprexmtthresh) {
1578 					tcp_seq onxt = tp->snd_nxt;
1579 					u_int win =
1580 					    min(tp->snd_wnd, tp->snd_cwnd) /
1581 					    2 /	tp->t_segsz;
1582 					if (tcp_do_newreno && SEQ_LT(th->th_ack,
1583 					    tp->snd_recover)) {
1584 						/*
1585 						 * False fast retransmit after
1586 						 * timeout.  Do not cut window.
1587 						 */
1588 						tp->snd_cwnd += tp->t_segsz;
1589 						tp->t_dupacks = 0;
1590 						(void) tcp_output(tp);
1591 						goto drop;
1592 					}
1593 
1594 					if (win < 2)
1595 						win = 2;
1596 					tp->snd_ssthresh = win * tp->t_segsz;
1597 					tp->snd_recover = tp->snd_max;
1598 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
1599 					tp->t_rtt = 0;
1600 					tp->snd_nxt = th->th_ack;
1601 					tp->snd_cwnd = tp->t_segsz;
1602 					(void) tcp_output(tp);
1603 					tp->snd_cwnd = tp->snd_ssthresh +
1604 					       tp->t_segsz * tp->t_dupacks;
1605 					if (SEQ_GT(onxt, tp->snd_nxt))
1606 						tp->snd_nxt = onxt;
1607 					goto drop;
1608 				} else if (tp->t_dupacks > tcprexmtthresh) {
1609 					tp->snd_cwnd += tp->t_segsz;
1610 					(void) tcp_output(tp);
1611 					goto drop;
1612 				}
1613 			} else
1614 				tp->t_dupacks = 0;
1615 			break;
1616 		}
1617 		/*
1618 		 * If the congestion window was inflated to account
1619 		 * for the other side's cached packets, retract it.
1620 		 */
1621 		if (tcp_do_newreno == 0) {
1622 			if (tp->t_dupacks >= tcprexmtthresh &&
1623 			    tp->snd_cwnd > tp->snd_ssthresh)
1624 				tp->snd_cwnd = tp->snd_ssthresh;
1625 			tp->t_dupacks = 0;
1626 		} else if (tp->t_dupacks >= tcprexmtthresh &&
1627 			   tcp_newreno(tp, th) == 0) {
1628 			tp->snd_cwnd = tp->snd_ssthresh;
1629 			/*
1630 			 * Window inflation should have left us with approx.
1631 			 * snd_ssthresh outstanding data.  But in case we
1632 			 * would be inclined to send a burst, better to do
1633 			 * it via the slow start mechanism.
1634 			 */
1635 			if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
1636 				tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
1637 				    + tp->t_segsz;
1638 			tp->t_dupacks = 0;
1639 		}
1640 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1641 			tcpstat.tcps_rcvacktoomuch++;
1642 			goto dropafterack;
1643 		}
1644 		acked = th->th_ack - tp->snd_una;
1645 		tcpstat.tcps_rcvackpack++;
1646 		tcpstat.tcps_rcvackbyte += acked;
1647 
1648 		/*
1649 		 * If we have a timestamp reply, update smoothed
1650 		 * round trip time.  If no timestamp is present but
1651 		 * transmit timer is running and timed sequence
1652 		 * number was acked, update smoothed round trip time.
1653 		 * Since we now have an rtt measurement, cancel the
1654 		 * timer backoff (cf., Phil Karn's retransmit alg.).
1655 		 * Recompute the initial retransmit timer.
1656 		 */
1657 		if (opti.ts_present && opti.ts_ecr)
1658 			tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
1659 		else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
1660 			tcp_xmit_timer(tp,tp->t_rtt);
1661 
1662 		/*
1663 		 * If all outstanding data is acked, stop retransmit
1664 		 * timer and remember to restart (more output or persist).
1665 		 * If there is more data to be acked, restart retransmit
1666 		 * timer, using current (possibly backed-off) value.
1667 		 */
1668 		if (th->th_ack == tp->snd_max) {
1669 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
1670 			needoutput = 1;
1671 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
1672 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1673 		/*
1674 		 * When new data is acked, open the congestion window.
1675 		 * If the window gives us less than ssthresh packets
1676 		 * in flight, open exponentially (segsz per packet).
1677 		 * Otherwise open linearly: segsz per window
1678 		 * (segsz^2 / cwnd per packet), plus a constant
1679 		 * fraction of a packet (segsz/8) to help larger windows
1680 		 * open quickly enough.
1681 		 */
1682 		{
1683 		register u_int cw = tp->snd_cwnd;
1684 		register u_int incr = tp->t_segsz;
1685 
1686 		if (cw > tp->snd_ssthresh)
1687 			incr = incr * incr / cw;
1688 		if (tcp_do_newreno == 0 || SEQ_GEQ(th->th_ack, tp->snd_recover))
1689 			tp->snd_cwnd = min(cw + incr,
1690 			    TCP_MAXWIN << tp->snd_scale);
1691 		}
1692 		if (acked > so->so_snd.sb_cc) {
1693 			tp->snd_wnd -= so->so_snd.sb_cc;
1694 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1695 			ourfinisacked = 1;
1696 		} else {
1697 			sbdrop(&so->so_snd, acked);
1698 			tp->snd_wnd -= acked;
1699 			ourfinisacked = 0;
1700 		}
1701 		sowwakeup(so);
1702 		/*
1703 		 * We want snd_recover to track snd_una to
1704 		 * avoid sequence wraparound problems for
1705 		 * very large transfers.
1706 		 */
1707 		tp->snd_una = tp->snd_recover = th->th_ack;
1708 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1709 			tp->snd_nxt = tp->snd_una;
1710 
1711 		switch (tp->t_state) {
1712 
1713 		/*
1714 		 * In FIN_WAIT_1 STATE in addition to the processing
1715 		 * for the ESTABLISHED state if our FIN is now acknowledged
1716 		 * then enter FIN_WAIT_2.
1717 		 */
1718 		case TCPS_FIN_WAIT_1:
1719 			if (ourfinisacked) {
1720 				/*
1721 				 * If we can't receive any more
1722 				 * data, then closing user can proceed.
1723 				 * Starting the timer is contrary to the
1724 				 * specification, but if we don't get a FIN
1725 				 * we'll hang forever.
1726 				 */
1727 				if (so->so_state & SS_CANTRCVMORE) {
1728 					soisdisconnected(so);
1729 					if (tcp_maxidle > 0)
1730 						TCP_TIMER_ARM(tp, TCPT_2MSL,
1731 						    tcp_maxidle);
1732 				}
1733 				tp->t_state = TCPS_FIN_WAIT_2;
1734 			}
1735 			break;
1736 
1737 	 	/*
1738 		 * In CLOSING STATE in addition to the processing for
1739 		 * the ESTABLISHED state if the ACK acknowledges our FIN
1740 		 * then enter the TIME-WAIT state, otherwise ignore
1741 		 * the segment.
1742 		 */
1743 		case TCPS_CLOSING:
1744 			if (ourfinisacked) {
1745 				tp->t_state = TCPS_TIME_WAIT;
1746 				tcp_canceltimers(tp);
1747 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1748 				soisdisconnected(so);
1749 			}
1750 			break;
1751 
1752 		/*
1753 		 * In LAST_ACK, we may still be waiting for data to drain
1754 		 * and/or to be acked, as well as for the ack of our FIN.
1755 		 * If our FIN is now acknowledged, delete the TCB,
1756 		 * enter the closed state and return.
1757 		 */
1758 		case TCPS_LAST_ACK:
1759 			if (ourfinisacked) {
1760 				tp = tcp_close(tp);
1761 				goto drop;
1762 			}
1763 			break;
1764 
1765 		/*
1766 		 * In TIME_WAIT state the only thing that should arrive
1767 		 * is a retransmission of the remote FIN.  Acknowledge
1768 		 * it and restart the finack timer.
1769 		 */
1770 		case TCPS_TIME_WAIT:
1771 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1772 			goto dropafterack;
1773 		}
1774 	}
1775 
1776 step6:
1777 	/*
1778 	 * Update window information.
1779 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1780 	 */
1781 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1782 	    (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
1783 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
1784 		/* keep track of pure window updates */
1785 		if (tlen == 0 &&
1786 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1787 			tcpstat.tcps_rcvwinupd++;
1788 		tp->snd_wnd = tiwin;
1789 		tp->snd_wl1 = th->th_seq;
1790 		tp->snd_wl2 = th->th_ack;
1791 		if (tp->snd_wnd > tp->max_sndwnd)
1792 			tp->max_sndwnd = tp->snd_wnd;
1793 		needoutput = 1;
1794 	}
1795 
1796 	/*
1797 	 * Process segments with URG.
1798 	 */
1799 	if ((tiflags & TH_URG) && th->th_urp &&
1800 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1801 		/*
1802 		 * This is a kludge, but if we receive and accept
1803 		 * random urgent pointers, we'll crash in
1804 		 * soreceive.  It's hard to imagine someone
1805 		 * actually wanting to send this much urgent data.
1806 		 */
1807 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1808 			th->th_urp = 0;			/* XXX */
1809 			tiflags &= ~TH_URG;		/* XXX */
1810 			goto dodata;			/* XXX */
1811 		}
1812 		/*
1813 		 * If this segment advances the known urgent pointer,
1814 		 * then mark the data stream.  This should not happen
1815 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1816 		 * a FIN has been received from the remote side.
1817 		 * In these states we ignore the URG.
1818 		 *
1819 		 * According to RFC961 (Assigned Protocols),
1820 		 * the urgent pointer points to the last octet
1821 		 * of urgent data.  We continue, however,
1822 		 * to consider it to indicate the first octet
1823 		 * of data past the urgent section as the original
1824 		 * spec states (in one of two places).
1825 		 */
1826 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1827 			tp->rcv_up = th->th_seq + th->th_urp;
1828 			so->so_oobmark = so->so_rcv.sb_cc +
1829 			    (tp->rcv_up - tp->rcv_nxt) - 1;
1830 			if (so->so_oobmark == 0)
1831 				so->so_state |= SS_RCVATMARK;
1832 			sohasoutofband(so);
1833 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1834 		}
1835 		/*
1836 		 * Remove out of band data so doesn't get presented to user.
1837 		 * This can happen independent of advancing the URG pointer,
1838 		 * but if two URG's are pending at once, some out-of-band
1839 		 * data may creep in... ick.
1840 		 */
1841 		if (th->th_urp <= (u_int16_t) tlen
1842 #ifdef SO_OOBINLINE
1843 		     && (so->so_options & SO_OOBINLINE) == 0
1844 #endif
1845 		     )
1846 			tcp_pulloutofband(so, th, m);
1847 	} else
1848 		/*
1849 		 * If no out of band data is expected,
1850 		 * pull receive urgent pointer along
1851 		 * with the receive window.
1852 		 */
1853 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1854 			tp->rcv_up = tp->rcv_nxt;
1855 dodata:							/* XXX */
1856 
1857 	/*
1858 	 * Process the segment text, merging it into the TCP sequencing queue,
1859 	 * and arranging for acknowledgement of receipt if necessary.
1860 	 * This process logically involves adjusting tp->rcv_wnd as data
1861 	 * is presented to the user (this happens in tcp_usrreq.c,
1862 	 * case PRU_RCVD).  If a FIN has already been received on this
1863 	 * connection then we just ignore the text.
1864 	 */
1865 	if ((tlen || (tiflags & TH_FIN)) &&
1866 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1867 		/*
1868 		 * Insert segment ti into reassembly queue of tcp with
1869 		 * control block tp.  Return TH_FIN if reassembly now includes
1870 		 * a segment with FIN.  The macro form does the common case
1871 		 * inline (segment is the next to be received on an
1872 		 * established connection, and the queue is empty),
1873 		 * avoiding linkage into and removal from the queue and
1874 		 * repetition of various conversions.
1875 		 * Set DELACK for segments received in order, but ack
1876 		 * immediately when segments are out of order
1877 		 * (so fast retransmit can work).
1878 		 */
1879 		/* NOTE: this was TCP_REASS() macro, but used only once */
1880 		TCP_REASS_LOCK(tp);
1881 		if (th->th_seq == tp->rcv_nxt &&
1882 		    tp->segq.lh_first == NULL &&
1883 		    tp->t_state == TCPS_ESTABLISHED) {
1884 			TCP_SETUP_ACK(tp, th);
1885 			tp->rcv_nxt += tlen;
1886 			tiflags = th->th_flags & TH_FIN;
1887 			tcpstat.tcps_rcvpack++;\
1888 			tcpstat.tcps_rcvbyte += tlen;\
1889 			sbappend(&(so)->so_rcv, m);
1890 			sorwakeup(so);
1891 		} else {
1892 			tiflags = tcp_reass(tp, th, m, &tlen);
1893 			tp->t_flags |= TF_ACKNOW;
1894 		}
1895 		TCP_REASS_UNLOCK(tp);
1896 
1897 		/*
1898 		 * Note the amount of data that peer has sent into
1899 		 * our window, in order to estimate the sender's
1900 		 * buffer size.
1901 		 */
1902 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1903 	} else {
1904 		m_freem(m);
1905 		m = NULL;
1906 		tiflags &= ~TH_FIN;
1907 	}
1908 
1909 	/*
1910 	 * If FIN is received ACK the FIN and let the user know
1911 	 * that the connection is closing.  Ignore a FIN received before
1912 	 * the connection is fully established.
1913 	 */
1914 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
1915 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1916 			socantrcvmore(so);
1917 			tp->t_flags |= TF_ACKNOW;
1918 			tp->rcv_nxt++;
1919 		}
1920 		switch (tp->t_state) {
1921 
1922 	 	/*
1923 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
1924 		 */
1925 		case TCPS_ESTABLISHED:
1926 			tp->t_state = TCPS_CLOSE_WAIT;
1927 			break;
1928 
1929 	 	/*
1930 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1931 		 * enter the CLOSING state.
1932 		 */
1933 		case TCPS_FIN_WAIT_1:
1934 			tp->t_state = TCPS_CLOSING;
1935 			break;
1936 
1937 	 	/*
1938 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1939 		 * starting the time-wait timer, turning off the other
1940 		 * standard timers.
1941 		 */
1942 		case TCPS_FIN_WAIT_2:
1943 			tp->t_state = TCPS_TIME_WAIT;
1944 			tcp_canceltimers(tp);
1945 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1946 			soisdisconnected(so);
1947 			break;
1948 
1949 		/*
1950 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1951 		 */
1952 		case TCPS_TIME_WAIT:
1953 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1954 			break;
1955 		}
1956 	}
1957 	if (so->so_options & SO_DEBUG) {
1958 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
1959 	}
1960 
1961 	/*
1962 	 * Return any desired output.
1963 	 */
1964 	if (needoutput || (tp->t_flags & TF_ACKNOW))
1965 		(void) tcp_output(tp);
1966 	if (tcp_saveti)
1967 		m_freem(tcp_saveti);
1968 	return;
1969 
1970 badsyn:
1971 	/*
1972 	 * Received a bad SYN.  Increment counters and dropwithreset.
1973 	 */
1974 	tcpstat.tcps_badsyn++;
1975 	tp = NULL;
1976 	goto dropwithreset;
1977 
1978 dropafterack:
1979 	/*
1980 	 * Generate an ACK dropping incoming segment if it occupies
1981 	 * sequence space, where the ACK reflects our state.
1982 	 */
1983 	if (tiflags & TH_RST)
1984 		goto drop;
1985 	m_freem(m);
1986 	tp->t_flags |= TF_ACKNOW;
1987 	(void) tcp_output(tp);
1988 	if (tcp_saveti)
1989 		m_freem(tcp_saveti);
1990 	return;
1991 
1992 dropwithreset:
1993 	/*
1994 	 * Generate a RST, dropping incoming segment.
1995 	 * Make ACK acceptable to originator of segment.
1996 	 * Don't bother to respond if destination was broadcast/multicast.
1997 	 */
1998 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
1999 		goto drop;
2000 	if (ip && IN_MULTICAST(ip->ip_dst.s_addr))
2001 		goto drop;
2002 #ifdef INET6
2003 	if (m->m_flags & M_ANYCAST6)
2004 		goto drop;
2005 	else if (ip6 && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2006 		goto drop;
2007 #endif
2008 	/* recover the header if dropped. */
2009 	m->m_data -= hdroptlen;
2010 	m->m_len += hdroptlen;
2011     {
2012 	/*
2013 	 * need to recover version # field, which was overwritten on
2014 	 * ip_cksum computation.
2015 	 */
2016 	struct ip *sip;
2017 	sip = mtod(m, struct ip *);
2018 	switch (af) {
2019 	case AF_INET:
2020 		sip->ip_v = 4;
2021 		break;
2022 #ifdef INET6
2023 	case AF_INET6:
2024 		sip->ip_v = 6;
2025 		break;
2026 #endif
2027 	}
2028     }
2029 	if (tiflags & TH_ACK)
2030 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2031 	else {
2032 		if (tiflags & TH_SYN)
2033 			tlen++;
2034 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2035 		    TH_RST|TH_ACK);
2036 	}
2037 	if (tcp_saveti)
2038 		m_freem(tcp_saveti);
2039 	return;
2040 
2041 drop:
2042 	/*
2043 	 * Drop space held by incoming segment and return.
2044 	 */
2045 	if (tp) {
2046 		if (tp->t_inpcb)
2047 			so = tp->t_inpcb->inp_socket;
2048 #ifdef INET6
2049 		else if (tp->t_in6pcb)
2050 			so = tp->t_in6pcb->in6p_socket;
2051 #endif
2052 		else
2053 			so = NULL;
2054 		if (so && (so->so_options & SO_DEBUG) != 0)
2055 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2056 	}
2057 	if (tcp_saveti)
2058 		m_freem(tcp_saveti);
2059 	m_freem(m);
2060 	return;
2061 }
2062 
2063 void
2064 tcp_dooptions(tp, cp, cnt, th, oi)
2065 	struct tcpcb *tp;
2066 	u_char *cp;
2067 	int cnt;
2068 	struct tcphdr *th;
2069 	struct tcp_opt_info *oi;
2070 {
2071 	u_int16_t mss;
2072 	int opt, optlen;
2073 
2074 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2075 		opt = cp[0];
2076 		if (opt == TCPOPT_EOL)
2077 			break;
2078 		if (opt == TCPOPT_NOP)
2079 			optlen = 1;
2080 		else {
2081 			optlen = cp[1];
2082 			if (optlen <= 0)
2083 				break;
2084 		}
2085 		switch (opt) {
2086 
2087 		default:
2088 			continue;
2089 
2090 		case TCPOPT_MAXSEG:
2091 			if (optlen != TCPOLEN_MAXSEG)
2092 				continue;
2093 			if (!(th->th_flags & TH_SYN))
2094 				continue;
2095 			bcopy(cp + 2, &mss, sizeof(mss));
2096 			oi->maxseg = ntohs(mss);
2097 			break;
2098 
2099 		case TCPOPT_WINDOW:
2100 			if (optlen != TCPOLEN_WINDOW)
2101 				continue;
2102 			if (!(th->th_flags & TH_SYN))
2103 				continue;
2104 			tp->t_flags |= TF_RCVD_SCALE;
2105 			tp->requested_s_scale = cp[2];
2106 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2107 #if 0	/*XXX*/
2108 				char *p;
2109 
2110 				if (ip)
2111 					p = ntohl(ip->ip_src);
2112 #ifdef INET6
2113 				else if (ip6)
2114 					p = ip6_sprintf(&ip6->ip6_src);
2115 #endif
2116 				else
2117 					p = "(unknown)";
2118 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2119 				    "assuming %d\n",
2120 				    tp->requested_s_scale, p,
2121 				    TCP_MAX_WINSHIFT);
2122 #else
2123 				log(LOG_ERR, "TCP: invalid wscale %d, "
2124 				    "assuming %d\n",
2125 				    tp->requested_s_scale,
2126 				    TCP_MAX_WINSHIFT);
2127 #endif
2128 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
2129 			}
2130 			break;
2131 
2132 		case TCPOPT_TIMESTAMP:
2133 			if (optlen != TCPOLEN_TIMESTAMP)
2134 				continue;
2135 			oi->ts_present = 1;
2136 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2137 			NTOHL(oi->ts_val);
2138 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2139 			NTOHL(oi->ts_ecr);
2140 
2141 			/*
2142 			 * A timestamp received in a SYN makes
2143 			 * it ok to send timestamp requests and replies.
2144 			 */
2145 			if (th->th_flags & TH_SYN) {
2146 				tp->t_flags |= TF_RCVD_TSTMP;
2147 				tp->ts_recent = oi->ts_val;
2148 				tp->ts_recent_age = tcp_now;
2149 			}
2150 			break;
2151 		case TCPOPT_SACK_PERMITTED:
2152 			if (optlen != TCPOLEN_SACK_PERMITTED)
2153 				continue;
2154 			if (!(th->th_flags & TH_SYN))
2155 				continue;
2156 			tp->t_flags &= ~TF_CANT_TXSACK;
2157 			break;
2158 
2159 		case TCPOPT_SACK:
2160 			if (tp->t_flags & TF_IGNR_RXSACK)
2161 				continue;
2162 			if (optlen % 8 != 2 || optlen < 10)
2163 				continue;
2164 			cp += 2;
2165 			optlen -= 2;
2166 			for (; optlen > 0; cp -= 8, optlen -= 8) {
2167 				tcp_seq lwe, rwe;
2168 				bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
2169 				NTOHL(lwe);
2170 				bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
2171 				NTOHL(rwe);
2172 				/* tcp_mark_sacked(tp, lwe, rwe); */
2173 			}
2174 			break;
2175 		}
2176 	}
2177 }
2178 
2179 /*
2180  * Pull out of band byte out of a segment so
2181  * it doesn't appear in the user's data queue.
2182  * It is still reflected in the segment length for
2183  * sequencing purposes.
2184  */
2185 void
2186 tcp_pulloutofband(so, th, m)
2187 	struct socket *so;
2188 	struct tcphdr *th;
2189 	register struct mbuf *m;
2190 {
2191 	int cnt = th->th_urp - 1;
2192 
2193 	while (cnt >= 0) {
2194 		if (m->m_len > cnt) {
2195 			char *cp = mtod(m, caddr_t) + cnt;
2196 			struct tcpcb *tp = sototcpcb(so);
2197 
2198 			tp->t_iobc = *cp;
2199 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2200 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2201 			m->m_len--;
2202 			return;
2203 		}
2204 		cnt -= m->m_len;
2205 		m = m->m_next;
2206 		if (m == 0)
2207 			break;
2208 	}
2209 	panic("tcp_pulloutofband");
2210 }
2211 
2212 /*
2213  * Collect new round-trip time estimate
2214  * and update averages and current timeout.
2215  */
2216 void
2217 tcp_xmit_timer(tp, rtt)
2218 	register struct tcpcb *tp;
2219 	short rtt;
2220 {
2221 	register short delta;
2222 	short rttmin;
2223 
2224 	tcpstat.tcps_rttupdated++;
2225 	--rtt;
2226 	if (tp->t_srtt != 0) {
2227 		/*
2228 		 * srtt is stored as fixed point with 3 bits after the
2229 		 * binary point (i.e., scaled by 8).  The following magic
2230 		 * is equivalent to the smoothing algorithm in rfc793 with
2231 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2232 		 * point).  Adjust rtt to origin 0.
2233 		 */
2234 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2235 		if ((tp->t_srtt += delta) <= 0)
2236 			tp->t_srtt = 1 << 2;
2237 		/*
2238 		 * We accumulate a smoothed rtt variance (actually, a
2239 		 * smoothed mean difference), then set the retransmit
2240 		 * timer to smoothed rtt + 4 times the smoothed variance.
2241 		 * rttvar is stored as fixed point with 2 bits after the
2242 		 * binary point (scaled by 4).  The following is
2243 		 * equivalent to rfc793 smoothing with an alpha of .75
2244 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2245 		 * rfc793's wired-in beta.
2246 		 */
2247 		if (delta < 0)
2248 			delta = -delta;
2249 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2250 		if ((tp->t_rttvar += delta) <= 0)
2251 			tp->t_rttvar = 1 << 2;
2252 	} else {
2253 		/*
2254 		 * No rtt measurement yet - use the unsmoothed rtt.
2255 		 * Set the variance to half the rtt (so our first
2256 		 * retransmit happens at 3*rtt).
2257 		 */
2258 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
2259 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
2260 	}
2261 	tp->t_rtt = 0;
2262 	tp->t_rxtshift = 0;
2263 
2264 	/*
2265 	 * the retransmit should happen at rtt + 4 * rttvar.
2266 	 * Because of the way we do the smoothing, srtt and rttvar
2267 	 * will each average +1/2 tick of bias.  When we compute
2268 	 * the retransmit timer, we want 1/2 tick of rounding and
2269 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2270 	 * firing of the timer.  The bias will give us exactly the
2271 	 * 1.5 tick we need.  But, because the bias is
2272 	 * statistical, we have to test that we don't drop below
2273 	 * the minimum feasible timer (which is 2 ticks).
2274 	 */
2275 	if (tp->t_rttmin > rtt + 2)
2276 		rttmin = tp->t_rttmin;
2277 	else
2278 		rttmin = rtt + 2;
2279 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
2280 
2281 	/*
2282 	 * We received an ack for a packet that wasn't retransmitted;
2283 	 * it is probably safe to discard any error indications we've
2284 	 * received recently.  This isn't quite right, but close enough
2285 	 * for now (a route might have failed after we sent a segment,
2286 	 * and the return path might not be symmetrical).
2287 	 */
2288 	tp->t_softerror = 0;
2289 }
2290 
2291 /*
2292  * Checks for partial ack.  If partial ack arrives, force the retransmission
2293  * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
2294  * 1.  By setting snd_nxt to th_ack, this forces retransmission timer to
2295  * be started again.  If the ack advances at least to tp->snd_recover, return 0.
2296  */
2297 int
2298 tcp_newreno(tp, th)
2299 	struct tcpcb *tp;
2300 	struct tcphdr *th;
2301 {
2302 	tcp_seq onxt = tp->snd_nxt;
2303 	u_long ocwnd = tp->snd_cwnd;
2304 
2305 	if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2306 		/*
2307 		 * snd_una has not yet been updated and the socket's send
2308 		 * buffer has not yet drained off the ACK'd data, so we
2309 		 * have to leave snd_una as it was to get the correct data
2310 		 * offset in tcp_output().
2311 		 */
2312 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
2313 	        tp->t_rtt = 0;
2314 	        tp->snd_nxt = th->th_ack;
2315 		/*
2316 		 * Set snd_cwnd to one segment beyond ACK'd offset.  snd_una
2317 		 * is not yet updated when we're called.
2318 		 */
2319 		tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
2320 	        (void) tcp_output(tp);
2321 	        tp->snd_cwnd = ocwnd;
2322 	        if (SEQ_GT(onxt, tp->snd_nxt))
2323 	                tp->snd_nxt = onxt;
2324 	        /*
2325 	         * Partial window deflation.  Relies on fact that tp->snd_una
2326 	         * not updated yet.
2327 	         */
2328 	        tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
2329 	        return 1;
2330 	}
2331 	return 0;
2332 }
2333 
2334 
2335 /*
2336  * TCP compressed state engine.  Currently used to hold compressed
2337  * state for SYN_RECEIVED.
2338  */
2339 
2340 u_long	syn_cache_count;
2341 u_int32_t syn_hash1, syn_hash2;
2342 
2343 #define SYN_HASH(sa, sp, dp) \
2344 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
2345 				     ((u_int32_t)(sp)))^syn_hash2)))
2346 #ifndef INET6
2347 #define	SYN_HASHALL(hash, src, dst) \
2348 do {									\
2349 	hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr,	\
2350 		((struct sockaddr_in *)(src))->sin_port,		\
2351 		((struct sockaddr_in *)(dst))->sin_port);		\
2352 } while (0)
2353 #else
2354 #define SYN_HASH6(sa, sp, dp) \
2355 	((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
2356 	  (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
2357 	 & 0x7fffffff)
2358 
2359 #define SYN_HASHALL(hash, src, dst) \
2360 do {									\
2361 	switch ((src)->sa_family) {					\
2362 	case AF_INET:							\
2363 		hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2364 			((struct sockaddr_in *)(src))->sin_port,	\
2365 			((struct sockaddr_in *)(dst))->sin_port);	\
2366 		break;							\
2367 	case AF_INET6:							\
2368 		hash = SYN_HASH6(&((struct sockaddr_in6 *)(src))->sin6_addr, \
2369 			((struct sockaddr_in6 *)(src))->sin6_port,	\
2370 			((struct sockaddr_in6 *)(dst))->sin6_port);	\
2371 		break;							\
2372 	default:							\
2373 		hash = 0;						\
2374 	}								\
2375 } while (0)
2376 #endif /* INET6 */
2377 
2378 #define	SYN_CACHE_RM(sc)						\
2379 do {									\
2380 	LIST_REMOVE((sc), sc_bucketq);					\
2381 	(sc)->sc_tp = NULL;						\
2382 	LIST_REMOVE((sc), sc_tpq);					\
2383 	tcp_syn_cache[(sc)->sc_bucketidx].sch_length--;			\
2384 	TAILQ_REMOVE(&tcp_syn_cache_timeq[(sc)->sc_rxtshift], (sc), sc_timeq); \
2385 	syn_cache_count--;						\
2386 } while (0)
2387 
2388 #define	SYN_CACHE_PUT(sc)						\
2389 do {									\
2390 	if ((sc)->sc_ipopts)						\
2391 		(void) m_free((sc)->sc_ipopts);				\
2392 	if ((sc)->sc_route4.ro_rt != NULL)				\
2393 		RTFREE((sc)->sc_route4.ro_rt);				\
2394 	pool_put(&syn_cache_pool, (sc));				\
2395 } while (0)
2396 
2397 struct pool syn_cache_pool;
2398 
2399 /*
2400  * We don't estimate RTT with SYNs, so each packet starts with the default
2401  * RTT and each timer queue has a fixed timeout value.  This allows us to
2402  * optimize the timer queues somewhat.
2403  */
2404 #define	SYN_CACHE_TIMER_ARM(sc)						\
2405 do {									\
2406 	TCPT_RANGESET((sc)->sc_rxtcur,					\
2407 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
2408 	    TCPTV_REXMTMAX);						\
2409 	PRT_SLOW_ARM((sc)->sc_rexmt, (sc)->sc_rxtcur);			\
2410 } while (0)
2411 
2412 TAILQ_HEAD(, syn_cache) tcp_syn_cache_timeq[TCP_MAXRXTSHIFT + 1];
2413 
2414 void
2415 syn_cache_init()
2416 {
2417 	int i;
2418 
2419 	/* Initialize the hash buckets. */
2420 	for (i = 0; i < tcp_syn_cache_size; i++)
2421 		LIST_INIT(&tcp_syn_cache[i].sch_bucket);
2422 
2423 	/* Initialize the timer queues. */
2424 	for (i = 0; i <= TCP_MAXRXTSHIFT; i++)
2425 		TAILQ_INIT(&tcp_syn_cache_timeq[i]);
2426 
2427 	/* Initialize the syn cache pool. */
2428 	pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
2429 	    "synpl", 0, NULL, NULL, M_PCB);
2430 }
2431 
2432 void
2433 syn_cache_insert(sc, tp)
2434 	struct syn_cache *sc;
2435 	struct tcpcb *tp;
2436 {
2437 	struct syn_cache_head *scp;
2438 	struct syn_cache *sc2;
2439 	int s, i;
2440 
2441 	/*
2442 	 * If there are no entries in the hash table, reinitialize
2443 	 * the hash secrets.
2444 	 */
2445 	if (syn_cache_count == 0) {
2446 		struct timeval tv;
2447 		microtime(&tv);
2448 		syn_hash1 = random() ^ (u_long)&sc;
2449 		syn_hash2 = random() ^ tv.tv_usec;
2450 	}
2451 
2452 	SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
2453 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
2454 	scp = &tcp_syn_cache[sc->sc_bucketidx];
2455 
2456 	/*
2457 	 * Make sure that we don't overflow the per-bucket
2458 	 * limit or the total cache size limit.
2459 	 */
2460 	s = splsoftnet();
2461 	if (scp->sch_length >= tcp_syn_bucket_limit) {
2462 		tcpstat.tcps_sc_bucketoverflow++;
2463 		/*
2464 		 * The bucket is full.  Toss the oldest element in the
2465 		 * bucket.  This will be the entry with our bucket
2466 		 * index closest to the front of the timer queue with
2467 		 * the largest timeout value.
2468 		 *
2469 		 * Note: This timer queue traversal may be expensive, so
2470 		 * we hope that this doesn't happen very often.  It is
2471 		 * much more likely that we'll overflow the entire
2472 		 * cache, which is much easier to handle; see below.
2473 		 */
2474 		for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2475 			for (sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2476 			     sc2 != NULL;
2477 			     sc2 = TAILQ_NEXT(sc2, sc_timeq)) {
2478 				if (sc2->sc_bucketidx == sc->sc_bucketidx) {
2479 					SYN_CACHE_RM(sc2);
2480 					SYN_CACHE_PUT(sc2);
2481 					goto insert;	/* 2 level break */
2482 				}
2483 			}
2484 		}
2485 #ifdef DIAGNOSTIC
2486 		/*
2487 		 * This should never happen; we should always find an
2488 		 * entry in our bucket.
2489 		 */
2490 		panic("syn_cache_insert: bucketoverflow: impossible");
2491 #endif
2492 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
2493 		tcpstat.tcps_sc_overflowed++;
2494 		/*
2495 		 * The cache is full.  Toss the oldest entry in the
2496 		 * entire cache.  This is the front entry in the
2497 		 * first non-empty timer queue with the largest
2498 		 * timeout value.
2499 		 */
2500 		for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2501 			sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2502 			if (sc2 == NULL)
2503 				continue;
2504 			SYN_CACHE_RM(sc2);
2505 			SYN_CACHE_PUT(sc2);
2506 			goto insert;		/* symmetry with above */
2507 		}
2508 #ifdef DIAGNOSTIC
2509 		/*
2510 		 * This should never happen; we should always find an
2511 		 * entry in the cache.
2512 		 */
2513 		panic("syn_cache_insert: cache overflow: impossible");
2514 #endif
2515 	}
2516 
2517  insert:
2518 	/*
2519 	 * Initialize the entry's timer.
2520 	 */
2521 	sc->sc_rxttot = 0;
2522 	sc->sc_rxtshift = 0;
2523 	SYN_CACHE_TIMER_ARM(sc);
2524 	TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift], sc, sc_timeq);
2525 
2526 	/* Link it from tcpcb entry */
2527 	LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
2528 
2529 	/* Put it into the bucket. */
2530 	LIST_INSERT_HEAD(&scp->sch_bucket, sc, sc_bucketq);
2531 	scp->sch_length++;
2532 	syn_cache_count++;
2533 
2534 	tcpstat.tcps_sc_added++;
2535 	splx(s);
2536 }
2537 
2538 /*
2539  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
2540  * If we have retransmitted an entry the maximum number of times, expire
2541  * that entry.
2542  */
2543 void
2544 syn_cache_timer()
2545 {
2546 	struct syn_cache *sc, *nsc;
2547 	int i, s;
2548 
2549 	s = splsoftnet();
2550 
2551 	/*
2552 	 * First, get all the entries that need to be retransmitted, or
2553 	 * must be expired due to exceeding the initial keepalive time.
2554 	 */
2555 	for (i = 0; i < TCP_MAXRXTSHIFT; i++) {
2556 		for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2557 		     sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2558 		     sc = nsc) {
2559 			nsc = TAILQ_NEXT(sc, sc_timeq);
2560 
2561 			/*
2562 			 * Compute the total amount of time this entry has
2563 			 * been on a queue.  If this entry has been on longer
2564 			 * than the keep alive timer would allow, expire it.
2565 			 */
2566 			sc->sc_rxttot += sc->sc_rxtcur;
2567 			if (sc->sc_rxttot >= TCPTV_KEEP_INIT) {
2568 				tcpstat.tcps_sc_timed_out++;
2569 				SYN_CACHE_RM(sc);
2570 				SYN_CACHE_PUT(sc);
2571 				continue;
2572 			}
2573 
2574 			tcpstat.tcps_sc_retransmitted++;
2575 			(void) syn_cache_respond(sc, NULL);
2576 
2577 			/* Advance this entry onto the next timer queue. */
2578 			TAILQ_REMOVE(&tcp_syn_cache_timeq[i], sc, sc_timeq);
2579 			sc->sc_rxtshift = i + 1;
2580 			SYN_CACHE_TIMER_ARM(sc);
2581 			TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift],
2582 			    sc, sc_timeq);
2583 		}
2584 	}
2585 
2586 	/*
2587 	 * Now get all the entries that are expired due to too many
2588 	 * retransmissions.
2589 	 */
2590 	for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[TCP_MAXRXTSHIFT]);
2591 	     sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2592 	     sc = nsc) {
2593 		nsc = TAILQ_NEXT(sc, sc_timeq);
2594 		tcpstat.tcps_sc_timed_out++;
2595 		SYN_CACHE_RM(sc);
2596 		SYN_CACHE_PUT(sc);
2597 	}
2598 	splx(s);
2599 }
2600 
2601 /*
2602  * Remove syn cache created by the specified tcb entry,
2603  * because this does not make sense to keep them
2604  * (if there's no tcb entry, syn cache entry will never be used)
2605  */
2606 void
2607 syn_cache_cleanup(tp)
2608 	struct tcpcb *tp;
2609 {
2610 	struct syn_cache *sc, *nsc;
2611 	int s;
2612 
2613 	s = splsoftnet();
2614 
2615 	for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
2616 		nsc = LIST_NEXT(sc, sc_tpq);
2617 
2618 #ifdef DIAGNOSTIC
2619 		if (sc->sc_tp != tp)
2620 			panic("invalid sc_tp in syn_cache_cleanup");
2621 #endif
2622 		SYN_CACHE_RM(sc);
2623 		SYN_CACHE_PUT(sc);
2624 	}
2625 	/* just for safety */
2626 	LIST_INIT(&tp->t_sc);
2627 
2628 	splx(s);
2629 }
2630 
2631 /*
2632  * Find an entry in the syn cache.
2633  */
2634 struct syn_cache *
2635 syn_cache_lookup(src, dst, headp)
2636 	struct sockaddr *src;
2637 	struct sockaddr *dst;
2638 	struct syn_cache_head **headp;
2639 {
2640 	struct syn_cache *sc;
2641 	struct syn_cache_head *scp;
2642 	u_int32_t hash;
2643 	int s;
2644 
2645 	SYN_HASHALL(hash, src, dst);
2646 
2647 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
2648 	*headp = scp;
2649 	s = splsoftnet();
2650 	for (sc = LIST_FIRST(&scp->sch_bucket); sc != NULL;
2651 	     sc = LIST_NEXT(sc, sc_bucketq)) {
2652 		if (sc->sc_hash != hash)
2653 			continue;
2654 		if (!bcmp(&sc->sc_src, src, src->sa_len) &&
2655 		    !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
2656 			splx(s);
2657 			return (sc);
2658 		}
2659 	}
2660 	splx(s);
2661 	return (NULL);
2662 }
2663 
2664 /*
2665  * This function gets called when we receive an ACK for a
2666  * socket in the LISTEN state.  We look up the connection
2667  * in the syn cache, and if its there, we pull it out of
2668  * the cache and turn it into a full-blown connection in
2669  * the SYN-RECEIVED state.
2670  *
2671  * The return values may not be immediately obvious, and their effects
2672  * can be subtle, so here they are:
2673  *
2674  *	NULL	SYN was not found in cache; caller should drop the
2675  *		packet and send an RST.
2676  *
2677  *	-1	We were unable to create the new connection, and are
2678  *		aborting it.  An ACK,RST is being sent to the peer
2679  *		(unless we got screwey sequence numbners; see below),
2680  *		because the 3-way handshake has been completed.  Caller
2681  *		should not free the mbuf, since we may be using it.  If
2682  *		we are not, we will free it.
2683  *
2684  *	Otherwise, the return value is a pointer to the new socket
2685  *	associated with the connection.
2686  */
2687 struct socket *
2688 syn_cache_get(src, dst, th, hlen, tlen, so, m)
2689 	struct sockaddr *src;
2690 	struct sockaddr *dst;
2691 	struct tcphdr *th;
2692 	unsigned int hlen, tlen;
2693 	struct socket *so;
2694 	struct mbuf *m;
2695 {
2696 	struct syn_cache *sc;
2697 	struct syn_cache_head *scp;
2698 	register struct inpcb *inp = NULL;
2699 #ifdef INET6
2700 	register struct in6pcb *in6p = NULL;
2701 #endif
2702 	register struct tcpcb *tp = 0;
2703 	struct mbuf *am;
2704 	int s;
2705 	struct socket *oso;
2706 
2707 	s = splsoftnet();
2708 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2709 		splx(s);
2710 		return (NULL);
2711 	}
2712 
2713 	/*
2714 	 * Verify the sequence and ack numbers.  Try getting the correct
2715 	 * response again.
2716 	 */
2717 	if ((th->th_ack != sc->sc_iss + 1) ||
2718 	    SEQ_LEQ(th->th_seq, sc->sc_irs) ||
2719 	    SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
2720 		(void) syn_cache_respond(sc, m);
2721 		splx(s);
2722 		return ((struct socket *)(-1));
2723 	}
2724 
2725 	/* Remove this cache entry */
2726 	SYN_CACHE_RM(sc);
2727 	splx(s);
2728 
2729 	/*
2730 	 * Ok, create the full blown connection, and set things up
2731 	 * as they would have been set up if we had created the
2732 	 * connection when the SYN arrived.  If we can't create
2733 	 * the connection, abort it.
2734 	 */
2735 	/*
2736 	 * inp still has the OLD in_pcb stuff, set the
2737 	 * v6-related flags on the new guy, too.   This is
2738 	 * done particularly for the case where an AF_INET6
2739 	 * socket is bound only to a port, and a v4 connection
2740 	 * comes in on that port.
2741 	 * we also copy the flowinfo from the original pcb
2742 	 * to the new one.
2743 	 */
2744     {
2745 	struct inpcb *parentinpcb;
2746 
2747 	parentinpcb = (struct inpcb *)so->so_pcb;
2748 
2749 	oso = so;
2750 	so = sonewconn(so, SS_ISCONNECTED);
2751 	if (so == NULL)
2752 		goto resetandabort;
2753 
2754 	switch (so->so_proto->pr_domain->dom_family) {
2755 	case AF_INET:
2756 		inp = sotoinpcb(so);
2757 		break;
2758 #ifdef INET6
2759 	case AF_INET6:
2760 		in6p = sotoin6pcb(so);
2761 #if 0 /*def INET6*/
2762 		inp->inp_flags |= (parentinpcb->inp_flags &
2763 			(INP_IPV6 | INP_IPV6_UNDEC | INP_IPV6_MAPPED));
2764 		if ((inp->inp_flags & INP_IPV6) &&
2765 		   !(inp->inp_flags & INP_IPV6_MAPPED)) {
2766 			inp->inp_ipv6.ip6_hlim = parentinpcb->inp_ipv6.ip6_hlim;
2767 			inp->inp_ipv6.ip6_vfc = parentinpcb->inp_ipv6.ip6_vfc;
2768 		}
2769 #endif
2770 		break;
2771 #endif
2772 	}
2773     }
2774 	switch (src->sa_family) {
2775 	case AF_INET:
2776 		if (inp) {
2777 			inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
2778 			inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
2779 			inp->inp_options = ip_srcroute();
2780 			in_pcbstate(inp, INP_BOUND);
2781 			if (inp->inp_options == NULL) {
2782 				inp->inp_options = sc->sc_ipopts;
2783 				sc->sc_ipopts = NULL;
2784 			}
2785 		}
2786 #ifdef INET6
2787 		else if (in6p) {
2788 			/* IPv4 packet to AF_INET6 socket */
2789 			bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
2790 			in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
2791 			bcopy(&((struct sockaddr_in *)dst)->sin_addr,
2792 				&in6p->in6p_laddr.s6_addr32[3],
2793 				sizeof(((struct sockaddr_in *)dst)->sin_addr));
2794 			in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
2795 			in6totcpcb(in6p)->t_family = AF_INET;
2796 		}
2797 #endif
2798 		break;
2799 #ifdef INET6
2800 	case AF_INET6:
2801 		if (in6p) {
2802 			in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
2803 			in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
2804 #if 0
2805 			in6p->in6p_flowinfo = ip6->ip6_flow & IPV6_FLOWINFO_MASK;
2806 			/*inp->inp_options = ip6_srcroute();*/ /* soon. */
2807 #endif
2808 		}
2809 		break;
2810 #endif
2811 	}
2812 #ifdef INET6
2813 	if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
2814 		struct in6pcb *oin6p = sotoin6pcb(oso);
2815 		/* inherit socket options from the listening socket */
2816 		in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
2817 		if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
2818 			m_freem(in6p->in6p_options);
2819 			in6p->in6p_options = 0;
2820 		}
2821 		ip6_savecontrol(in6p, &in6p->in6p_options,
2822 			mtod(m, struct ip6_hdr *), m);
2823 	}
2824 #endif
2825 
2826 #ifdef IPSEC
2827     {
2828 	struct secpolicy *sp;
2829 	if (inp) {
2830 		sp = ipsec_copy_policy(sotoinpcb(oso)->inp_sp);
2831 		if (sp) {
2832 			key_freesp(inp->inp_sp);
2833 			inp->inp_sp = sp;
2834 		} else
2835 			printf("tcp_input: could not copy policy\n");
2836 	}
2837 #ifdef INET6
2838 	else if (in6p) {
2839 		sp = ipsec_copy_policy(sotoin6pcb(oso)->in6p_sp);
2840 		if (sp) {
2841 			key_freesp(in6p->in6p_sp);
2842 			in6p->in6p_sp = sp;
2843 		} else
2844 			printf("tcp_input: could not copy policy\n");
2845 	}
2846 #endif
2847     }
2848 #endif
2849 
2850 	/*
2851 	 * Give the new socket our cached route reference.
2852 	 */
2853 	if (inp)
2854 		inp->inp_route = sc->sc_route4;		/* struct assignment */
2855 #ifdef INET6
2856 	else
2857 		in6p->in6p_route = sc->sc_route6;
2858 #endif
2859 	sc->sc_route4.ro_rt = NULL;
2860 
2861 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
2862 	if (am == NULL)
2863 		goto resetandabort;
2864 	am->m_len = src->sa_len;
2865 	bcopy(src, mtod(am, caddr_t), src->sa_len);
2866 	if (inp) {
2867 		if (in_pcbconnect(inp, am)) {
2868 			(void) m_free(am);
2869 			goto resetandabort;
2870 		}
2871 	}
2872 #ifdef INET6
2873 	else if (in6p) {
2874 		if (src->sa_family == AF_INET) {
2875 			/* IPv4 packet to AF_INET6 socket */
2876 			struct sockaddr_in6 *sin6;
2877 			sin6 = mtod(am, struct sockaddr_in6 *);
2878 			am->m_len = sizeof(*sin6);
2879 			bzero(sin6, sizeof(*sin6));
2880 			sin6->sin6_family = AF_INET6;
2881 			sin6->sin6_len = sizeof(*sin6);
2882 			sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
2883 			sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
2884 			bcopy(&((struct sockaddr_in *)src)->sin_addr,
2885 				&sin6->sin6_addr.s6_addr32[3],
2886 				sizeof(sin6->sin6_addr.s6_addr32[3]));
2887 		}
2888 		if (in6_pcbconnect(in6p, am)) {
2889 			(void) m_free(am);
2890 			goto resetandabort;
2891 		}
2892 	}
2893 #endif
2894 	else {
2895 		(void) m_free(am);
2896 		goto resetandabort;
2897 	}
2898 	(void) m_free(am);
2899 
2900 	if (inp)
2901 		tp = intotcpcb(inp);
2902 #ifdef INET6
2903 	else if (in6p)
2904 		tp = in6totcpcb(in6p);
2905 #endif
2906 	else
2907 		tp = NULL;
2908 	if (sc->sc_request_r_scale != 15) {
2909 		tp->requested_s_scale = sc->sc_requested_s_scale;
2910 		tp->request_r_scale = sc->sc_request_r_scale;
2911 		tp->snd_scale = sc->sc_requested_s_scale;
2912 		tp->rcv_scale = sc->sc_request_r_scale;
2913 		tp->t_flags |= TF_RCVD_SCALE;
2914 	}
2915 	if (sc->sc_flags & SCF_TIMESTAMP)
2916 		tp->t_flags |= TF_RCVD_TSTMP;
2917 
2918 	tp->t_template = tcp_template(tp);
2919 	if (tp->t_template == 0) {
2920 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
2921 		so = NULL;
2922 		m_freem(m);
2923 		goto abort;
2924 	}
2925 
2926 	tp->iss = sc->sc_iss;
2927 	tp->irs = sc->sc_irs;
2928 	tcp_sendseqinit(tp);
2929 	tcp_rcvseqinit(tp);
2930 	tp->t_state = TCPS_SYN_RECEIVED;
2931 	TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
2932 	tcpstat.tcps_accepts++;
2933 
2934 	/* Initialize tp->t_ourmss before we deal with the peer's! */
2935 	tp->t_ourmss = sc->sc_ourmaxseg;
2936 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
2937 
2938 	/*
2939 	 * Initialize the initial congestion window.  If we
2940 	 * had to retransmit the SYN,ACK, we must initialize cwnd
2941 	 * to 1 segment (i.e. the Loss Window).
2942 	 */
2943 	if (sc->sc_rxtshift)
2944 		tp->snd_cwnd = tp->t_peermss;
2945 	else
2946 		tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win, tp->t_peermss);
2947 
2948 	tcp_rmx_rtt(tp);
2949 	tp->snd_wl1 = sc->sc_irs;
2950 	tp->rcv_up = sc->sc_irs + 1;
2951 
2952 	/*
2953 	 * This is what whould have happened in tcp_ouput() when
2954 	 * the SYN,ACK was sent.
2955 	 */
2956 	tp->snd_up = tp->snd_una;
2957 	tp->snd_max = tp->snd_nxt = tp->iss+1;
2958 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2959 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
2960 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
2961 	tp->last_ack_sent = tp->rcv_nxt;
2962 
2963 	tcpstat.tcps_sc_completed++;
2964 	SYN_CACHE_PUT(sc);
2965 	return (so);
2966 
2967 resetandabort:
2968 	(void) tcp_respond(NULL, m, m, th,
2969 			   th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
2970 abort:
2971 	if (so != NULL)
2972 		(void) soabort(so);
2973 	SYN_CACHE_PUT(sc);
2974 	tcpstat.tcps_sc_aborted++;
2975 	return ((struct socket *)(-1));
2976 }
2977 
2978 /*
2979  * This function is called when we get a RST for a
2980  * non-existant connection, so that we can see if the
2981  * connection is in the syn cache.  If it is, zap it.
2982  */
2983 
2984 void
2985 syn_cache_reset(src, dst, th)
2986 	struct sockaddr *src;
2987 	struct sockaddr *dst;
2988 	struct tcphdr *th;
2989 {
2990 	struct syn_cache *sc;
2991 	struct syn_cache_head *scp;
2992 	int s = splsoftnet();
2993 
2994 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2995 		splx(s);
2996 		return;
2997 	}
2998 	if (SEQ_LT(th->th_seq, sc->sc_irs) ||
2999 	    SEQ_GT(th->th_seq, sc->sc_irs+1)) {
3000 		splx(s);
3001 		return;
3002 	}
3003 	SYN_CACHE_RM(sc);
3004 	splx(s);
3005 	tcpstat.tcps_sc_reset++;
3006 	SYN_CACHE_PUT(sc);
3007 }
3008 
3009 void
3010 syn_cache_unreach(src, dst, th)
3011 	struct sockaddr *src;
3012 	struct sockaddr *dst;
3013 	struct tcphdr *th;
3014 {
3015 	struct syn_cache *sc;
3016 	struct syn_cache_head *scp;
3017 	int s;
3018 
3019 	s = splsoftnet();
3020 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3021 		splx(s);
3022 		return;
3023 	}
3024 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
3025 	if (ntohl (th->th_seq) != sc->sc_iss) {
3026 		splx(s);
3027 		return;
3028 	}
3029 
3030 	/*
3031 	 * If we've rertransmitted 3 times and this is our second error,
3032 	 * we remove the entry.  Otherwise, we allow it to continue on.
3033 	 * This prevents us from incorrectly nuking an entry during a
3034 	 * spurious network outage.
3035 	 *
3036 	 * See tcp_notify().
3037 	 */
3038 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
3039 		sc->sc_flags |= SCF_UNREACH;
3040 		splx(s);
3041 		return;
3042 	}
3043 
3044 	SYN_CACHE_RM(sc);
3045 	splx(s);
3046 	tcpstat.tcps_sc_unreach++;
3047 	SYN_CACHE_PUT(sc);
3048 }
3049 
3050 /*
3051  * Given a LISTEN socket and an inbound SYN request, add
3052  * this to the syn cache, and send back a segment:
3053  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3054  * to the source.
3055  *
3056  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3057  * Doing so would require that we hold onto the data and deliver it
3058  * to the application.  However, if we are the target of a SYN-flood
3059  * DoS attack, an attacker could send data which would eventually
3060  * consume all available buffer space if it were ACKed.  By not ACKing
3061  * the data, we avoid this DoS scenario.
3062  */
3063 
3064 int
3065 syn_cache_add(src, dst, th, hlen, so, m, optp, optlen, oi)
3066 	struct sockaddr *src;
3067 	struct sockaddr *dst;
3068 	struct tcphdr *th;
3069 	unsigned int hlen;
3070 	struct socket *so;
3071 	struct mbuf *m;
3072 	u_char *optp;
3073 	int optlen;
3074 	struct tcp_opt_info *oi;
3075 {
3076 	struct tcpcb tb, *tp;
3077 	long win;
3078 	struct syn_cache *sc;
3079 	struct syn_cache_head *scp;
3080 	struct mbuf *ipopts;
3081 
3082 	tp = sototcpcb(so);
3083 
3084 	/*
3085 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3086 	 * in_broadcast() should never return true on a received
3087 	 * packet with M_BCAST not set.
3088 	 */
3089 	if (m->m_flags & (M_BCAST|M_MCAST))
3090 		return 0;
3091 #ifdef INET6
3092 	if (m->m_flags & M_ANYCAST6)
3093 		return 0;
3094 #endif
3095 
3096 	switch (src->sa_family) {
3097 	case AF_INET:
3098 		if (IN_MULTICAST(((struct sockaddr_in *)src)->sin_addr.s_addr)
3099 		 || IN_MULTICAST(((struct sockaddr_in *)dst)->sin_addr.s_addr))
3100 			return 0;
3101 		break;
3102 #ifdef INET6
3103 	case AF_INET6:
3104 		if (IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)src)->sin6_addr)
3105 		 || IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)dst)->sin6_addr))
3106 			return 0;
3107 		break;
3108 #endif
3109 	default:
3110 		return 0;
3111 	}
3112 
3113 	/*
3114 	 * Initialize some local state.
3115 	 */
3116 	win = sbspace(&so->so_rcv);
3117 	if (win > TCP_MAXWIN)
3118 		win = TCP_MAXWIN;
3119 
3120 	if (src->sa_family == AF_INET) {
3121 		/*
3122 		 * Remember the IP options, if any.
3123 		 */
3124 		ipopts = ip_srcroute();
3125 	} else
3126 		ipopts = NULL;
3127 
3128 	if (optp) {
3129 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
3130 		tcp_dooptions(&tb, optp, optlen, th, oi);
3131 	} else
3132 		tb.t_flags = 0;
3133 
3134 	/*
3135 	 * See if we already have an entry for this connection.
3136 	 * If we do, resend the SYN,ACK.  We do not count this
3137 	 * as a retransmission (XXX though maybe we should).
3138 	 */
3139 	if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
3140 		tcpstat.tcps_sc_dupesyn++;
3141 		if (ipopts) {
3142 			/*
3143 			 * If we were remembering a previous source route,
3144 			 * forget it and use the new one we've been given.
3145 			 */
3146 			if (sc->sc_ipopts)
3147 				(void) m_free(sc->sc_ipopts);
3148 			sc->sc_ipopts = ipopts;
3149 		}
3150 		sc->sc_timestamp = tb.ts_recent;
3151 		if (syn_cache_respond(sc, m) == 0) {
3152 			tcpstat.tcps_sndacks++;
3153 			tcpstat.tcps_sndtotal++;
3154 		}
3155 		return (1);
3156 	}
3157 
3158 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
3159 	if (sc == NULL) {
3160 		if (ipopts)
3161 			(void) m_free(ipopts);
3162 		return (0);
3163 	}
3164 
3165 	/*
3166 	 * Fill in the cache, and put the necessary IP and TCP
3167 	 * options into the reply.
3168 	 */
3169 	bzero(sc, sizeof(struct syn_cache));
3170 	bcopy(src, &sc->sc_src, src->sa_len);
3171 	bcopy(dst, &sc->sc_dst, dst->sa_len);
3172 	sc->sc_flags = 0;
3173 	sc->sc_ipopts = ipopts;
3174 	sc->sc_irs = th->th_seq;
3175 	sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
3176 	sc->sc_peermaxseg = oi->maxseg;
3177 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
3178 						m->m_pkthdr.rcvif : NULL,
3179 						sc->sc_src.sa.sa_family);
3180 	sc->sc_win = win;
3181 	sc->sc_timestamp = tb.ts_recent;
3182 	if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
3183 		sc->sc_flags |= SCF_TIMESTAMP;
3184 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
3185 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
3186 		sc->sc_requested_s_scale = tb.requested_s_scale;
3187 		sc->sc_request_r_scale = 0;
3188 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
3189 		    TCP_MAXWIN << sc->sc_request_r_scale <
3190 		    so->so_rcv.sb_hiwat)
3191 			sc->sc_request_r_scale++;
3192 	} else {
3193 		sc->sc_requested_s_scale = 15;
3194 		sc->sc_request_r_scale = 15;
3195 	}
3196 	sc->sc_tp = tp;
3197 	if (syn_cache_respond(sc, m) == 0) {
3198 		syn_cache_insert(sc, tp);
3199 		tcpstat.tcps_sndacks++;
3200 		tcpstat.tcps_sndtotal++;
3201 	} else {
3202 		SYN_CACHE_PUT(sc);
3203 		tcpstat.tcps_sc_dropped++;
3204 	}
3205 	return (1);
3206 }
3207 
3208 int
3209 syn_cache_respond(sc, m)
3210 	struct syn_cache *sc;
3211 	struct mbuf *m;
3212 {
3213 	struct route *ro = &sc->sc_route4;
3214 	struct rtentry *rt;
3215 	u_int8_t *optp;
3216 	int optlen, error;
3217 	u_int16_t tlen;
3218 	struct ip *ip = NULL;
3219 #ifdef INET6
3220 	struct ip6_hdr *ip6 = NULL;
3221 #endif
3222 	struct tcphdr *th;
3223 	u_int hlen;
3224 
3225 	switch (sc->sc_src.sa.sa_family) {
3226 	case AF_INET:
3227 		hlen = sizeof(struct ip);
3228 		break;
3229 #ifdef INET6
3230 	case AF_INET6:
3231 		hlen = sizeof(struct ip6_hdr);
3232 		break;
3233 #endif
3234 	default:
3235 		if (m)
3236 			m_freem(m);
3237 		return EAFNOSUPPORT;
3238 	}
3239 
3240 	/* Compute the size of the TCP options. */
3241 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
3242 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
3243 
3244 	tlen = hlen + sizeof(struct tcphdr) + optlen;
3245 
3246 	/*
3247 	 * Create the IP+TCP header from scratch.  Reuse the received mbuf
3248 	 * if possible.
3249 	 */
3250 	if (m != NULL) {
3251 		m_freem(m->m_next);
3252 		m->m_next = NULL;
3253 		MRESETDATA(m);
3254 	} else {
3255 		MGETHDR(m, M_DONTWAIT, MT_DATA);
3256 		if (m == NULL)
3257 			return (ENOBUFS);
3258 	}
3259 
3260 	/* Fixup the mbuf. */
3261 	m->m_data += max_linkhdr;
3262 	m->m_len = m->m_pkthdr.len = tlen;
3263 #ifdef IPSEC
3264 	if (sc->sc_tp) {
3265 		struct tcpcb *tp;
3266 		struct socket *so;
3267 
3268 		tp = sc->sc_tp;
3269 		if (tp->t_inpcb)
3270 			so = tp->t_inpcb->inp_socket;
3271 #ifdef INET6
3272 		else if (tp->t_in6pcb)
3273 			so = tp->t_in6pcb->in6p_socket;
3274 #endif
3275 		else
3276 			so = NULL;
3277 		/* use IPsec policy on listening socket, on SYN ACK */
3278 		m->m_pkthdr.rcvif = (struct ifnet *)so;
3279 	}
3280 #else
3281 	m->m_pkthdr.rcvif = NULL;
3282 #endif
3283 	memset(mtod(m, u_char *), 0, tlen);
3284 
3285 	switch (sc->sc_src.sa.sa_family) {
3286 	case AF_INET:
3287 		ip = mtod(m, struct ip *);
3288 		ip->ip_dst = sc->sc_src.sin.sin_addr;
3289 		ip->ip_src = sc->sc_dst.sin.sin_addr;
3290 		ip->ip_p = IPPROTO_TCP;
3291 		th = (struct tcphdr *)(ip + 1);
3292 		th->th_dport = sc->sc_src.sin.sin_port;
3293 		th->th_sport = sc->sc_dst.sin.sin_port;
3294 		break;
3295 #ifdef INET6
3296 	case AF_INET6:
3297 		ip6 = mtod(m, struct ip6_hdr *);
3298 		ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
3299 		ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
3300 		ip6->ip6_nxt = IPPROTO_TCP;
3301 		/* ip6_plen will be updated in ip6_output() */
3302 		th = (struct tcphdr *)(ip6 + 1);
3303 		th->th_dport = sc->sc_src.sin6.sin6_port;
3304 		th->th_sport = sc->sc_dst.sin6.sin6_port;
3305 		break;
3306 #endif
3307 	default:
3308 		th = NULL;
3309 	}
3310 
3311 	th->th_seq = htonl(sc->sc_iss);
3312 	th->th_ack = htonl(sc->sc_irs + 1);
3313 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
3314 	th->th_flags = TH_SYN|TH_ACK;
3315 	th->th_win = htons(sc->sc_win);
3316 	/* th_sum already 0 */
3317 	/* th_urp already 0 */
3318 
3319 	/* Tack on the TCP options. */
3320 	optp = (u_int8_t *)(th + 1);
3321 	*optp++ = TCPOPT_MAXSEG;
3322 	*optp++ = 4;
3323 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
3324 	*optp++ = sc->sc_ourmaxseg & 0xff;
3325 
3326 	if (sc->sc_request_r_scale != 15) {
3327 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
3328 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
3329 		    sc->sc_request_r_scale);
3330 		optp += 4;
3331 	}
3332 
3333 	if (sc->sc_flags & SCF_TIMESTAMP) {
3334 		u_int32_t *lp = (u_int32_t *)(optp);
3335 		/* Form timestamp option as shown in appendix A of RFC 1323. */
3336 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
3337 		*lp++ = htonl(tcp_now);
3338 		*lp   = htonl(sc->sc_timestamp);
3339 		optp += TCPOLEN_TSTAMP_APPA;
3340 	}
3341 
3342 	/* Compute the packet's checksum. */
3343 	switch (sc->sc_src.sa.sa_family) {
3344 	case AF_INET:
3345 		ip->ip_len = htons(tlen - hlen);
3346 		th->th_sum = 0;
3347 		th->th_sum = in_cksum(m, tlen);
3348 		break;
3349 #ifdef INET6
3350 	case AF_INET6:
3351 		ip6->ip6_plen = htons(tlen - hlen);
3352 		th->th_sum = 0;
3353 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
3354 		break;
3355 #endif
3356 	}
3357 
3358 	/*
3359 	 * Fill in some straggling IP bits.  Note the stack expects
3360 	 * ip_len to be in host order, for convenience.
3361 	 */
3362 	switch (sc->sc_src.sa.sa_family) {
3363 	case AF_INET:
3364 		ip->ip_len = tlen;
3365 		ip->ip_ttl = ip_defttl;
3366 		/* XXX tos? */
3367 		break;
3368 #ifdef INET6
3369 	case AF_INET6:
3370 		ip6->ip6_vfc = IPV6_VERSION;
3371 		ip6->ip6_plen = htons(tlen - hlen);
3372 		ip6->ip6_hlim = ip6_defhlim;
3373 		/* XXX flowlabel? */
3374 		break;
3375 #endif
3376 	}
3377 
3378 	/*
3379 	 * If we're doing Path MTU discovery, we need to set DF unless
3380 	 * the route's MTU is locked.  If we don't yet know the route,
3381 	 * look it up now.  We will copy this reference to the inpcb
3382 	 * when we finish creating the connection.
3383 	 */
3384 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
3385 		if (ro->ro_rt != NULL) {
3386 			RTFREE(ro->ro_rt);
3387 			ro->ro_rt = NULL;
3388 		}
3389 		bcopy(&sc->sc_src, &ro->ro_dst, sc->sc_src.sa.sa_len);
3390 		rtalloc(ro);
3391 		if ((rt = ro->ro_rt) == NULL) {
3392 			m_freem(m);
3393 			switch (sc->sc_src.sa.sa_family) {
3394 			case AF_INET:
3395 				ipstat.ips_noroute++;
3396 				break;
3397 #ifdef INET6
3398 			case AF_INET6:
3399 				ip6stat.ip6s_noroute++;
3400 				break;
3401 #endif
3402 			}
3403 			return (EHOSTUNREACH);
3404 		}
3405 	}
3406 
3407 	switch (sc->sc_src.sa.sa_family) {
3408 	case AF_INET:
3409 		if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
3410 			ip->ip_off |= IP_DF;
3411 
3412 		/* ...and send it off! */
3413 		error = ip_output(m, sc->sc_ipopts, ro, 0, NULL);
3414 		break;
3415 #ifdef INET6
3416 	case AF_INET6:
3417 		error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro,
3418 			0, NULL);
3419 		break;
3420 #endif
3421 	default:
3422 		error = EAFNOSUPPORT;
3423 		break;
3424 	}
3425 	return (error);
3426 }
3427