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