xref: /netbsd-src/sys/netinet/tcp_input.c (revision 1b9578b8c2c1f848eeb16dabbfd7d1f0d9fdefbd)
1 /*	$NetBSD: tcp_input.c,v 1.314 2011/05/25 23:20:57 gdt 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, 2005, 2006,
74  * 2011 The NetBSD Foundation, Inc.
75  * All rights reserved.
76  *
77  * This code is derived from software contributed to The NetBSD Foundation
78  * by Coyote Point Systems, Inc.
79  * This code is derived from software contributed to The NetBSD Foundation
80  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
81  * Facility, NASA Ames Research Center.
82  * This code is derived from software contributed to The NetBSD Foundation
83  * by Charles M. Hannum.
84  * This code is derived from software contributed to The NetBSD Foundation
85  * by Rui Paulo.
86  *
87  * Redistribution and use in source and binary forms, with or without
88  * modification, are permitted provided that the following conditions
89  * are met:
90  * 1. Redistributions of source code must retain the above copyright
91  *    notice, this list of conditions and the following disclaimer.
92  * 2. Redistributions in binary form must reproduce the above copyright
93  *    notice, this list of conditions and the following disclaimer in the
94  *    documentation and/or other materials provided with the distribution.
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.314 2011/05/25 23:20:57 gdt 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 #ifdef TCP_SIGNATURE
171 #include <sys/md5.h>
172 #endif
173 #include <sys/lwp.h> /* for lwp0 */
174 
175 #include <net/if.h>
176 #include <net/route.h>
177 #include <net/if_types.h>
178 
179 #include <netinet/in.h>
180 #include <netinet/in_systm.h>
181 #include <netinet/ip.h>
182 #include <netinet/in_pcb.h>
183 #include <netinet/in_var.h>
184 #include <netinet/ip_var.h>
185 #include <netinet/in_offload.h>
186 
187 #ifdef INET6
188 #ifndef INET
189 #include <netinet/in.h>
190 #endif
191 #include <netinet/ip6.h>
192 #include <netinet6/ip6_var.h>
193 #include <netinet6/in6_pcb.h>
194 #include <netinet6/ip6_var.h>
195 #include <netinet6/in6_var.h>
196 #include <netinet/icmp6.h>
197 #include <netinet6/nd6.h>
198 #ifdef TCP_SIGNATURE
199 #include <netinet6/scope6_var.h>
200 #endif
201 #endif
202 
203 #ifndef INET6
204 /* always need ip6.h for IP6_EXTHDR_GET */
205 #include <netinet/ip6.h>
206 #endif
207 
208 #include <netinet/tcp.h>
209 #include <netinet/tcp_fsm.h>
210 #include <netinet/tcp_seq.h>
211 #include <netinet/tcp_timer.h>
212 #include <netinet/tcp_var.h>
213 #include <netinet/tcp_private.h>
214 #include <netinet/tcpip.h>
215 #include <netinet/tcp_congctl.h>
216 #include <netinet/tcp_debug.h>
217 
218 #include <machine/stdarg.h>
219 
220 #ifdef IPSEC
221 #include <netinet6/ipsec.h>
222 #include <netinet6/ipsec_private.h>
223 #include <netkey/key.h>
224 #endif /*IPSEC*/
225 #ifdef INET6
226 #include "faith.h"
227 #if defined(NFAITH) && NFAITH > 0
228 #include <net/if_faith.h>
229 #endif
230 #endif	/* IPSEC */
231 
232 #ifdef FAST_IPSEC
233 #include <netipsec/ipsec.h>
234 #include <netipsec/ipsec_var.h>
235 #include <netipsec/ipsec_private.h>
236 #include <netipsec/key.h>
237 #ifdef INET6
238 #include <netipsec/ipsec6.h>
239 #endif
240 #endif	/* FAST_IPSEC*/
241 
242 #include <netinet/tcp_vtw.h>
243 
244 int	tcprexmtthresh = 3;
245 int	tcp_log_refused;
246 
247 int	tcp_do_autorcvbuf = 1;
248 int	tcp_autorcvbuf_inc = 16 * 1024;
249 int	tcp_autorcvbuf_max = 256 * 1024;
250 int	tcp_msl = (TCPTV_MSL / PR_SLOWHZ);
251 
252 static int tcp_rst_ppslim_count = 0;
253 static struct timeval tcp_rst_ppslim_last;
254 static int tcp_ackdrop_ppslim_count = 0;
255 static struct timeval tcp_ackdrop_ppslim_last;
256 
257 #define TCP_PAWS_IDLE	(24U * 24 * 60 * 60 * PR_SLOWHZ)
258 
259 /* for modulo comparisons of timestamps */
260 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
261 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
262 
263 /*
264  * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
265  */
266 #ifdef INET6
267 static inline void
268 nd6_hint(struct tcpcb *tp)
269 {
270 	struct rtentry *rt;
271 
272 	if (tp != NULL && tp->t_in6pcb != NULL && tp->t_family == AF_INET6 &&
273 	    (rt = rtcache_validate(&tp->t_in6pcb->in6p_route)) != NULL)
274 		nd6_nud_hint(rt, NULL, 0);
275 }
276 #else
277 static inline void
278 nd6_hint(struct tcpcb *tp)
279 {
280 }
281 #endif
282 
283 /*
284  * Compute ACK transmission behavior.  Delay the ACK unless
285  * we have already delayed an ACK (must send an ACK every two segments).
286  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
287  * option is enabled.
288  */
289 static void
290 tcp_setup_ack(struct tcpcb *tp, const struct tcphdr *th)
291 {
292 
293 	if (tp->t_flags & TF_DELACK ||
294 	    (tcp_ack_on_push && th->th_flags & TH_PUSH))
295 		tp->t_flags |= TF_ACKNOW;
296 	else
297 		TCP_SET_DELACK(tp);
298 }
299 
300 static void
301 icmp_check(struct tcpcb *tp, const struct tcphdr *th, int acked)
302 {
303 
304 	/*
305 	 * If we had a pending ICMP message that refers to data that have
306 	 * just been acknowledged, disregard the recorded ICMP message.
307 	 */
308 	if ((tp->t_flags & TF_PMTUD_PEND) &&
309 	    SEQ_GT(th->th_ack, tp->t_pmtud_th_seq))
310 		tp->t_flags &= ~TF_PMTUD_PEND;
311 
312 	/*
313 	 * Keep track of the largest chunk of data
314 	 * acknowledged since last PMTU update
315 	 */
316 	if (tp->t_pmtud_mss_acked < acked)
317 		tp->t_pmtud_mss_acked = acked;
318 }
319 
320 /*
321  * Convert TCP protocol fields to host order for easier processing.
322  */
323 static void
324 tcp_fields_to_host(struct tcphdr *th)
325 {
326 
327 	NTOHL(th->th_seq);
328 	NTOHL(th->th_ack);
329 	NTOHS(th->th_win);
330 	NTOHS(th->th_urp);
331 }
332 
333 /*
334  * ... and reverse the above.
335  */
336 static void
337 tcp_fields_to_net(struct tcphdr *th)
338 {
339 
340 	HTONL(th->th_seq);
341 	HTONL(th->th_ack);
342 	HTONS(th->th_win);
343 	HTONS(th->th_urp);
344 }
345 
346 #ifdef TCP_CSUM_COUNTERS
347 #include <sys/device.h>
348 
349 #if defined(INET)
350 extern struct evcnt tcp_hwcsum_ok;
351 extern struct evcnt tcp_hwcsum_bad;
352 extern struct evcnt tcp_hwcsum_data;
353 extern struct evcnt tcp_swcsum;
354 #endif /* defined(INET) */
355 #if defined(INET6)
356 extern struct evcnt tcp6_hwcsum_ok;
357 extern struct evcnt tcp6_hwcsum_bad;
358 extern struct evcnt tcp6_hwcsum_data;
359 extern struct evcnt tcp6_swcsum;
360 #endif /* defined(INET6) */
361 
362 #define	TCP_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
363 
364 #else
365 
366 #define	TCP_CSUM_COUNTER_INCR(ev)	/* nothing */
367 
368 #endif /* TCP_CSUM_COUNTERS */
369 
370 #ifdef TCP_REASS_COUNTERS
371 #include <sys/device.h>
372 
373 extern struct evcnt tcp_reass_;
374 extern struct evcnt tcp_reass_empty;
375 extern struct evcnt tcp_reass_iteration[8];
376 extern struct evcnt tcp_reass_prependfirst;
377 extern struct evcnt tcp_reass_prepend;
378 extern struct evcnt tcp_reass_insert;
379 extern struct evcnt tcp_reass_inserttail;
380 extern struct evcnt tcp_reass_append;
381 extern struct evcnt tcp_reass_appendtail;
382 extern struct evcnt tcp_reass_overlaptail;
383 extern struct evcnt tcp_reass_overlapfront;
384 extern struct evcnt tcp_reass_segdup;
385 extern struct evcnt tcp_reass_fragdup;
386 
387 #define	TCP_REASS_COUNTER_INCR(ev)	(ev)->ev_count++
388 
389 #else
390 
391 #define	TCP_REASS_COUNTER_INCR(ev)	/* nothing */
392 
393 #endif /* TCP_REASS_COUNTERS */
394 
395 static int tcp_reass(struct tcpcb *, const struct tcphdr *, struct mbuf *,
396     int *);
397 static int tcp_dooptions(struct tcpcb *, const u_char *, int,
398     struct tcphdr *, struct mbuf *, int, struct tcp_opt_info *);
399 
400 #ifdef INET
401 static void tcp4_log_refused(const struct ip *, const struct tcphdr *);
402 #endif
403 #ifdef INET6
404 static void tcp6_log_refused(const struct ip6_hdr *, const struct tcphdr *);
405 #endif
406 
407 #define	TRAVERSE(x) while ((x)->m_next) (x) = (x)->m_next
408 
409 #if defined(MBUFTRACE)
410 struct mowner tcp_reass_mowner = MOWNER_INIT("tcp", "reass");
411 #endif /* defined(MBUFTRACE) */
412 
413 static struct pool tcpipqent_pool;
414 
415 void
416 tcpipqent_init(void)
417 {
418 
419 	pool_init(&tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl",
420 	    NULL, IPL_VM);
421 }
422 
423 struct ipqent *
424 tcpipqent_alloc(void)
425 {
426 	struct ipqent *ipqe;
427 	int s;
428 
429 	s = splvm();
430 	ipqe = pool_get(&tcpipqent_pool, PR_NOWAIT);
431 	splx(s);
432 
433 	return ipqe;
434 }
435 
436 void
437 tcpipqent_free(struct ipqent *ipqe)
438 {
439 	int s;
440 
441 	s = splvm();
442 	pool_put(&tcpipqent_pool, ipqe);
443 	splx(s);
444 }
445 
446 static int
447 tcp_reass(struct tcpcb *tp, const struct tcphdr *th, struct mbuf *m, int *tlen)
448 {
449 	struct ipqent *p, *q, *nq, *tiqe = NULL;
450 	struct socket *so = NULL;
451 	int pkt_flags;
452 	tcp_seq pkt_seq;
453 	unsigned pkt_len;
454 	u_long rcvpartdupbyte = 0;
455 	u_long rcvoobyte;
456 #ifdef TCP_REASS_COUNTERS
457 	u_int count = 0;
458 #endif
459 	uint64_t *tcps;
460 
461 	if (tp->t_inpcb)
462 		so = tp->t_inpcb->inp_socket;
463 #ifdef INET6
464 	else if (tp->t_in6pcb)
465 		so = tp->t_in6pcb->in6p_socket;
466 #endif
467 
468 	TCP_REASS_LOCK_CHECK(tp);
469 
470 	/*
471 	 * Call with th==0 after become established to
472 	 * force pre-ESTABLISHED data up to user socket.
473 	 */
474 	if (th == 0)
475 		goto present;
476 
477 	m_claimm(m, &tcp_reass_mowner);
478 
479 	rcvoobyte = *tlen;
480 	/*
481 	 * Copy these to local variables because the tcpiphdr
482 	 * gets munged while we are collapsing mbufs.
483 	 */
484 	pkt_seq = th->th_seq;
485 	pkt_len = *tlen;
486 	pkt_flags = th->th_flags;
487 
488 	TCP_REASS_COUNTER_INCR(&tcp_reass_);
489 
490 	if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) {
491 		/*
492 		 * When we miss a packet, the vast majority of time we get
493 		 * packets that follow it in order.  So optimize for that.
494 		 */
495 		if (pkt_seq == p->ipqe_seq + p->ipqe_len) {
496 			p->ipqe_len += pkt_len;
497 			p->ipqe_flags |= pkt_flags;
498 			m_cat(p->ipre_mlast, m);
499 			TRAVERSE(p->ipre_mlast);
500 			m = NULL;
501 			tiqe = p;
502 			TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq);
503 			TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail);
504 			goto skip_replacement;
505 		}
506 		/*
507 		 * While we're here, if the pkt is completely beyond
508 		 * anything we have, just insert it at the tail.
509 		 */
510 		if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) {
511 			TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail);
512 			goto insert_it;
513 		}
514 	}
515 
516 	q = TAILQ_FIRST(&tp->segq);
517 
518 	if (q != NULL) {
519 		/*
520 		 * If this segment immediately precedes the first out-of-order
521 		 * block, simply slap the segment in front of it and (mostly)
522 		 * skip the complicated logic.
523 		 */
524 		if (pkt_seq + pkt_len == q->ipqe_seq) {
525 			q->ipqe_seq = pkt_seq;
526 			q->ipqe_len += pkt_len;
527 			q->ipqe_flags |= pkt_flags;
528 			m_cat(m, q->ipqe_m);
529 			q->ipqe_m = m;
530 			q->ipre_mlast = m; /* last mbuf may have changed */
531 			TRAVERSE(q->ipre_mlast);
532 			tiqe = q;
533 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
534 			TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst);
535 			goto skip_replacement;
536 		}
537 	} else {
538 		TCP_REASS_COUNTER_INCR(&tcp_reass_empty);
539 	}
540 
541 	/*
542 	 * Find a segment which begins after this one does.
543 	 */
544 	for (p = NULL; q != NULL; q = nq) {
545 		nq = TAILQ_NEXT(q, ipqe_q);
546 #ifdef TCP_REASS_COUNTERS
547 		count++;
548 #endif
549 		/*
550 		 * If the received segment is just right after this
551 		 * fragment, merge the two together and then check
552 		 * for further overlaps.
553 		 */
554 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
555 #ifdef TCPREASS_DEBUG
556 			printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
557 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
558 			       q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
559 #endif
560 			pkt_len += q->ipqe_len;
561 			pkt_flags |= q->ipqe_flags;
562 			pkt_seq = q->ipqe_seq;
563 			m_cat(q->ipre_mlast, m);
564 			TRAVERSE(q->ipre_mlast);
565 			m = q->ipqe_m;
566 			TCP_REASS_COUNTER_INCR(&tcp_reass_append);
567 			goto free_ipqe;
568 		}
569 		/*
570 		 * If the received segment is completely past this
571 		 * fragment, we need to go the next fragment.
572 		 */
573 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
574 			p = q;
575 			continue;
576 		}
577 		/*
578 		 * If the fragment is past the received segment,
579 		 * it (or any following) can't be concatenated.
580 		 */
581 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) {
582 			TCP_REASS_COUNTER_INCR(&tcp_reass_insert);
583 			break;
584 		}
585 
586 		/*
587 		 * We've received all the data in this segment before.
588 		 * mark it as a duplicate and return.
589 		 */
590 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
591 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
592 			tcps = TCP_STAT_GETREF();
593 			tcps[TCP_STAT_RCVDUPPACK]++;
594 			tcps[TCP_STAT_RCVDUPBYTE] += pkt_len;
595 			TCP_STAT_PUTREF();
596 			tcp_new_dsack(tp, pkt_seq, pkt_len);
597 			m_freem(m);
598 			if (tiqe != NULL) {
599 				tcpipqent_free(tiqe);
600 			}
601 			TCP_REASS_COUNTER_INCR(&tcp_reass_segdup);
602 			goto out;
603 		}
604 		/*
605 		 * Received segment completely overlaps this fragment
606 		 * so we drop the fragment (this keeps the temporal
607 		 * ordering of segments correct).
608 		 */
609 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
610 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
611 			rcvpartdupbyte += q->ipqe_len;
612 			m_freem(q->ipqe_m);
613 			TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup);
614 			goto free_ipqe;
615 		}
616 		/*
617 		 * RX'ed segment extends past the end of the
618 		 * fragment.  Drop the overlapping bytes.  Then
619 		 * merge the fragment and segment then treat as
620 		 * a longer received packet.
621 		 */
622 		if (SEQ_LT(q->ipqe_seq, pkt_seq) &&
623 		    SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
624 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
625 #ifdef TCPREASS_DEBUG
626 			printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
627 			       tp, overlap,
628 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
629 #endif
630 			m_adj(m, overlap);
631 			rcvpartdupbyte += overlap;
632 			m_cat(q->ipre_mlast, m);
633 			TRAVERSE(q->ipre_mlast);
634 			m = q->ipqe_m;
635 			pkt_seq = q->ipqe_seq;
636 			pkt_len += q->ipqe_len - overlap;
637 			rcvoobyte -= overlap;
638 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail);
639 			goto free_ipqe;
640 		}
641 		/*
642 		 * RX'ed segment extends past the front of the
643 		 * fragment.  Drop the overlapping bytes on the
644 		 * received packet.  The packet will then be
645 		 * contatentated with this fragment a bit later.
646 		 */
647 		if (SEQ_GT(q->ipqe_seq, pkt_seq) &&
648 		    SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
649 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
650 #ifdef TCPREASS_DEBUG
651 			printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
652 			       tp, overlap,
653 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
654 #endif
655 			m_adj(m, -overlap);
656 			pkt_len -= overlap;
657 			rcvpartdupbyte += overlap;
658 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront);
659 			rcvoobyte -= overlap;
660 		}
661 		/*
662 		 * If the received segment immediates precedes this
663 		 * fragment then tack the fragment onto this segment
664 		 * and reinsert the data.
665 		 */
666 		if (q->ipqe_seq == pkt_seq + pkt_len) {
667 #ifdef TCPREASS_DEBUG
668 			printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
669 			       tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
670 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
671 #endif
672 			pkt_len += q->ipqe_len;
673 			pkt_flags |= q->ipqe_flags;
674 			m_cat(m, q->ipqe_m);
675 			TAILQ_REMOVE(&tp->segq, q, ipqe_q);
676 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
677 			tp->t_segqlen--;
678 			KASSERT(tp->t_segqlen >= 0);
679 			KASSERT(tp->t_segqlen != 0 ||
680 			    (TAILQ_EMPTY(&tp->segq) &&
681 			    TAILQ_EMPTY(&tp->timeq)));
682 			if (tiqe == NULL) {
683 				tiqe = q;
684 			} else {
685 				tcpipqent_free(q);
686 			}
687 			TCP_REASS_COUNTER_INCR(&tcp_reass_prepend);
688 			break;
689 		}
690 		/*
691 		 * If the fragment is before the segment, remember it.
692 		 * When this loop is terminated, p will contain the
693 		 * pointer to fragment that is right before the received
694 		 * segment.
695 		 */
696 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
697 			p = q;
698 
699 		continue;
700 
701 		/*
702 		 * This is a common operation.  It also will allow
703 		 * to save doing a malloc/free in most instances.
704 		 */
705 	  free_ipqe:
706 		TAILQ_REMOVE(&tp->segq, q, ipqe_q);
707 		TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
708 		tp->t_segqlen--;
709 		KASSERT(tp->t_segqlen >= 0);
710 		KASSERT(tp->t_segqlen != 0 ||
711 		    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
712 		if (tiqe == NULL) {
713 			tiqe = q;
714 		} else {
715 			tcpipqent_free(q);
716 		}
717 	}
718 
719 #ifdef TCP_REASS_COUNTERS
720 	if (count > 7)
721 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]);
722 	else if (count > 0)
723 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]);
724 #endif
725 
726     insert_it:
727 
728 	/*
729 	 * Allocate a new queue entry since the received segment did not
730 	 * collapse onto any other out-of-order block; thus we are allocating
731 	 * a new block.  If it had collapsed, tiqe would not be NULL and
732 	 * we would be reusing it.
733 	 * XXX If we can't, just drop the packet.  XXX
734 	 */
735 	if (tiqe == NULL) {
736 		tiqe = tcpipqent_alloc();
737 		if (tiqe == NULL) {
738 			TCP_STATINC(TCP_STAT_RCVMEMDROP);
739 			m_freem(m);
740 			goto out;
741 		}
742 	}
743 
744 	/*
745 	 * Update the counters.
746 	 */
747 	tcps = TCP_STAT_GETREF();
748 	tcps[TCP_STAT_RCVOOPACK]++;
749 	tcps[TCP_STAT_RCVOOBYTE] += rcvoobyte;
750 	if (rcvpartdupbyte) {
751 	    tcps[TCP_STAT_RCVPARTDUPPACK]++;
752 	    tcps[TCP_STAT_RCVPARTDUPBYTE] += rcvpartdupbyte;
753 	}
754 	TCP_STAT_PUTREF();
755 
756 	/*
757 	 * Insert the new fragment queue entry into both queues.
758 	 */
759 	tiqe->ipqe_m = m;
760 	tiqe->ipre_mlast = m;
761 	tiqe->ipqe_seq = pkt_seq;
762 	tiqe->ipqe_len = pkt_len;
763 	tiqe->ipqe_flags = pkt_flags;
764 	if (p == NULL) {
765 		TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
766 #ifdef TCPREASS_DEBUG
767 		if (tiqe->ipqe_seq != tp->rcv_nxt)
768 			printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
769 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
770 #endif
771 	} else {
772 		TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q);
773 #ifdef TCPREASS_DEBUG
774 		printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
775 		       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
776 		       p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
777 #endif
778 	}
779 	tp->t_segqlen++;
780 
781 skip_replacement:
782 
783 	TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
784 
785 present:
786 	/*
787 	 * Present data to user, advancing rcv_nxt through
788 	 * completed sequence space.
789 	 */
790 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
791 		goto out;
792 	q = TAILQ_FIRST(&tp->segq);
793 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
794 		goto out;
795 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
796 		goto out;
797 
798 	tp->rcv_nxt += q->ipqe_len;
799 	pkt_flags = q->ipqe_flags & TH_FIN;
800 	nd6_hint(tp);
801 
802 	TAILQ_REMOVE(&tp->segq, q, ipqe_q);
803 	TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
804 	tp->t_segqlen--;
805 	KASSERT(tp->t_segqlen >= 0);
806 	KASSERT(tp->t_segqlen != 0 ||
807 	    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
808 	if (so->so_state & SS_CANTRCVMORE)
809 		m_freem(q->ipqe_m);
810 	else
811 		sbappendstream(&so->so_rcv, q->ipqe_m);
812 	tcpipqent_free(q);
813 	TCP_REASS_UNLOCK(tp);
814 	sorwakeup(so);
815 	return (pkt_flags);
816 out:
817 	TCP_REASS_UNLOCK(tp);
818 	return (0);
819 }
820 
821 #ifdef INET6
822 int
823 tcp6_input(struct mbuf **mp, int *offp, int proto)
824 {
825 	struct mbuf *m = *mp;
826 
827 	/*
828 	 * draft-itojun-ipv6-tcp-to-anycast
829 	 * better place to put this in?
830 	 */
831 	if (m->m_flags & M_ANYCAST6) {
832 		struct ip6_hdr *ip6;
833 		if (m->m_len < sizeof(struct ip6_hdr)) {
834 			if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
835 				TCP_STATINC(TCP_STAT_RCVSHORT);
836 				return IPPROTO_DONE;
837 			}
838 		}
839 		ip6 = mtod(m, struct ip6_hdr *);
840 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
841 		    (char *)&ip6->ip6_dst - (char *)ip6);
842 		return IPPROTO_DONE;
843 	}
844 
845 	tcp_input(m, *offp, proto);
846 	return IPPROTO_DONE;
847 }
848 #endif
849 
850 #ifdef INET
851 static void
852 tcp4_log_refused(const struct ip *ip, const struct tcphdr *th)
853 {
854 	char src[4*sizeof "123"];
855 	char dst[4*sizeof "123"];
856 
857 	if (ip) {
858 		strlcpy(src, inet_ntoa(ip->ip_src), sizeof(src));
859 		strlcpy(dst, inet_ntoa(ip->ip_dst), sizeof(dst));
860 	}
861 	else {
862 		strlcpy(src, "(unknown)", sizeof(src));
863 		strlcpy(dst, "(unknown)", sizeof(dst));
864 	}
865 	log(LOG_INFO,
866 	    "Connection attempt to TCP %s:%d from %s:%d\n",
867 	    dst, ntohs(th->th_dport),
868 	    src, ntohs(th->th_sport));
869 }
870 #endif
871 
872 #ifdef INET6
873 static void
874 tcp6_log_refused(const struct ip6_hdr *ip6, const struct tcphdr *th)
875 {
876 	char src[INET6_ADDRSTRLEN];
877 	char dst[INET6_ADDRSTRLEN];
878 
879 	if (ip6) {
880 		strlcpy(src, ip6_sprintf(&ip6->ip6_src), sizeof(src));
881 		strlcpy(dst, ip6_sprintf(&ip6->ip6_dst), sizeof(dst));
882 	}
883 	else {
884 		strlcpy(src, "(unknown v6)", sizeof(src));
885 		strlcpy(dst, "(unknown v6)", sizeof(dst));
886 	}
887 	log(LOG_INFO,
888 	    "Connection attempt to TCP [%s]:%d from [%s]:%d\n",
889 	    dst, ntohs(th->th_dport),
890 	    src, ntohs(th->th_sport));
891 }
892 #endif
893 
894 /*
895  * Checksum extended TCP header and data.
896  */
897 int
898 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th,
899     int toff, int off, int tlen)
900 {
901 
902 	/*
903 	 * XXX it's better to record and check if this mbuf is
904 	 * already checked.
905 	 */
906 
907 	switch (af) {
908 #ifdef INET
909 	case AF_INET:
910 		switch (m->m_pkthdr.csum_flags &
911 			((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv4) |
912 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
913 		case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD:
914 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad);
915 			goto badcsum;
916 
917 		case M_CSUM_TCPv4|M_CSUM_DATA: {
918 			u_int32_t hw_csum = m->m_pkthdr.csum_data;
919 
920 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data);
921 			if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) {
922 				const struct ip *ip =
923 				    mtod(m, const struct ip *);
924 
925 				hw_csum = in_cksum_phdr(ip->ip_src.s_addr,
926 				    ip->ip_dst.s_addr,
927 				    htons(hw_csum + tlen + off + IPPROTO_TCP));
928 			}
929 			if ((hw_csum ^ 0xffff) != 0)
930 				goto badcsum;
931 			break;
932 		}
933 
934 		case M_CSUM_TCPv4:
935 			/* Checksum was okay. */
936 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok);
937 			break;
938 
939 		default:
940 			/*
941 			 * Must compute it ourselves.  Maybe skip checksum
942 			 * on loopback interfaces.
943 			 */
944 			if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
945 					     IFF_LOOPBACK) ||
946 					   tcp_do_loopback_cksum)) {
947 				TCP_CSUM_COUNTER_INCR(&tcp_swcsum);
948 				if (in4_cksum(m, IPPROTO_TCP, toff,
949 					      tlen + off) != 0)
950 					goto badcsum;
951 			}
952 			break;
953 		}
954 		break;
955 #endif /* INET4 */
956 
957 #ifdef INET6
958 	case AF_INET6:
959 		switch (m->m_pkthdr.csum_flags &
960 			((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv6) |
961 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
962 		case M_CSUM_TCPv6|M_CSUM_TCP_UDP_BAD:
963 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_bad);
964 			goto badcsum;
965 
966 #if 0 /* notyet */
967 		case M_CSUM_TCPv6|M_CSUM_DATA:
968 #endif
969 
970 		case M_CSUM_TCPv6:
971 			/* Checksum was okay. */
972 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_ok);
973 			break;
974 
975 		default:
976 			/*
977 			 * Must compute it ourselves.  Maybe skip checksum
978 			 * on loopback interfaces.
979 			 */
980 			if (__predict_true((m->m_flags & M_LOOP) == 0 ||
981 			    tcp_do_loopback_cksum)) {
982 				TCP_CSUM_COUNTER_INCR(&tcp6_swcsum);
983 				if (in6_cksum(m, IPPROTO_TCP, toff,
984 				    tlen + off) != 0)
985 					goto badcsum;
986 			}
987 		}
988 		break;
989 #endif /* INET6 */
990 	}
991 
992 	return 0;
993 
994 badcsum:
995 	TCP_STATINC(TCP_STAT_RCVBADSUM);
996 	return -1;
997 }
998 
999 /* When a packet arrives addressed to a vestigial tcpbp, we
1000  * nevertheless have to respond to it per the spec.
1001  */
1002 static void tcp_vtw_input(struct tcphdr *th, vestigial_inpcb_t *vp,
1003 			  struct mbuf *m, int tlen, int multicast)
1004 {
1005 	int		tiflags;
1006 	int		todrop, dupseg;
1007 	uint32_t	t_flags = 0;
1008 	uint64_t	*tcps;
1009 
1010 	tiflags = th->th_flags;
1011 	todrop  = vp->rcv_nxt - th->th_seq;
1012 	dupseg  = false;
1013 
1014 	if (todrop > 0) {
1015 		if (tiflags & TH_SYN) {
1016 			tiflags &= ~TH_SYN;
1017 			++th->th_seq;
1018 			if (th->th_urp > 1)
1019 				--th->th_urp;
1020 			else {
1021 				tiflags &= ~TH_URG;
1022 				th->th_urp = 0;
1023 			}
1024 			--todrop;
1025 		}
1026 		if (todrop > tlen ||
1027 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1028 			/*
1029 			 * Any valid FIN or RST must be to the left of the
1030 			 * window.  At this point the FIN or RST must be a
1031 			 * duplicate or out of sequence; drop it.
1032 			 */
1033 			if (tiflags & TH_RST)
1034 				goto drop;
1035 			tiflags &= ~(TH_FIN|TH_RST);
1036 			/*
1037 			 * Send an ACK to resynchronize and drop any data.
1038 			 * But keep on processing for RST or ACK.
1039 			 */
1040 			t_flags |= TF_ACKNOW;
1041 			todrop = tlen;
1042 			dupseg = true;
1043 			tcps = TCP_STAT_GETREF();
1044 			tcps[TCP_STAT_RCVDUPPACK] += 1;
1045 			tcps[TCP_STAT_RCVDUPBYTE] += todrop;
1046 			TCP_STAT_PUTREF();
1047 		} else if ((tiflags & TH_RST)
1048 			   && th->th_seq != vp->rcv_nxt) {
1049 			/*
1050 			 * Test for reset before adjusting the sequence
1051 			 * number for overlapping data.
1052 			 */
1053 			goto dropafterack_ratelim;
1054 		} else {
1055 			tcps = TCP_STAT_GETREF();
1056 			tcps[TCP_STAT_RCVPARTDUPPACK] += 1;
1057 			tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
1058 			TCP_STAT_PUTREF();
1059 		}
1060 
1061 //		tcp_new_dsack(tp, th->th_seq, todrop);
1062 //		hdroptlen += todrop;	/*drop from head afterwards*/
1063 
1064 		th->th_seq += todrop;
1065 		tlen -= todrop;
1066 
1067 		if (th->th_urp > todrop)
1068 			th->th_urp -= todrop;
1069 		else {
1070 			tiflags &= ~TH_URG;
1071 			th->th_urp = 0;
1072 		}
1073 	}
1074 
1075 	/*
1076 	 * If new data are received on a connection after the
1077 	 * user processes are gone, then RST the other end.
1078 	 */
1079 	if (tlen) {
1080 		TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
1081 		goto dropwithreset;
1082 	}
1083 
1084 	/*
1085 	 * If segment ends after window, drop trailing data
1086 	 * (and PUSH and FIN); if nothing left, just ACK.
1087 	 */
1088 	todrop = (th->th_seq + tlen) - (vp->rcv_nxt+vp->rcv_wnd);
1089 
1090 	if (todrop > 0) {
1091 		TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
1092 		if (todrop >= tlen) {
1093 			/*
1094 			 * The segment actually starts after the window.
1095 			 * th->th_seq + tlen - vp->rcv_nxt - vp->rcv_wnd >= tlen
1096 			 * th->th_seq - vp->rcv_nxt - vp->rcv_wnd >= 0
1097 			 * th->th_seq >= vp->rcv_nxt + vp->rcv_wnd
1098 			 */
1099 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
1100 			/*
1101 			 * If a new connection request is received
1102 			 * while in TIME_WAIT, drop the old connection
1103 			 * and start over if the sequence numbers
1104 			 * are above the previous ones.
1105 			 */
1106 			if ((tiflags & TH_SYN)
1107 			    && SEQ_GT(th->th_seq, vp->rcv_nxt)) {
1108 				/* We only support this in the !NOFDREF case, which
1109 				 * is to say: not here.
1110 				 */
1111 				goto dropwithreset;;
1112 			}
1113 			/*
1114 			 * If window is closed can only take segments at
1115 			 * window edge, and have to drop data and PUSH from
1116 			 * incoming segments.  Continue processing, but
1117 			 * remember to ack.  Otherwise, drop segment
1118 			 * and (if not RST) ack.
1119 			 */
1120 			if (vp->rcv_wnd == 0 && th->th_seq == vp->rcv_nxt) {
1121 				t_flags |= TF_ACKNOW;
1122 				TCP_STATINC(TCP_STAT_RCVWINPROBE);
1123 			} else
1124 				goto dropafterack;
1125 		} else
1126 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
1127 		m_adj(m, -todrop);
1128 		tlen -= todrop;
1129 		tiflags &= ~(TH_PUSH|TH_FIN);
1130 	}
1131 
1132 	if (tiflags & TH_RST) {
1133 		if (th->th_seq != vp->rcv_nxt)
1134 			goto dropafterack_ratelim;
1135 
1136 		vtw_del(vp->ctl, vp->vtw);
1137 		goto drop;
1138 	}
1139 
1140 	/*
1141 	 * If the ACK bit is off we drop the segment and return.
1142 	 */
1143 	if ((tiflags & TH_ACK) == 0) {
1144 		if (t_flags & TF_ACKNOW)
1145 			goto dropafterack;
1146 		else
1147 			goto drop;
1148 	}
1149 
1150 	/*
1151 	 * In TIME_WAIT state the only thing that should arrive
1152 	 * is a retransmission of the remote FIN.  Acknowledge
1153 	 * it and restart the finack timer.
1154 	 */
1155 	vtw_restart(vp);
1156 	goto dropafterack;
1157 
1158 dropafterack:
1159 	/*
1160 	 * Generate an ACK dropping incoming segment if it occupies
1161 	 * sequence space, where the ACK reflects our state.
1162 	 */
1163 	if (tiflags & TH_RST)
1164 		goto drop;
1165 	goto dropafterack2;
1166 
1167 dropafterack_ratelim:
1168 	/*
1169 	 * We may want to rate-limit ACKs against SYN/RST attack.
1170 	 */
1171 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
1172 			 tcp_ackdrop_ppslim) == 0) {
1173 		/* XXX stat */
1174 		goto drop;
1175 	}
1176 	/* ...fall into dropafterack2... */
1177 
1178 dropafterack2:
1179 	(void)tcp_respond(0, m, m, th, th->th_seq + tlen, th->th_ack,
1180 			  TH_ACK);
1181 	return;
1182 
1183 dropwithreset:
1184 	/*
1185 	 * Generate a RST, dropping incoming segment.
1186 	 * Make ACK acceptable to originator of segment.
1187 	 */
1188 	if (tiflags & TH_RST)
1189 		goto drop;
1190 
1191 	if (tiflags & TH_ACK)
1192 		tcp_respond(0, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
1193 	else {
1194 		if (tiflags & TH_SYN)
1195 			++tlen;
1196 		(void)tcp_respond(0, m, m, th, th->th_seq + tlen, (tcp_seq)0,
1197 				  TH_RST|TH_ACK);
1198 	}
1199 	return;
1200 drop:
1201 	m_freem(m);
1202 }
1203 
1204 /*
1205  * TCP input routine, follows pages 65-76 of RFC 793 very closely.
1206  */
1207 void
1208 tcp_input(struct mbuf *m, ...)
1209 {
1210 	struct tcphdr *th;
1211 	struct ip *ip;
1212 	struct inpcb *inp;
1213 #ifdef INET6
1214 	struct ip6_hdr *ip6;
1215 	struct in6pcb *in6p;
1216 #endif
1217 	u_int8_t *optp = NULL;
1218 	int optlen = 0;
1219 	int len, tlen, toff, hdroptlen = 0;
1220 	struct tcpcb *tp = 0;
1221 	int tiflags;
1222 	struct socket *so = NULL;
1223 	int todrop, acked, ourfinisacked, needoutput = 0;
1224 	bool dupseg;
1225 #ifdef TCP_DEBUG
1226 	short ostate = 0;
1227 #endif
1228 	u_long tiwin;
1229 	struct tcp_opt_info opti;
1230 	int off, iphlen;
1231 	va_list ap;
1232 	int af;		/* af on the wire */
1233 	struct mbuf *tcp_saveti = NULL;
1234 	uint32_t ts_rtt;
1235 	uint8_t iptos;
1236 	uint64_t *tcps;
1237 	vestigial_inpcb_t vestige;
1238 
1239 	vestige.valid = 0;
1240 
1241 	MCLAIM(m, &tcp_rx_mowner);
1242 	va_start(ap, m);
1243 	toff = va_arg(ap, int);
1244 	(void)va_arg(ap, int);		/* ignore value, advance ap */
1245 	va_end(ap);
1246 
1247 	TCP_STATINC(TCP_STAT_RCVTOTAL);
1248 
1249 	memset(&opti, 0, sizeof(opti));
1250 	opti.ts_present = 0;
1251 	opti.maxseg = 0;
1252 
1253 	/*
1254 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
1255 	 *
1256 	 * TCP is, by definition, unicast, so we reject all
1257 	 * multicast outright.
1258 	 *
1259 	 * Note, there are additional src/dst address checks in
1260 	 * the AF-specific code below.
1261 	 */
1262 	if (m->m_flags & (M_BCAST|M_MCAST)) {
1263 		/* XXX stat */
1264 		goto drop;
1265 	}
1266 #ifdef INET6
1267 	if (m->m_flags & M_ANYCAST6) {
1268 		/* XXX stat */
1269 		goto drop;
1270 	}
1271 #endif
1272 
1273 	/*
1274 	 * Get IP and TCP header.
1275 	 * Note: IP leaves IP header in first mbuf.
1276 	 */
1277 	ip = mtod(m, struct ip *);
1278 	switch (ip->ip_v) {
1279 #ifdef INET
1280 	case 4:
1281 #ifdef INET6
1282 		ip6 = NULL;
1283 #endif
1284 		af = AF_INET;
1285 		iphlen = sizeof(struct ip);
1286 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
1287 			sizeof(struct tcphdr));
1288 		if (th == NULL) {
1289 			TCP_STATINC(TCP_STAT_RCVSHORT);
1290 			return;
1291 		}
1292 		/* We do the checksum after PCB lookup... */
1293 		len = ntohs(ip->ip_len);
1294 		tlen = len - toff;
1295 		iptos = ip->ip_tos;
1296 		break;
1297 #endif
1298 #ifdef INET6
1299 	case 6:
1300 		ip = NULL;
1301 		iphlen = sizeof(struct ip6_hdr);
1302 		af = AF_INET6;
1303 		ip6 = mtod(m, struct ip6_hdr *);
1304 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
1305 			sizeof(struct tcphdr));
1306 		if (th == NULL) {
1307 			TCP_STATINC(TCP_STAT_RCVSHORT);
1308 			return;
1309 		}
1310 
1311 		/* Be proactive about malicious use of IPv4 mapped address */
1312 		if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
1313 		    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
1314 			/* XXX stat */
1315 			goto drop;
1316 		}
1317 
1318 		/*
1319 		 * Be proactive about unspecified IPv6 address in source.
1320 		 * As we use all-zero to indicate unbounded/unconnected pcb,
1321 		 * unspecified IPv6 address can be used to confuse us.
1322 		 *
1323 		 * Note that packets with unspecified IPv6 destination is
1324 		 * already dropped in ip6_input.
1325 		 */
1326 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1327 			/* XXX stat */
1328 			goto drop;
1329 		}
1330 
1331 		/*
1332 		 * Make sure destination address is not multicast.
1333 		 * Source address checked in ip6_input().
1334 		 */
1335 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1336 			/* XXX stat */
1337 			goto drop;
1338 		}
1339 
1340 		/* We do the checksum after PCB lookup... */
1341 		len = m->m_pkthdr.len;
1342 		tlen = len - toff;
1343 		iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1344 		break;
1345 #endif
1346 	default:
1347 		m_freem(m);
1348 		return;
1349 	}
1350 
1351 	KASSERT(TCP_HDR_ALIGNED_P(th));
1352 
1353 	/*
1354 	 * Check that TCP offset makes sense,
1355 	 * pull out TCP options and adjust length.		XXX
1356 	 */
1357 	off = th->th_off << 2;
1358 	if (off < sizeof (struct tcphdr) || off > tlen) {
1359 		TCP_STATINC(TCP_STAT_RCVBADOFF);
1360 		goto drop;
1361 	}
1362 	tlen -= off;
1363 
1364 	/*
1365 	 * tcp_input() has been modified to use tlen to mean the TCP data
1366 	 * length throughout the function.  Other functions can use
1367 	 * m->m_pkthdr.len as the basis for calculating the TCP data length.
1368 	 * rja
1369 	 */
1370 
1371 	if (off > sizeof (struct tcphdr)) {
1372 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
1373 		if (th == NULL) {
1374 			TCP_STATINC(TCP_STAT_RCVSHORT);
1375 			return;
1376 		}
1377 		/*
1378 		 * NOTE: ip/ip6 will not be affected by m_pulldown()
1379 		 * (as they're before toff) and we don't need to update those.
1380 		 */
1381 		KASSERT(TCP_HDR_ALIGNED_P(th));
1382 		optlen = off - sizeof (struct tcphdr);
1383 		optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1384 		/*
1385 		 * Do quick retrieval of timestamp options ("options
1386 		 * prediction?").  If timestamp is the only option and it's
1387 		 * formatted as recommended in RFC 1323 appendix A, we
1388 		 * quickly get the values now and not bother calling
1389 		 * tcp_dooptions(), etc.
1390 		 */
1391 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
1392 		     (optlen > TCPOLEN_TSTAMP_APPA &&
1393 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1394 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1395 		     (th->th_flags & TH_SYN) == 0) {
1396 			opti.ts_present = 1;
1397 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1398 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1399 			optp = NULL;	/* we've parsed the options */
1400 		}
1401 	}
1402 	tiflags = th->th_flags;
1403 
1404 	/*
1405 	 * Locate pcb for segment.
1406 	 */
1407 findpcb:
1408 	inp = NULL;
1409 #ifdef INET6
1410 	in6p = NULL;
1411 #endif
1412 	switch (af) {
1413 #ifdef INET
1414 	case AF_INET:
1415 		inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1416 					   ip->ip_dst, th->th_dport,
1417 					   &vestige);
1418 		if (inp == 0 && !vestige.valid) {
1419 			TCP_STATINC(TCP_STAT_PCBHASHMISS);
1420 			inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
1421 		}
1422 #ifdef INET6
1423 		if (inp == 0 && !vestige.valid) {
1424 			struct in6_addr s, d;
1425 
1426 			/* mapped addr case */
1427 			memset(&s, 0, sizeof(s));
1428 			s.s6_addr16[5] = htons(0xffff);
1429 			bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
1430 			memset(&d, 0, sizeof(d));
1431 			d.s6_addr16[5] = htons(0xffff);
1432 			bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
1433 			in6p = in6_pcblookup_connect(&tcbtable, &s,
1434 						     th->th_sport, &d, th->th_dport,
1435 						     0, &vestige);
1436 			if (in6p == 0 && !vestige.valid) {
1437 				TCP_STATINC(TCP_STAT_PCBHASHMISS);
1438 				in6p = in6_pcblookup_bind(&tcbtable, &d,
1439 				    th->th_dport, 0);
1440 			}
1441 		}
1442 #endif
1443 #ifndef INET6
1444 		if (inp == 0 && !vestige.valid)
1445 #else
1446 		if (inp == 0 && in6p == 0 && !vestige.valid)
1447 #endif
1448 		{
1449 			TCP_STATINC(TCP_STAT_NOPORT);
1450 			if (tcp_log_refused &&
1451 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1452 				tcp4_log_refused(ip, th);
1453 			}
1454 			tcp_fields_to_host(th);
1455 			goto dropwithreset_ratelim;
1456 		}
1457 #if defined(IPSEC) || defined(FAST_IPSEC)
1458 		if (inp && (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0 &&
1459 		    ipsec4_in_reject(m, inp)) {
1460 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1461 			goto drop;
1462 		}
1463 #ifdef INET6
1464 		else if (in6p &&
1465 		    (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
1466 		    ipsec6_in_reject_so(m, in6p->in6p_socket)) {
1467 			IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1468 			goto drop;
1469 		}
1470 #endif
1471 #endif /*IPSEC*/
1472 		break;
1473 #endif /*INET*/
1474 #ifdef INET6
1475 	case AF_INET6:
1476 	    {
1477 		int faith;
1478 
1479 #if defined(NFAITH) && NFAITH > 0
1480 		faith = faithprefix(&ip6->ip6_dst);
1481 #else
1482 		faith = 0;
1483 #endif
1484 		in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1485 					     th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
1486 		if (!in6p && !vestige.valid) {
1487 			TCP_STATINC(TCP_STAT_PCBHASHMISS);
1488 			in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1489 				th->th_dport, faith);
1490 		}
1491 		if (!in6p && !vestige.valid) {
1492 			TCP_STATINC(TCP_STAT_NOPORT);
1493 			if (tcp_log_refused &&
1494 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1495 				tcp6_log_refused(ip6, th);
1496 			}
1497 			tcp_fields_to_host(th);
1498 			goto dropwithreset_ratelim;
1499 		}
1500 #if defined(IPSEC) || defined(FAST_IPSEC)
1501 		if (in6p
1502 		    && (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0
1503 		    && ipsec6_in_reject(m, in6p)) {
1504 			IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
1505 			goto drop;
1506 		}
1507 #endif /*IPSEC*/
1508 		break;
1509 	    }
1510 #endif
1511 	}
1512 
1513 	/*
1514 	 * If the state is CLOSED (i.e., TCB does not exist) then
1515 	 * all data in the incoming segment is discarded.
1516 	 * If the TCB exists but is in CLOSED state, it is embryonic,
1517 	 * but should either do a listen or a connect soon.
1518 	 */
1519 	tp = NULL;
1520 	so = NULL;
1521 	if (inp) {
1522 		/* Check the minimum TTL for socket. */
1523 		if (ip->ip_ttl < inp->inp_ip_minttl)
1524 			goto drop;
1525 
1526 		tp = intotcpcb(inp);
1527 		so = inp->inp_socket;
1528 	}
1529 #ifdef INET6
1530 	else if (in6p) {
1531 		tp = in6totcpcb(in6p);
1532 		so = in6p->in6p_socket;
1533 	}
1534 #endif
1535 	else if (vestige.valid) {
1536 		int mc = 0;
1537 
1538 		/* We do not support the resurrection of vtw tcpcps.
1539 		 */
1540 		if (tcp_input_checksum(af, m, th, toff, off, tlen))
1541 			goto badcsum;
1542 
1543 		switch (af) {
1544 #ifdef INET6
1545 		case AF_INET6:
1546 			mc = IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst);
1547 			break;
1548 #endif
1549 
1550 		case AF_INET:
1551 			mc = (IN_MULTICAST(ip->ip_dst.s_addr)
1552 			      || in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif));
1553 			break;
1554 		}
1555 
1556 		tcp_fields_to_host(th);
1557 		tcp_vtw_input(th, &vestige, m, tlen, mc);
1558 		m = 0;
1559 		goto drop;
1560 	}
1561 
1562 	if (tp == 0) {
1563 		tcp_fields_to_host(th);
1564 		goto dropwithreset_ratelim;
1565 	}
1566 	if (tp->t_state == TCPS_CLOSED)
1567 		goto drop;
1568 
1569 	KASSERT(so->so_lock == softnet_lock);
1570 	KASSERT(solocked(so));
1571 
1572 	/*
1573 	 * Checksum extended TCP header and data.
1574 	 */
1575 	if (tcp_input_checksum(af, m, th, toff, off, tlen))
1576 		goto badcsum;
1577 
1578 	tcp_fields_to_host(th);
1579 
1580 	/* Unscale the window into a 32-bit value. */
1581 	if ((tiflags & TH_SYN) == 0)
1582 		tiwin = th->th_win << tp->snd_scale;
1583 	else
1584 		tiwin = th->th_win;
1585 
1586 #ifdef INET6
1587 	/* save packet options if user wanted */
1588 	if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1589 		if (in6p->in6p_options) {
1590 			m_freem(in6p->in6p_options);
1591 			in6p->in6p_options = 0;
1592 		}
1593 		KASSERT(ip6 != NULL);
1594 		ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1595 	}
1596 #endif
1597 
1598 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
1599 		union syn_cache_sa src;
1600 		union syn_cache_sa dst;
1601 
1602 		memset(&src, 0, sizeof(src));
1603 		memset(&dst, 0, sizeof(dst));
1604 		switch (af) {
1605 #ifdef INET
1606 		case AF_INET:
1607 			src.sin.sin_len = sizeof(struct sockaddr_in);
1608 			src.sin.sin_family = AF_INET;
1609 			src.sin.sin_addr = ip->ip_src;
1610 			src.sin.sin_port = th->th_sport;
1611 
1612 			dst.sin.sin_len = sizeof(struct sockaddr_in);
1613 			dst.sin.sin_family = AF_INET;
1614 			dst.sin.sin_addr = ip->ip_dst;
1615 			dst.sin.sin_port = th->th_dport;
1616 			break;
1617 #endif
1618 #ifdef INET6
1619 		case AF_INET6:
1620 			src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1621 			src.sin6.sin6_family = AF_INET6;
1622 			src.sin6.sin6_addr = ip6->ip6_src;
1623 			src.sin6.sin6_port = th->th_sport;
1624 
1625 			dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1626 			dst.sin6.sin6_family = AF_INET6;
1627 			dst.sin6.sin6_addr = ip6->ip6_dst;
1628 			dst.sin6.sin6_port = th->th_dport;
1629 			break;
1630 #endif /* INET6 */
1631 		default:
1632 			goto badsyn;	/*sanity*/
1633 		}
1634 
1635 		if (so->so_options & SO_DEBUG) {
1636 #ifdef TCP_DEBUG
1637 			ostate = tp->t_state;
1638 #endif
1639 
1640 			tcp_saveti = NULL;
1641 			if (iphlen + sizeof(struct tcphdr) > MHLEN)
1642 				goto nosave;
1643 
1644 			if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1645 				tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1646 				if (!tcp_saveti)
1647 					goto nosave;
1648 			} else {
1649 				MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1650 				if (!tcp_saveti)
1651 					goto nosave;
1652 				MCLAIM(m, &tcp_mowner);
1653 				tcp_saveti->m_len = iphlen;
1654 				m_copydata(m, 0, iphlen,
1655 				    mtod(tcp_saveti, void *));
1656 			}
1657 
1658 			if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1659 				m_freem(tcp_saveti);
1660 				tcp_saveti = NULL;
1661 			} else {
1662 				tcp_saveti->m_len += sizeof(struct tcphdr);
1663 				memcpy(mtod(tcp_saveti, char *) + iphlen, th,
1664 				    sizeof(struct tcphdr));
1665 			}
1666 	nosave:;
1667 		}
1668 		if (so->so_options & SO_ACCEPTCONN) {
1669 			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1670 				if (tiflags & TH_RST) {
1671 					syn_cache_reset(&src.sa, &dst.sa, th);
1672 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
1673 				    (TH_ACK|TH_SYN)) {
1674 					/*
1675 					 * Received a SYN,ACK.  This should
1676 					 * never happen while we are in
1677 					 * LISTEN.  Send an RST.
1678 					 */
1679 					goto badsyn;
1680 				} else if (tiflags & TH_ACK) {
1681 					so = syn_cache_get(&src.sa, &dst.sa,
1682 						th, toff, tlen, so, m);
1683 					if (so == NULL) {
1684 						/*
1685 						 * We don't have a SYN for
1686 						 * this ACK; send an RST.
1687 						 */
1688 						goto badsyn;
1689 					} else if (so ==
1690 					    (struct socket *)(-1)) {
1691 						/*
1692 						 * We were unable to create
1693 						 * the connection.  If the
1694 						 * 3-way handshake was
1695 						 * completed, and RST has
1696 						 * been sent to the peer.
1697 						 * Since the mbuf might be
1698 						 * in use for the reply,
1699 						 * do not free it.
1700 						 */
1701 						m = NULL;
1702 					} else {
1703 						/*
1704 						 * We have created a
1705 						 * full-blown connection.
1706 						 */
1707 						tp = NULL;
1708 						inp = NULL;
1709 #ifdef INET6
1710 						in6p = NULL;
1711 #endif
1712 						switch (so->so_proto->pr_domain->dom_family) {
1713 #ifdef INET
1714 						case AF_INET:
1715 							inp = sotoinpcb(so);
1716 							tp = intotcpcb(inp);
1717 							break;
1718 #endif
1719 #ifdef INET6
1720 						case AF_INET6:
1721 							in6p = sotoin6pcb(so);
1722 							tp = in6totcpcb(in6p);
1723 							break;
1724 #endif
1725 						}
1726 						if (tp == NULL)
1727 							goto badsyn;	/*XXX*/
1728 						tiwin <<= tp->snd_scale;
1729 						goto after_listen;
1730 					}
1731 				} else {
1732 					/*
1733 					 * None of RST, SYN or ACK was set.
1734 					 * This is an invalid packet for a
1735 					 * TCB in LISTEN state.  Send a RST.
1736 					 */
1737 					goto badsyn;
1738 				}
1739 			} else {
1740 				/*
1741 				 * Received a SYN.
1742 				 *
1743 				 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1744 				 */
1745 				if (m->m_flags & (M_BCAST|M_MCAST))
1746 					goto drop;
1747 
1748 				switch (af) {
1749 #ifdef INET6
1750 				case AF_INET6:
1751 					if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1752 						goto drop;
1753 					break;
1754 #endif /* INET6 */
1755 				case AF_INET:
1756 					if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1757 					    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1758 						goto drop;
1759 				break;
1760 				}
1761 
1762 #ifdef INET6
1763 				/*
1764 				 * If deprecated address is forbidden, we do
1765 				 * not accept SYN to deprecated interface
1766 				 * address to prevent any new inbound
1767 				 * connection from getting established.
1768 				 * When we do not accept SYN, we send a TCP
1769 				 * RST, with deprecated source address (instead
1770 				 * of dropping it).  We compromise it as it is
1771 				 * much better for peer to send a RST, and
1772 				 * RST will be the final packet for the
1773 				 * exchange.
1774 				 *
1775 				 * If we do not forbid deprecated addresses, we
1776 				 * accept the SYN packet.  RFC2462 does not
1777 				 * suggest dropping SYN in this case.
1778 				 * If we decipher RFC2462 5.5.4, it says like
1779 				 * this:
1780 				 * 1. use of deprecated addr with existing
1781 				 *    communication is okay - "SHOULD continue
1782 				 *    to be used"
1783 				 * 2. use of it with new communication:
1784 				 *   (2a) "SHOULD NOT be used if alternate
1785 				 *        address with sufficient scope is
1786 				 *        available"
1787 				 *   (2b) nothing mentioned otherwise.
1788 				 * Here we fall into (2b) case as we have no
1789 				 * choice in our source address selection - we
1790 				 * must obey the peer.
1791 				 *
1792 				 * The wording in RFC2462 is confusing, and
1793 				 * there are multiple description text for
1794 				 * deprecated address handling - worse, they
1795 				 * are not exactly the same.  I believe 5.5.4
1796 				 * is the best one, so we follow 5.5.4.
1797 				 */
1798 				if (af == AF_INET6 && !ip6_use_deprecated) {
1799 					struct in6_ifaddr *ia6;
1800 					if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif,
1801 					    &ip6->ip6_dst)) &&
1802 					    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1803 						tp = NULL;
1804 						goto dropwithreset;
1805 					}
1806 				}
1807 #endif
1808 
1809 #if defined(IPSEC) || defined(FAST_IPSEC)
1810 				switch (af) {
1811 #ifdef INET
1812 				case AF_INET:
1813 					if (ipsec4_in_reject_so(m, so)) {
1814 						IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1815 						tp = NULL;
1816 						goto dropwithreset;
1817 					}
1818 					break;
1819 #endif
1820 #ifdef INET6
1821 				case AF_INET6:
1822 					if (ipsec6_in_reject_so(m, so)) {
1823 						IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
1824 						tp = NULL;
1825 						goto dropwithreset;
1826 					}
1827 					break;
1828 #endif /*INET6*/
1829 				}
1830 #endif /*IPSEC*/
1831 
1832 				/*
1833 				 * LISTEN socket received a SYN
1834 				 * from itself?  This can't possibly
1835 				 * be valid; drop the packet.
1836 				 */
1837 				if (th->th_sport == th->th_dport) {
1838 					int i;
1839 
1840 					switch (af) {
1841 #ifdef INET
1842 					case AF_INET:
1843 						i = in_hosteq(ip->ip_src, ip->ip_dst);
1844 						break;
1845 #endif
1846 #ifdef INET6
1847 					case AF_INET6:
1848 						i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1849 						break;
1850 #endif
1851 					default:
1852 						i = 1;
1853 					}
1854 					if (i) {
1855 						TCP_STATINC(TCP_STAT_BADSYN);
1856 						goto drop;
1857 					}
1858 				}
1859 
1860 				/*
1861 				 * SYN looks ok; create compressed TCP
1862 				 * state for it.
1863 				 */
1864 				if (so->so_qlen <= so->so_qlimit &&
1865 				    syn_cache_add(&src.sa, &dst.sa, th, tlen,
1866 						so, m, optp, optlen, &opti))
1867 					m = NULL;
1868 			}
1869 			goto drop;
1870 		}
1871 	}
1872 
1873 after_listen:
1874 #ifdef DIAGNOSTIC
1875 	/*
1876 	 * Should not happen now that all embryonic connections
1877 	 * are handled with compressed state.
1878 	 */
1879 	if (tp->t_state == TCPS_LISTEN)
1880 		panic("tcp_input: TCPS_LISTEN");
1881 #endif
1882 
1883 	/*
1884 	 * Segment received on connection.
1885 	 * Reset idle time and keep-alive timer.
1886 	 */
1887 	tp->t_rcvtime = tcp_now;
1888 	if (TCPS_HAVEESTABLISHED(tp->t_state))
1889 		TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
1890 
1891 	/*
1892 	 * Process options.
1893 	 */
1894 #ifdef TCP_SIGNATURE
1895 	if (optp || (tp->t_flags & TF_SIGNATURE))
1896 #else
1897 	if (optp)
1898 #endif
1899 		if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1900 			goto drop;
1901 
1902 	if (TCP_SACK_ENABLED(tp)) {
1903 		tcp_del_sackholes(tp, th);
1904 	}
1905 
1906 	if (TCP_ECN_ALLOWED(tp)) {
1907 		if (tiflags & TH_CWR) {
1908 			tp->t_flags &= ~TF_ECN_SND_ECE;
1909 		}
1910 		switch (iptos & IPTOS_ECN_MASK) {
1911 		case IPTOS_ECN_CE:
1912 			tp->t_flags |= TF_ECN_SND_ECE;
1913 			TCP_STATINC(TCP_STAT_ECN_CE);
1914 			break;
1915 		case IPTOS_ECN_ECT0:
1916 			TCP_STATINC(TCP_STAT_ECN_ECT);
1917 			break;
1918 		case IPTOS_ECN_ECT1:
1919 			/* XXX: ignore for now -- rpaulo */
1920 			break;
1921 		}
1922 		/*
1923 		 * Congestion experienced.
1924 		 * Ignore if we are already trying to recover.
1925 		 */
1926 		if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
1927 			tp->t_congctl->cong_exp(tp);
1928 	}
1929 
1930 	if (opti.ts_present && opti.ts_ecr) {
1931 		/*
1932 		 * Calculate the RTT from the returned time stamp and the
1933 		 * connection's time base.  If the time stamp is later than
1934 		 * the current time, or is extremely old, fall back to non-1323
1935 		 * RTT calculation.  Since ts_rtt is unsigned, we can test both
1936 		 * at the same time.
1937 		 *
1938 		 * Note that ts_rtt is in units of slow ticks (500
1939 		 * ms).  Since most earthbound RTTs are < 500 ms,
1940 		 * observed values will have large quantization noise.
1941 		 * Our smoothed RTT is then the fraction of observed
1942 		 * samples that are 1 tick instead of 0 (times 500
1943 		 * ms).
1944 		 *
1945 		 * ts_rtt is increased by 1 to denote a valid sample,
1946 		 * with 0 indicating an invalid measurement.  This
1947 		 * extra 1 must be removed when ts_rtt is used, or
1948 		 * else an an erroneous extra 500 ms will result.
1949 		 */
1950 		ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1951 		if (ts_rtt > TCP_PAWS_IDLE)
1952 			ts_rtt = 0;
1953 	} else {
1954 		ts_rtt = 0;
1955 	}
1956 
1957 	/*
1958 	 * Header prediction: check for the two common cases
1959 	 * of a uni-directional data xfer.  If the packet has
1960 	 * no control flags, is in-sequence, the window didn't
1961 	 * change and we're not retransmitting, it's a
1962 	 * candidate.  If the length is zero and the ack moved
1963 	 * forward, we're the sender side of the xfer.  Just
1964 	 * free the data acked & wake any higher level process
1965 	 * that was blocked waiting for space.  If the length
1966 	 * is non-zero and the ack didn't move, we're the
1967 	 * receiver side.  If we're getting packets in-order
1968 	 * (the reassembly queue is empty), add the data to
1969 	 * the socket buffer and note that we need a delayed ack.
1970 	 */
1971 	if (tp->t_state == TCPS_ESTABLISHED &&
1972 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
1973 	        == TH_ACK &&
1974 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1975 	    th->th_seq == tp->rcv_nxt &&
1976 	    tiwin && tiwin == tp->snd_wnd &&
1977 	    tp->snd_nxt == tp->snd_max) {
1978 
1979 		/*
1980 		 * If last ACK falls within this segment's sequence numbers,
1981 		 * record the timestamp.
1982 		 * NOTE that the test is modified according to the latest
1983 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1984 		 *
1985 		 * note that we already know
1986 		 *	TSTMP_GEQ(opti.ts_val, tp->ts_recent)
1987 		 */
1988 		if (opti.ts_present &&
1989 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1990 			tp->ts_recent_age = tcp_now;
1991 			tp->ts_recent = opti.ts_val;
1992 		}
1993 
1994 		if (tlen == 0) {
1995 			/* Ack prediction. */
1996 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1997 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1998 			    tp->snd_cwnd >= tp->snd_wnd &&
1999 			    tp->t_partialacks < 0) {
2000 				/*
2001 				 * this is a pure ack for outstanding data.
2002 				 */
2003 				if (ts_rtt)
2004 					tcp_xmit_timer(tp, ts_rtt - 1);
2005 				else if (tp->t_rtttime &&
2006 				    SEQ_GT(th->th_ack, tp->t_rtseq))
2007 					tcp_xmit_timer(tp,
2008 					  tcp_now - tp->t_rtttime);
2009 				acked = th->th_ack - tp->snd_una;
2010 				tcps = TCP_STAT_GETREF();
2011 				tcps[TCP_STAT_PREDACK]++;
2012 				tcps[TCP_STAT_RCVACKPACK]++;
2013 				tcps[TCP_STAT_RCVACKBYTE] += acked;
2014 				TCP_STAT_PUTREF();
2015 				nd6_hint(tp);
2016 
2017 				if (acked > (tp->t_lastoff - tp->t_inoff))
2018 					tp->t_lastm = NULL;
2019 				sbdrop(&so->so_snd, acked);
2020 				tp->t_lastoff -= acked;
2021 
2022 				icmp_check(tp, th, acked);
2023 
2024 				tp->snd_una = th->th_ack;
2025 				tp->snd_fack = tp->snd_una;
2026 				if (SEQ_LT(tp->snd_high, tp->snd_una))
2027 					tp->snd_high = tp->snd_una;
2028 				m_freem(m);
2029 
2030 				/*
2031 				 * If all outstanding data are acked, stop
2032 				 * retransmit timer, otherwise restart timer
2033 				 * using current (possibly backed-off) value.
2034 				 * If process is waiting for space,
2035 				 * wakeup/selnotify/signal.  If data
2036 				 * are ready to send, let tcp_output
2037 				 * decide between more output or persist.
2038 				 */
2039 				if (tp->snd_una == tp->snd_max)
2040 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
2041 				else if (TCP_TIMER_ISARMED(tp,
2042 				    TCPT_PERSIST) == 0)
2043 					TCP_TIMER_ARM(tp, TCPT_REXMT,
2044 					    tp->t_rxtcur);
2045 
2046 				sowwakeup(so);
2047 				if (so->so_snd.sb_cc) {
2048 					KERNEL_LOCK(1, NULL);
2049 					(void) tcp_output(tp);
2050 					KERNEL_UNLOCK_ONE(NULL);
2051 				}
2052 				if (tcp_saveti)
2053 					m_freem(tcp_saveti);
2054 				return;
2055 			}
2056 		} else if (th->th_ack == tp->snd_una &&
2057 		    TAILQ_FIRST(&tp->segq) == NULL &&
2058 		    tlen <= sbspace(&so->so_rcv)) {
2059 			int newsize = 0;	/* automatic sockbuf scaling */
2060 
2061 			/*
2062 			 * this is a pure, in-sequence data packet
2063 			 * with nothing on the reassembly queue and
2064 			 * we have enough buffer space to take it.
2065 			 */
2066 			tp->rcv_nxt += tlen;
2067 			tcps = TCP_STAT_GETREF();
2068 			tcps[TCP_STAT_PREDDAT]++;
2069 			tcps[TCP_STAT_RCVPACK]++;
2070 			tcps[TCP_STAT_RCVBYTE] += tlen;
2071 			TCP_STAT_PUTREF();
2072 			nd6_hint(tp);
2073 
2074 		/*
2075 		 * Automatic sizing enables the performance of large buffers
2076 		 * and most of the efficiency of small ones by only allocating
2077 		 * space when it is needed.
2078 		 *
2079 		 * On the receive side the socket buffer memory is only rarely
2080 		 * used to any significant extent.  This allows us to be much
2081 		 * more aggressive in scaling the receive socket buffer.  For
2082 		 * the case that the buffer space is actually used to a large
2083 		 * extent and we run out of kernel memory we can simply drop
2084 		 * the new segments; TCP on the sender will just retransmit it
2085 		 * later.  Setting the buffer size too big may only consume too
2086 		 * much kernel memory if the application doesn't read() from
2087 		 * the socket or packet loss or reordering makes use of the
2088 		 * reassembly queue.
2089 		 *
2090 		 * The criteria to step up the receive buffer one notch are:
2091 		 *  1. the number of bytes received during the time it takes
2092 		 *     one timestamp to be reflected back to us (the RTT);
2093 		 *  2. received bytes per RTT is within seven eighth of the
2094 		 *     current socket buffer size;
2095 		 *  3. receive buffer size has not hit maximal automatic size;
2096 		 *
2097 		 * This algorithm does one step per RTT at most and only if
2098 		 * we receive a bulk stream w/o packet losses or reorderings.
2099 		 * Shrinking the buffer during idle times is not necessary as
2100 		 * it doesn't consume any memory when idle.
2101 		 *
2102 		 * TODO: Only step up if the application is actually serving
2103 		 * the buffer to better manage the socket buffer resources.
2104 		 */
2105 			if (tcp_do_autorcvbuf &&
2106 			    opti.ts_ecr &&
2107 			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
2108 				if (opti.ts_ecr > tp->rfbuf_ts &&
2109 				    opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
2110 					if (tp->rfbuf_cnt >
2111 					    (so->so_rcv.sb_hiwat / 8 * 7) &&
2112 					    so->so_rcv.sb_hiwat <
2113 					    tcp_autorcvbuf_max) {
2114 						newsize =
2115 						    min(so->so_rcv.sb_hiwat +
2116 						    tcp_autorcvbuf_inc,
2117 						    tcp_autorcvbuf_max);
2118 					}
2119 					/* Start over with next RTT. */
2120 					tp->rfbuf_ts = 0;
2121 					tp->rfbuf_cnt = 0;
2122 				} else
2123 					tp->rfbuf_cnt += tlen;	/* add up */
2124 			}
2125 
2126 			/*
2127 			 * Drop TCP, IP headers and TCP options then add data
2128 			 * to socket buffer.
2129 			 */
2130 			if (so->so_state & SS_CANTRCVMORE)
2131 				m_freem(m);
2132 			else {
2133 				/*
2134 				 * Set new socket buffer size.
2135 				 * Give up when limit is reached.
2136 				 */
2137 				if (newsize)
2138 					if (!sbreserve(&so->so_rcv,
2139 					    newsize, so))
2140 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
2141 				m_adj(m, toff + off);
2142 				sbappendstream(&so->so_rcv, m);
2143 			}
2144 			sorwakeup(so);
2145 			tcp_setup_ack(tp, th);
2146 			if (tp->t_flags & TF_ACKNOW) {
2147 				KERNEL_LOCK(1, NULL);
2148 				(void) tcp_output(tp);
2149 				KERNEL_UNLOCK_ONE(NULL);
2150 			}
2151 			if (tcp_saveti)
2152 				m_freem(tcp_saveti);
2153 			return;
2154 		}
2155 	}
2156 
2157 	/*
2158 	 * Compute mbuf offset to TCP data segment.
2159 	 */
2160 	hdroptlen = toff + off;
2161 
2162 	/*
2163 	 * Calculate amount of space in receive window,
2164 	 * and then do TCP input processing.
2165 	 * Receive window is amount of space in rcv queue,
2166 	 * but not less than advertised window.
2167 	 */
2168 	{ int win;
2169 
2170 	win = sbspace(&so->so_rcv);
2171 	if (win < 0)
2172 		win = 0;
2173 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
2174 	}
2175 
2176 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
2177 	tp->rfbuf_ts = 0;
2178 	tp->rfbuf_cnt = 0;
2179 
2180 	switch (tp->t_state) {
2181 	/*
2182 	 * If the state is SYN_SENT:
2183 	 *	if seg contains an ACK, but not for our SYN, drop the input.
2184 	 *	if seg contains a RST, then drop the connection.
2185 	 *	if seg does not contain SYN, then drop it.
2186 	 * Otherwise this is an acceptable SYN segment
2187 	 *	initialize tp->rcv_nxt and tp->irs
2188 	 *	if seg contains ack then advance tp->snd_una
2189 	 *	if seg contains a ECE and ECN support is enabled, the stream
2190 	 *	    is ECN capable.
2191 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2192 	 *	arrange for segment to be acked (eventually)
2193 	 *	continue processing rest of data/controls, beginning with URG
2194 	 */
2195 	case TCPS_SYN_SENT:
2196 		if ((tiflags & TH_ACK) &&
2197 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
2198 		     SEQ_GT(th->th_ack, tp->snd_max)))
2199 			goto dropwithreset;
2200 		if (tiflags & TH_RST) {
2201 			if (tiflags & TH_ACK)
2202 				tp = tcp_drop(tp, ECONNREFUSED);
2203 			goto drop;
2204 		}
2205 		if ((tiflags & TH_SYN) == 0)
2206 			goto drop;
2207 		if (tiflags & TH_ACK) {
2208 			tp->snd_una = th->th_ack;
2209 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2210 				tp->snd_nxt = tp->snd_una;
2211 			if (SEQ_LT(tp->snd_high, tp->snd_una))
2212 				tp->snd_high = tp->snd_una;
2213 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
2214 
2215 			if ((tiflags & TH_ECE) && tcp_do_ecn) {
2216 				tp->t_flags |= TF_ECN_PERMIT;
2217 				TCP_STATINC(TCP_STAT_ECN_SHS);
2218 			}
2219 
2220 		}
2221 		tp->irs = th->th_seq;
2222 		tcp_rcvseqinit(tp);
2223 		tp->t_flags |= TF_ACKNOW;
2224 		tcp_mss_from_peer(tp, opti.maxseg);
2225 
2226 		/*
2227 		 * Initialize the initial congestion window.  If we
2228 		 * had to retransmit the SYN, we must initialize cwnd
2229 		 * to 1 segment (i.e. the Loss Window).
2230 		 */
2231 		if (tp->t_flags & TF_SYN_REXMT)
2232 			tp->snd_cwnd = tp->t_peermss;
2233 		else {
2234 			int ss = tcp_init_win;
2235 #ifdef INET
2236 			if (inp != NULL && in_localaddr(inp->inp_faddr))
2237 				ss = tcp_init_win_local;
2238 #endif
2239 #ifdef INET6
2240 			if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
2241 				ss = tcp_init_win_local;
2242 #endif
2243 			tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
2244 		}
2245 
2246 		tcp_rmx_rtt(tp);
2247 		if (tiflags & TH_ACK) {
2248 			TCP_STATINC(TCP_STAT_CONNECTS);
2249 			/*
2250 			 * move tcp_established before soisconnected
2251 			 * because upcall handler can drive tcp_output
2252 			 * functionality.
2253 			 * XXX we might call soisconnected at the end of
2254 			 * all processing
2255 			 */
2256 			tcp_established(tp);
2257 			soisconnected(so);
2258 			/* Do window scaling on this connection? */
2259 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2260 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2261 				tp->snd_scale = tp->requested_s_scale;
2262 				tp->rcv_scale = tp->request_r_scale;
2263 			}
2264 			TCP_REASS_LOCK(tp);
2265 			(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
2266 			/*
2267 			 * if we didn't have to retransmit the SYN,
2268 			 * use its rtt as our initial srtt & rtt var.
2269 			 */
2270 			if (tp->t_rtttime)
2271 				tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2272 		} else
2273 			tp->t_state = TCPS_SYN_RECEIVED;
2274 
2275 		/*
2276 		 * Advance th->th_seq to correspond to first data byte.
2277 		 * If data, trim to stay within window,
2278 		 * dropping FIN if necessary.
2279 		 */
2280 		th->th_seq++;
2281 		if (tlen > tp->rcv_wnd) {
2282 			todrop = tlen - tp->rcv_wnd;
2283 			m_adj(m, -todrop);
2284 			tlen = tp->rcv_wnd;
2285 			tiflags &= ~TH_FIN;
2286 			tcps = TCP_STAT_GETREF();
2287 			tcps[TCP_STAT_RCVPACKAFTERWIN]++;
2288 			tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
2289 			TCP_STAT_PUTREF();
2290 		}
2291 		tp->snd_wl1 = th->th_seq - 1;
2292 		tp->rcv_up = th->th_seq;
2293 		goto step6;
2294 
2295 	/*
2296 	 * If the state is SYN_RECEIVED:
2297 	 *	If seg contains an ACK, but not for our SYN, drop the input
2298 	 *	and generate an RST.  See page 36, rfc793
2299 	 */
2300 	case TCPS_SYN_RECEIVED:
2301 		if ((tiflags & TH_ACK) &&
2302 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
2303 		     SEQ_GT(th->th_ack, tp->snd_max)))
2304 			goto dropwithreset;
2305 		break;
2306 	}
2307 
2308 	/*
2309 	 * States other than LISTEN or SYN_SENT.
2310 	 * First check timestamp, if present.
2311 	 * Then check that at least some bytes of segment are within
2312 	 * receive window.  If segment begins before rcv_nxt,
2313 	 * drop leading data (and SYN); if nothing left, just ack.
2314 	 *
2315 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2316 	 * and it's less than ts_recent, drop it.
2317 	 */
2318 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
2319 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
2320 
2321 		/* Check to see if ts_recent is over 24 days old.  */
2322 		if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
2323 			/*
2324 			 * Invalidate ts_recent.  If this segment updates
2325 			 * ts_recent, the age will be reset later and ts_recent
2326 			 * will get a valid value.  If it does not, setting
2327 			 * ts_recent to zero will at least satisfy the
2328 			 * requirement that zero be placed in the timestamp
2329 			 * echo reply when ts_recent isn't valid.  The
2330 			 * age isn't reset until we get a valid ts_recent
2331 			 * because we don't want out-of-order segments to be
2332 			 * dropped when ts_recent is old.
2333 			 */
2334 			tp->ts_recent = 0;
2335 		} else {
2336 			tcps = TCP_STAT_GETREF();
2337 			tcps[TCP_STAT_RCVDUPPACK]++;
2338 			tcps[TCP_STAT_RCVDUPBYTE] += tlen;
2339 			tcps[TCP_STAT_PAWSDROP]++;
2340 			TCP_STAT_PUTREF();
2341 			tcp_new_dsack(tp, th->th_seq, tlen);
2342 			goto dropafterack;
2343 		}
2344 	}
2345 
2346 	todrop = tp->rcv_nxt - th->th_seq;
2347 	dupseg = false;
2348 	if (todrop > 0) {
2349 		if (tiflags & TH_SYN) {
2350 			tiflags &= ~TH_SYN;
2351 			th->th_seq++;
2352 			if (th->th_urp > 1)
2353 				th->th_urp--;
2354 			else {
2355 				tiflags &= ~TH_URG;
2356 				th->th_urp = 0;
2357 			}
2358 			todrop--;
2359 		}
2360 		if (todrop > tlen ||
2361 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
2362 			/*
2363 			 * Any valid FIN or RST must be to the left of the
2364 			 * window.  At this point the FIN or RST must be a
2365 			 * duplicate or out of sequence; drop it.
2366 			 */
2367 			if (tiflags & TH_RST)
2368 				goto drop;
2369 			tiflags &= ~(TH_FIN|TH_RST);
2370 			/*
2371 			 * Send an ACK to resynchronize and drop any data.
2372 			 * But keep on processing for RST or ACK.
2373 			 */
2374 			tp->t_flags |= TF_ACKNOW;
2375 			todrop = tlen;
2376 			dupseg = true;
2377 			tcps = TCP_STAT_GETREF();
2378 			tcps[TCP_STAT_RCVDUPPACK]++;
2379 			tcps[TCP_STAT_RCVDUPBYTE] += todrop;
2380 			TCP_STAT_PUTREF();
2381 		} else if ((tiflags & TH_RST) &&
2382 			   th->th_seq != tp->rcv_nxt) {
2383 			/*
2384 			 * Test for reset before adjusting the sequence
2385 			 * number for overlapping data.
2386 			 */
2387 			goto dropafterack_ratelim;
2388 		} else {
2389 			tcps = TCP_STAT_GETREF();
2390 			tcps[TCP_STAT_RCVPARTDUPPACK]++;
2391 			tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
2392 			TCP_STAT_PUTREF();
2393 		}
2394 		tcp_new_dsack(tp, th->th_seq, todrop);
2395 		hdroptlen += todrop;	/*drop from head afterwards*/
2396 		th->th_seq += todrop;
2397 		tlen -= todrop;
2398 		if (th->th_urp > todrop)
2399 			th->th_urp -= todrop;
2400 		else {
2401 			tiflags &= ~TH_URG;
2402 			th->th_urp = 0;
2403 		}
2404 	}
2405 
2406 	/*
2407 	 * If new data are received on a connection after the
2408 	 * user processes are gone, then RST the other end.
2409 	 */
2410 	if ((so->so_state & SS_NOFDREF) &&
2411 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2412 		tp = tcp_close(tp);
2413 		TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
2414 		goto dropwithreset;
2415 	}
2416 
2417 	/*
2418 	 * If segment ends after window, drop trailing data
2419 	 * (and PUSH and FIN); if nothing left, just ACK.
2420 	 */
2421 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
2422 	if (todrop > 0) {
2423 		TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
2424 		if (todrop >= tlen) {
2425 			/*
2426 			 * The segment actually starts after the window.
2427 			 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2428 			 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2429 			 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2430 			 */
2431 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
2432 			/*
2433 			 * If a new connection request is received
2434 			 * while in TIME_WAIT, drop the old connection
2435 			 * and start over if the sequence numbers
2436 			 * are above the previous ones.
2437 			 *
2438 			 * NOTE: We will checksum the packet again, and
2439 			 * so we need to put the header fields back into
2440 			 * network order!
2441 			 * XXX This kind of sucks, but we don't expect
2442 			 * XXX this to happen very often, so maybe it
2443 			 * XXX doesn't matter so much.
2444 			 */
2445 			if (tiflags & TH_SYN &&
2446 			    tp->t_state == TCPS_TIME_WAIT &&
2447 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2448 				tp = tcp_close(tp);
2449 				tcp_fields_to_net(th);
2450 				goto findpcb;
2451 			}
2452 			/*
2453 			 * If window is closed can only take segments at
2454 			 * window edge, and have to drop data and PUSH from
2455 			 * incoming segments.  Continue processing, but
2456 			 * remember to ack.  Otherwise, drop segment
2457 			 * and (if not RST) ack.
2458 			 */
2459 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2460 				tp->t_flags |= TF_ACKNOW;
2461 				TCP_STATINC(TCP_STAT_RCVWINPROBE);
2462 			} else
2463 				goto dropafterack;
2464 		} else
2465 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
2466 		m_adj(m, -todrop);
2467 		tlen -= todrop;
2468 		tiflags &= ~(TH_PUSH|TH_FIN);
2469 	}
2470 
2471 	/*
2472 	 * If last ACK falls within this segment's sequence numbers,
2473 	 *  record the timestamp.
2474 	 * NOTE:
2475 	 * 1) That the test incorporates suggestions from the latest
2476 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
2477 	 * 2) That updating only on newer timestamps interferes with
2478 	 *    our earlier PAWS tests, so this check should be solely
2479 	 *    predicated on the sequence space of this segment.
2480 	 * 3) That we modify the segment boundary check to be
2481 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
2482 	 *    instead of RFC1323's
2483 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
2484 	 *    This modified check allows us to overcome RFC1323's
2485 	 *    limitations as described in Stevens TCP/IP Illustrated
2486 	 *    Vol. 2 p.869. In such cases, we can still calculate the
2487 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
2488 	 */
2489 	if (opti.ts_present &&
2490 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2491 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2492 		    ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2493 		tp->ts_recent_age = tcp_now;
2494 		tp->ts_recent = opti.ts_val;
2495 	}
2496 
2497 	/*
2498 	 * If the RST bit is set examine the state:
2499 	 *    SYN_RECEIVED STATE:
2500 	 *	If passive open, return to LISTEN state.
2501 	 *	If active open, inform user that connection was refused.
2502 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
2503 	 *	Inform user that connection was reset, and close tcb.
2504 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
2505 	 *	Close the tcb.
2506 	 */
2507 	if (tiflags & TH_RST) {
2508 		if (th->th_seq != tp->rcv_nxt)
2509 			goto dropafterack_ratelim;
2510 
2511 		switch (tp->t_state) {
2512 		case TCPS_SYN_RECEIVED:
2513 			so->so_error = ECONNREFUSED;
2514 			goto close;
2515 
2516 		case TCPS_ESTABLISHED:
2517 		case TCPS_FIN_WAIT_1:
2518 		case TCPS_FIN_WAIT_2:
2519 		case TCPS_CLOSE_WAIT:
2520 			so->so_error = ECONNRESET;
2521 		close:
2522 			tp->t_state = TCPS_CLOSED;
2523 			TCP_STATINC(TCP_STAT_DROPS);
2524 			tp = tcp_close(tp);
2525 			goto drop;
2526 
2527 		case TCPS_CLOSING:
2528 		case TCPS_LAST_ACK:
2529 		case TCPS_TIME_WAIT:
2530 			tp = tcp_close(tp);
2531 			goto drop;
2532 		}
2533 	}
2534 
2535 	/*
2536 	 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2537 	 * we must be in a synchronized state.  RFC791 states (under RST
2538 	 * generation) that any unacceptable segment (an out-of-order SYN
2539 	 * qualifies) received in a synchronized state must elicit only an
2540 	 * empty acknowledgment segment ... and the connection remains in
2541 	 * the same state.
2542 	 */
2543 	if (tiflags & TH_SYN) {
2544 		if (tp->rcv_nxt == th->th_seq) {
2545 			tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2546 			    TH_ACK);
2547 			if (tcp_saveti)
2548 				m_freem(tcp_saveti);
2549 			return;
2550 		}
2551 
2552 		goto dropafterack_ratelim;
2553 	}
2554 
2555 	/*
2556 	 * If the ACK bit is off we drop the segment and return.
2557 	 */
2558 	if ((tiflags & TH_ACK) == 0) {
2559 		if (tp->t_flags & TF_ACKNOW)
2560 			goto dropafterack;
2561 		else
2562 			goto drop;
2563 	}
2564 
2565 	/*
2566 	 * Ack processing.
2567 	 */
2568 	switch (tp->t_state) {
2569 
2570 	/*
2571 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2572 	 * ESTABLISHED state and continue processing, otherwise
2573 	 * send an RST.
2574 	 */
2575 	case TCPS_SYN_RECEIVED:
2576 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
2577 		    SEQ_GT(th->th_ack, tp->snd_max))
2578 			goto dropwithreset;
2579 		TCP_STATINC(TCP_STAT_CONNECTS);
2580 		soisconnected(so);
2581 		tcp_established(tp);
2582 		/* Do window scaling? */
2583 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2584 		    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2585 			tp->snd_scale = tp->requested_s_scale;
2586 			tp->rcv_scale = tp->request_r_scale;
2587 		}
2588 		TCP_REASS_LOCK(tp);
2589 		(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
2590 		tp->snd_wl1 = th->th_seq - 1;
2591 		/* fall into ... */
2592 
2593 	/*
2594 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2595 	 * ACKs.  If the ack is in the range
2596 	 *	tp->snd_una < th->th_ack <= tp->snd_max
2597 	 * then advance tp->snd_una to th->th_ack and drop
2598 	 * data from the retransmission queue.  If this ACK reflects
2599 	 * more up to date window information we update our window information.
2600 	 */
2601 	case TCPS_ESTABLISHED:
2602 	case TCPS_FIN_WAIT_1:
2603 	case TCPS_FIN_WAIT_2:
2604 	case TCPS_CLOSE_WAIT:
2605 	case TCPS_CLOSING:
2606 	case TCPS_LAST_ACK:
2607 	case TCPS_TIME_WAIT:
2608 
2609 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2610 			if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2611 				TCP_STATINC(TCP_STAT_RCVDUPACK);
2612 				/*
2613 				 * If we have outstanding data (other than
2614 				 * a window probe), this is a completely
2615 				 * duplicate ack (ie, window info didn't
2616 				 * change), the ack is the biggest we've
2617 				 * seen and we've seen exactly our rexmt
2618 				 * threshhold of them, assume a packet
2619 				 * has been dropped and retransmit it.
2620 				 * Kludge snd_nxt & the congestion
2621 				 * window so we send only this one
2622 				 * packet.
2623 				 */
2624 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2625 				    th->th_ack != tp->snd_una)
2626 					tp->t_dupacks = 0;
2627 				else if (tp->t_partialacks < 0 &&
2628 					 (++tp->t_dupacks == tcprexmtthresh ||
2629 					 TCP_FACK_FASTRECOV(tp))) {
2630 					/*
2631 					 * Do the fast retransmit, and adjust
2632 					 * congestion control paramenters.
2633 					 */
2634 					if (tp->t_congctl->fast_retransmit(tp, th)) {
2635 						/* False fast retransmit */
2636 						break;
2637 					} else
2638 						goto drop;
2639 				} else if (tp->t_dupacks > tcprexmtthresh) {
2640 					tp->snd_cwnd += tp->t_segsz;
2641 					KERNEL_LOCK(1, NULL);
2642 					(void) tcp_output(tp);
2643 					KERNEL_UNLOCK_ONE(NULL);
2644 					goto drop;
2645 				}
2646 			} else {
2647 				/*
2648 				 * If the ack appears to be very old, only
2649 				 * allow data that is in-sequence.  This
2650 				 * makes it somewhat more difficult to insert
2651 				 * forged data by guessing sequence numbers.
2652 				 * Sent an ack to try to update the send
2653 				 * sequence number on the other side.
2654 				 */
2655 				if (tlen && th->th_seq != tp->rcv_nxt &&
2656 				    SEQ_LT(th->th_ack,
2657 				    tp->snd_una - tp->max_sndwnd))
2658 					goto dropafterack;
2659 			}
2660 			break;
2661 		}
2662 		/*
2663 		 * If the congestion window was inflated to account
2664 		 * for the other side's cached packets, retract it.
2665 		 */
2666 		/* XXX: make SACK have his own congestion control
2667 		 * struct -- rpaulo */
2668 		if (TCP_SACK_ENABLED(tp))
2669 			tcp_sack_newack(tp, th);
2670 		else
2671 			tp->t_congctl->fast_retransmit_newack(tp, th);
2672 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
2673 			TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
2674 			goto dropafterack;
2675 		}
2676 		acked = th->th_ack - tp->snd_una;
2677 		tcps = TCP_STAT_GETREF();
2678 		tcps[TCP_STAT_RCVACKPACK]++;
2679 		tcps[TCP_STAT_RCVACKBYTE] += acked;
2680 		TCP_STAT_PUTREF();
2681 
2682 		/*
2683 		 * If we have a timestamp reply, update smoothed
2684 		 * round trip time.  If no timestamp is present but
2685 		 * transmit timer is running and timed sequence
2686 		 * number was acked, update smoothed round trip time.
2687 		 * Since we now have an rtt measurement, cancel the
2688 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2689 		 * Recompute the initial retransmit timer.
2690 		 */
2691 		if (ts_rtt)
2692 			tcp_xmit_timer(tp, ts_rtt - 1);
2693 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2694 			tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2695 
2696 		/*
2697 		 * If all outstanding data is acked, stop retransmit
2698 		 * timer and remember to restart (more output or persist).
2699 		 * If there is more data to be acked, restart retransmit
2700 		 * timer, using current (possibly backed-off) value.
2701 		 */
2702 		if (th->th_ack == tp->snd_max) {
2703 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
2704 			needoutput = 1;
2705 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2706 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2707 
2708 		/*
2709 		 * New data has been acked, adjust the congestion window.
2710 		 */
2711 		tp->t_congctl->newack(tp, th);
2712 
2713 		nd6_hint(tp);
2714 		if (acked > so->so_snd.sb_cc) {
2715 			tp->snd_wnd -= so->so_snd.sb_cc;
2716 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2717 			ourfinisacked = 1;
2718 		} else {
2719 			if (acked > (tp->t_lastoff - tp->t_inoff))
2720 				tp->t_lastm = NULL;
2721 			sbdrop(&so->so_snd, acked);
2722 			tp->t_lastoff -= acked;
2723 			tp->snd_wnd -= acked;
2724 			ourfinisacked = 0;
2725 		}
2726 		sowwakeup(so);
2727 
2728 		icmp_check(tp, th, acked);
2729 
2730 		tp->snd_una = th->th_ack;
2731 		if (SEQ_GT(tp->snd_una, tp->snd_fack))
2732 			tp->snd_fack = tp->snd_una;
2733 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2734 			tp->snd_nxt = tp->snd_una;
2735 		if (SEQ_LT(tp->snd_high, tp->snd_una))
2736 			tp->snd_high = tp->snd_una;
2737 
2738 		switch (tp->t_state) {
2739 
2740 		/*
2741 		 * In FIN_WAIT_1 STATE in addition to the processing
2742 		 * for the ESTABLISHED state if our FIN is now acknowledged
2743 		 * then enter FIN_WAIT_2.
2744 		 */
2745 		case TCPS_FIN_WAIT_1:
2746 			if (ourfinisacked) {
2747 				/*
2748 				 * If we can't receive any more
2749 				 * data, then closing user can proceed.
2750 				 * Starting the timer is contrary to the
2751 				 * specification, but if we don't get a FIN
2752 				 * we'll hang forever.
2753 				 */
2754 				if (so->so_state & SS_CANTRCVMORE) {
2755 					soisdisconnected(so);
2756 					if (tp->t_maxidle > 0)
2757 						TCP_TIMER_ARM(tp, TCPT_2MSL,
2758 						    tp->t_maxidle);
2759 				}
2760 				tp->t_state = TCPS_FIN_WAIT_2;
2761 			}
2762 			break;
2763 
2764 	 	/*
2765 		 * In CLOSING STATE in addition to the processing for
2766 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2767 		 * then enter the TIME-WAIT state, otherwise ignore
2768 		 * the segment.
2769 		 */
2770 		case TCPS_CLOSING:
2771 			if (ourfinisacked) {
2772 				tp->t_state = TCPS_TIME_WAIT;
2773 				tcp_canceltimers(tp);
2774 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2775 				soisdisconnected(so);
2776 			}
2777 			break;
2778 
2779 		/*
2780 		 * In LAST_ACK, we may still be waiting for data to drain
2781 		 * and/or to be acked, as well as for the ack of our FIN.
2782 		 * If our FIN is now acknowledged, delete the TCB,
2783 		 * enter the closed state and return.
2784 		 */
2785 		case TCPS_LAST_ACK:
2786 			if (ourfinisacked) {
2787 				tp = tcp_close(tp);
2788 				goto drop;
2789 			}
2790 			break;
2791 
2792 		/*
2793 		 * In TIME_WAIT state the only thing that should arrive
2794 		 * is a retransmission of the remote FIN.  Acknowledge
2795 		 * it and restart the finack timer.
2796 		 */
2797 		case TCPS_TIME_WAIT:
2798 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2799 			goto dropafterack;
2800 		}
2801 	}
2802 
2803 step6:
2804 	/*
2805 	 * Update window information.
2806 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2807 	 */
2808 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2809 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2810 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2811 		/* keep track of pure window updates */
2812 		if (tlen == 0 &&
2813 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2814 			TCP_STATINC(TCP_STAT_RCVWINUPD);
2815 		tp->snd_wnd = tiwin;
2816 		tp->snd_wl1 = th->th_seq;
2817 		tp->snd_wl2 = th->th_ack;
2818 		if (tp->snd_wnd > tp->max_sndwnd)
2819 			tp->max_sndwnd = tp->snd_wnd;
2820 		needoutput = 1;
2821 	}
2822 
2823 	/*
2824 	 * Process segments with URG.
2825 	 */
2826 	if ((tiflags & TH_URG) && th->th_urp &&
2827 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2828 		/*
2829 		 * This is a kludge, but if we receive and accept
2830 		 * random urgent pointers, we'll crash in
2831 		 * soreceive.  It's hard to imagine someone
2832 		 * actually wanting to send this much urgent data.
2833 		 */
2834 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2835 			th->th_urp = 0;			/* XXX */
2836 			tiflags &= ~TH_URG;		/* XXX */
2837 			goto dodata;			/* XXX */
2838 		}
2839 		/*
2840 		 * If this segment advances the known urgent pointer,
2841 		 * then mark the data stream.  This should not happen
2842 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2843 		 * a FIN has been received from the remote side.
2844 		 * In these states we ignore the URG.
2845 		 *
2846 		 * According to RFC961 (Assigned Protocols),
2847 		 * the urgent pointer points to the last octet
2848 		 * of urgent data.  We continue, however,
2849 		 * to consider it to indicate the first octet
2850 		 * of data past the urgent section as the original
2851 		 * spec states (in one of two places).
2852 		 */
2853 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2854 			tp->rcv_up = th->th_seq + th->th_urp;
2855 			so->so_oobmark = so->so_rcv.sb_cc +
2856 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2857 			if (so->so_oobmark == 0)
2858 				so->so_state |= SS_RCVATMARK;
2859 			sohasoutofband(so);
2860 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2861 		}
2862 		/*
2863 		 * Remove out of band data so doesn't get presented to user.
2864 		 * This can happen independent of advancing the URG pointer,
2865 		 * but if two URG's are pending at once, some out-of-band
2866 		 * data may creep in... ick.
2867 		 */
2868 		if (th->th_urp <= (u_int16_t) tlen
2869 #ifdef SO_OOBINLINE
2870 		     && (so->so_options & SO_OOBINLINE) == 0
2871 #endif
2872 		     )
2873 			tcp_pulloutofband(so, th, m, hdroptlen);
2874 	} else
2875 		/*
2876 		 * If no out of band data is expected,
2877 		 * pull receive urgent pointer along
2878 		 * with the receive window.
2879 		 */
2880 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2881 			tp->rcv_up = tp->rcv_nxt;
2882 dodata:							/* XXX */
2883 
2884 	/*
2885 	 * Process the segment text, merging it into the TCP sequencing queue,
2886 	 * and arranging for acknowledgement of receipt if necessary.
2887 	 * This process logically involves adjusting tp->rcv_wnd as data
2888 	 * is presented to the user (this happens in tcp_usrreq.c,
2889 	 * case PRU_RCVD).  If a FIN has already been received on this
2890 	 * connection then we just ignore the text.
2891 	 */
2892 	if ((tlen || (tiflags & TH_FIN)) &&
2893 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2894 		/*
2895 		 * Insert segment ti into reassembly queue of tcp with
2896 		 * control block tp.  Return TH_FIN if reassembly now includes
2897 		 * a segment with FIN.  The macro form does the common case
2898 		 * inline (segment is the next to be received on an
2899 		 * established connection, and the queue is empty),
2900 		 * avoiding linkage into and removal from the queue and
2901 		 * repetition of various conversions.
2902 		 * Set DELACK for segments received in order, but ack
2903 		 * immediately when segments are out of order
2904 		 * (so fast retransmit can work).
2905 		 */
2906 		/* NOTE: this was TCP_REASS() macro, but used only once */
2907 		TCP_REASS_LOCK(tp);
2908 		if (th->th_seq == tp->rcv_nxt &&
2909 		    TAILQ_FIRST(&tp->segq) == NULL &&
2910 		    tp->t_state == TCPS_ESTABLISHED) {
2911 			tcp_setup_ack(tp, th);
2912 			tp->rcv_nxt += tlen;
2913 			tiflags = th->th_flags & TH_FIN;
2914 			tcps = TCP_STAT_GETREF();
2915 			tcps[TCP_STAT_RCVPACK]++;
2916 			tcps[TCP_STAT_RCVBYTE] += tlen;
2917 			TCP_STAT_PUTREF();
2918 			nd6_hint(tp);
2919 			if (so->so_state & SS_CANTRCVMORE)
2920 				m_freem(m);
2921 			else {
2922 				m_adj(m, hdroptlen);
2923 				sbappendstream(&(so)->so_rcv, m);
2924 			}
2925 			TCP_REASS_UNLOCK(tp);
2926 			sorwakeup(so);
2927 		} else {
2928 			m_adj(m, hdroptlen);
2929 			tiflags = tcp_reass(tp, th, m, &tlen);
2930 			tp->t_flags |= TF_ACKNOW;
2931 			TCP_REASS_UNLOCK(tp);
2932 		}
2933 
2934 		/*
2935 		 * Note the amount of data that peer has sent into
2936 		 * our window, in order to estimate the sender's
2937 		 * buffer size.
2938 		 */
2939 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2940 	} else {
2941 		m_freem(m);
2942 		m = NULL;
2943 		tiflags &= ~TH_FIN;
2944 	}
2945 
2946 	/*
2947 	 * If FIN is received ACK the FIN and let the user know
2948 	 * that the connection is closing.  Ignore a FIN received before
2949 	 * the connection is fully established.
2950 	 */
2951 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2952 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2953 			socantrcvmore(so);
2954 			tp->t_flags |= TF_ACKNOW;
2955 			tp->rcv_nxt++;
2956 		}
2957 		switch (tp->t_state) {
2958 
2959 	 	/*
2960 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2961 		 */
2962 		case TCPS_ESTABLISHED:
2963 			tp->t_state = TCPS_CLOSE_WAIT;
2964 			break;
2965 
2966 	 	/*
2967 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2968 		 * enter the CLOSING state.
2969 		 */
2970 		case TCPS_FIN_WAIT_1:
2971 			tp->t_state = TCPS_CLOSING;
2972 			break;
2973 
2974 	 	/*
2975 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2976 		 * starting the time-wait timer, turning off the other
2977 		 * standard timers.
2978 		 */
2979 		case TCPS_FIN_WAIT_2:
2980 			tp->t_state = TCPS_TIME_WAIT;
2981 			tcp_canceltimers(tp);
2982 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2983 			soisdisconnected(so);
2984 			break;
2985 
2986 		/*
2987 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2988 		 */
2989 		case TCPS_TIME_WAIT:
2990 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2991 			break;
2992 		}
2993 	}
2994 #ifdef TCP_DEBUG
2995 	if (so->so_options & SO_DEBUG)
2996 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2997 #endif
2998 
2999 	/*
3000 	 * Return any desired output.
3001 	 */
3002 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
3003 		KERNEL_LOCK(1, NULL);
3004 		(void) tcp_output(tp);
3005 		KERNEL_UNLOCK_ONE(NULL);
3006 	}
3007 	if (tcp_saveti)
3008 		m_freem(tcp_saveti);
3009 
3010 	if (tp->t_state == TCPS_TIME_WAIT
3011 	    && (so->so_state & SS_NOFDREF)
3012 	    && (tp->t_inpcb || af != AF_INET)
3013 	    && (tp->t_in6pcb || af != AF_INET6)
3014 	    && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
3015 	    && TAILQ_EMPTY(&tp->segq)
3016 	    && vtw_add(af, tp)) {
3017 		;
3018 	}
3019 	return;
3020 
3021 badsyn:
3022 	/*
3023 	 * Received a bad SYN.  Increment counters and dropwithreset.
3024 	 */
3025 	TCP_STATINC(TCP_STAT_BADSYN);
3026 	tp = NULL;
3027 	goto dropwithreset;
3028 
3029 dropafterack:
3030 	/*
3031 	 * Generate an ACK dropping incoming segment if it occupies
3032 	 * sequence space, where the ACK reflects our state.
3033 	 */
3034 	if (tiflags & TH_RST)
3035 		goto drop;
3036 	goto dropafterack2;
3037 
3038 dropafterack_ratelim:
3039 	/*
3040 	 * We may want to rate-limit ACKs against SYN/RST attack.
3041 	 */
3042 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
3043 	    tcp_ackdrop_ppslim) == 0) {
3044 		/* XXX stat */
3045 		goto drop;
3046 	}
3047 	/* ...fall into dropafterack2... */
3048 
3049 dropafterack2:
3050 	m_freem(m);
3051 	tp->t_flags |= TF_ACKNOW;
3052 	KERNEL_LOCK(1, NULL);
3053 	(void) tcp_output(tp);
3054 	KERNEL_UNLOCK_ONE(NULL);
3055 	if (tcp_saveti)
3056 		m_freem(tcp_saveti);
3057 	return;
3058 
3059 dropwithreset_ratelim:
3060 	/*
3061 	 * We may want to rate-limit RSTs in certain situations,
3062 	 * particularly if we are sending an RST in response to
3063 	 * an attempt to connect to or otherwise communicate with
3064 	 * a port for which we have no socket.
3065 	 */
3066 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
3067 	    tcp_rst_ppslim) == 0) {
3068 		/* XXX stat */
3069 		goto drop;
3070 	}
3071 	/* ...fall into dropwithreset... */
3072 
3073 dropwithreset:
3074 	/*
3075 	 * Generate a RST, dropping incoming segment.
3076 	 * Make ACK acceptable to originator of segment.
3077 	 */
3078 	if (tiflags & TH_RST)
3079 		goto drop;
3080 
3081 	switch (af) {
3082 #ifdef INET6
3083 	case AF_INET6:
3084 		/* For following calls to tcp_respond */
3085 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
3086 			goto drop;
3087 		break;
3088 #endif /* INET6 */
3089 	case AF_INET:
3090 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
3091 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3092 			goto drop;
3093 	}
3094 
3095 	if (tiflags & TH_ACK)
3096 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3097 	else {
3098 		if (tiflags & TH_SYN)
3099 			tlen++;
3100 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
3101 		    TH_RST|TH_ACK);
3102 	}
3103 	if (tcp_saveti)
3104 		m_freem(tcp_saveti);
3105 	return;
3106 
3107 badcsum:
3108 drop:
3109 	/*
3110 	 * Drop space held by incoming segment and return.
3111 	 */
3112 	if (tp) {
3113 		if (tp->t_inpcb)
3114 			so = tp->t_inpcb->inp_socket;
3115 #ifdef INET6
3116 		else if (tp->t_in6pcb)
3117 			so = tp->t_in6pcb->in6p_socket;
3118 #endif
3119 		else
3120 			so = NULL;
3121 #ifdef TCP_DEBUG
3122 		if (so && (so->so_options & SO_DEBUG) != 0)
3123 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
3124 #endif
3125 	}
3126 	if (tcp_saveti)
3127 		m_freem(tcp_saveti);
3128 	m_freem(m);
3129 	return;
3130 }
3131 
3132 #ifdef TCP_SIGNATURE
3133 int
3134 tcp_signature_apply(void *fstate, void *data, u_int len)
3135 {
3136 
3137 	MD5Update(fstate, (u_char *)data, len);
3138 	return (0);
3139 }
3140 
3141 struct secasvar *
3142 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
3143 {
3144 	struct secasvar *sav;
3145 #ifdef FAST_IPSEC
3146 	union sockaddr_union dst;
3147 #endif
3148 	struct ip *ip;
3149 	struct ip6_hdr *ip6;
3150 
3151 	ip = mtod(m, struct ip *);
3152 	switch (ip->ip_v) {
3153 	case 4:
3154 		ip = mtod(m, struct ip *);
3155 		ip6 = NULL;
3156 		break;
3157 	case 6:
3158 		ip = NULL;
3159 		ip6 = mtod(m, struct ip6_hdr *);
3160 		break;
3161 	default:
3162 		return (NULL);
3163 	}
3164 
3165 #ifdef FAST_IPSEC
3166 	/* Extract the destination from the IP header in the mbuf. */
3167 	memset(&dst, 0, sizeof(union sockaddr_union));
3168 	if (ip !=NULL) {
3169 		dst.sa.sa_len = sizeof(struct sockaddr_in);
3170 		dst.sa.sa_family = AF_INET;
3171 		dst.sin.sin_addr = ip->ip_dst;
3172 	} else {
3173 		dst.sa.sa_len = sizeof(struct sockaddr_in6);
3174 		dst.sa.sa_family = AF_INET6;
3175 		dst.sin6.sin6_addr = ip6->ip6_dst;
3176 	}
3177 
3178 	/*
3179 	 * Look up an SADB entry which matches the address of the peer.
3180 	 */
3181 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
3182 #else
3183 	if (ip)
3184 		sav = key_allocsa(AF_INET, (void *)&ip->ip_src,
3185 		    (void *)&ip->ip_dst, IPPROTO_TCP,
3186 		    htonl(TCP_SIG_SPI), 0, 0);
3187 	else
3188 		sav = key_allocsa(AF_INET6, (void *)&ip6->ip6_src,
3189 		    (void *)&ip6->ip6_dst, IPPROTO_TCP,
3190 		    htonl(TCP_SIG_SPI), 0, 0);
3191 #endif
3192 
3193 	return (sav);	/* freesav must be performed by caller */
3194 }
3195 
3196 int
3197 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
3198     struct secasvar *sav, char *sig)
3199 {
3200 	MD5_CTX ctx;
3201 	struct ip *ip;
3202 	struct ipovly *ipovly;
3203 	struct ip6_hdr *ip6;
3204 	struct ippseudo ippseudo;
3205 	struct ip6_hdr_pseudo ip6pseudo;
3206 	struct tcphdr th0;
3207 	int l, tcphdrlen;
3208 
3209 	if (sav == NULL)
3210 		return (-1);
3211 
3212 	tcphdrlen = th->th_off * 4;
3213 
3214 	switch (mtod(m, struct ip *)->ip_v) {
3215 	case 4:
3216 		ip = mtod(m, struct ip *);
3217 		ip6 = NULL;
3218 		break;
3219 	case 6:
3220 		ip = NULL;
3221 		ip6 = mtod(m, struct ip6_hdr *);
3222 		break;
3223 	default:
3224 		return (-1);
3225 	}
3226 
3227 	MD5Init(&ctx);
3228 
3229 	if (ip) {
3230 		memset(&ippseudo, 0, sizeof(ippseudo));
3231 		ipovly = (struct ipovly *)ip;
3232 		ippseudo.ippseudo_src = ipovly->ih_src;
3233 		ippseudo.ippseudo_dst = ipovly->ih_dst;
3234 		ippseudo.ippseudo_pad = 0;
3235 		ippseudo.ippseudo_p = IPPROTO_TCP;
3236 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
3237 		MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
3238 	} else {
3239 		memset(&ip6pseudo, 0, sizeof(ip6pseudo));
3240 		ip6pseudo.ip6ph_src = ip6->ip6_src;
3241 		in6_clearscope(&ip6pseudo.ip6ph_src);
3242 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
3243 		in6_clearscope(&ip6pseudo.ip6ph_dst);
3244 		ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
3245 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
3246 		MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
3247 	}
3248 
3249 	th0 = *th;
3250 	th0.th_sum = 0;
3251 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
3252 
3253 	l = m->m_pkthdr.len - thoff - tcphdrlen;
3254 	if (l > 0)
3255 		m_apply(m, thoff + tcphdrlen,
3256 		    m->m_pkthdr.len - thoff - tcphdrlen,
3257 		    tcp_signature_apply, &ctx);
3258 
3259 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3260 	MD5Final(sig, &ctx);
3261 
3262 	return (0);
3263 }
3264 #endif
3265 
3266 /*
3267  * tcp_dooptions: parse and process tcp options.
3268  *
3269  * returns -1 if this segment should be dropped.  (eg. wrong signature)
3270  * otherwise returns 0.
3271  */
3272 
3273 static int
3274 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt,
3275     struct tcphdr *th,
3276     struct mbuf *m, int toff, struct tcp_opt_info *oi)
3277 {
3278 	u_int16_t mss;
3279 	int opt, optlen = 0;
3280 #ifdef TCP_SIGNATURE
3281 	void *sigp = NULL;
3282 	char sigbuf[TCP_SIGLEN];
3283 	struct secasvar *sav = NULL;
3284 #endif
3285 
3286 	for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
3287 		opt = cp[0];
3288 		if (opt == TCPOPT_EOL)
3289 			break;
3290 		if (opt == TCPOPT_NOP)
3291 			optlen = 1;
3292 		else {
3293 			if (cnt < 2)
3294 				break;
3295 			optlen = cp[1];
3296 			if (optlen < 2 || optlen > cnt)
3297 				break;
3298 		}
3299 		switch (opt) {
3300 
3301 		default:
3302 			continue;
3303 
3304 		case TCPOPT_MAXSEG:
3305 			if (optlen != TCPOLEN_MAXSEG)
3306 				continue;
3307 			if (!(th->th_flags & TH_SYN))
3308 				continue;
3309 			if (TCPS_HAVERCVDSYN(tp->t_state))
3310 				continue;
3311 			bcopy(cp + 2, &mss, sizeof(mss));
3312 			oi->maxseg = ntohs(mss);
3313 			break;
3314 
3315 		case TCPOPT_WINDOW:
3316 			if (optlen != TCPOLEN_WINDOW)
3317 				continue;
3318 			if (!(th->th_flags & TH_SYN))
3319 				continue;
3320 			if (TCPS_HAVERCVDSYN(tp->t_state))
3321 				continue;
3322 			tp->t_flags |= TF_RCVD_SCALE;
3323 			tp->requested_s_scale = cp[2];
3324 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
3325 #if 0	/*XXX*/
3326 				char *p;
3327 
3328 				if (ip)
3329 					p = ntohl(ip->ip_src);
3330 #ifdef INET6
3331 				else if (ip6)
3332 					p = ip6_sprintf(&ip6->ip6_src);
3333 #endif
3334 				else
3335 					p = "(unknown)";
3336 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
3337 				    "assuming %d\n",
3338 				    tp->requested_s_scale, p,
3339 				    TCP_MAX_WINSHIFT);
3340 #else
3341 				log(LOG_ERR, "TCP: invalid wscale %d, "
3342 				    "assuming %d\n",
3343 				    tp->requested_s_scale,
3344 				    TCP_MAX_WINSHIFT);
3345 #endif
3346 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
3347 			}
3348 			break;
3349 
3350 		case TCPOPT_TIMESTAMP:
3351 			if (optlen != TCPOLEN_TIMESTAMP)
3352 				continue;
3353 			oi->ts_present = 1;
3354 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
3355 			NTOHL(oi->ts_val);
3356 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
3357 			NTOHL(oi->ts_ecr);
3358 
3359 			if (!(th->th_flags & TH_SYN))
3360 				continue;
3361 			if (TCPS_HAVERCVDSYN(tp->t_state))
3362 				continue;
3363 			/*
3364 			 * A timestamp received in a SYN makes
3365 			 * it ok to send timestamp requests and replies.
3366 			 */
3367 			tp->t_flags |= TF_RCVD_TSTMP;
3368 			tp->ts_recent = oi->ts_val;
3369 			tp->ts_recent_age = tcp_now;
3370                         break;
3371 
3372 		case TCPOPT_SACK_PERMITTED:
3373 			if (optlen != TCPOLEN_SACK_PERMITTED)
3374 				continue;
3375 			if (!(th->th_flags & TH_SYN))
3376 				continue;
3377 			if (TCPS_HAVERCVDSYN(tp->t_state))
3378 				continue;
3379 			if (tcp_do_sack) {
3380 				tp->t_flags |= TF_SACK_PERMIT;
3381 				tp->t_flags |= TF_WILL_SACK;
3382 			}
3383 			break;
3384 
3385 		case TCPOPT_SACK:
3386 			tcp_sack_option(tp, th, cp, optlen);
3387 			break;
3388 #ifdef TCP_SIGNATURE
3389 		case TCPOPT_SIGNATURE:
3390 			if (optlen != TCPOLEN_SIGNATURE)
3391 				continue;
3392 			if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN))
3393 				return (-1);
3394 
3395 			sigp = sigbuf;
3396 			memcpy(sigbuf, cp + 2, TCP_SIGLEN);
3397 			tp->t_flags |= TF_SIGNATURE;
3398 			break;
3399 #endif
3400 		}
3401 	}
3402 
3403 #ifdef TCP_SIGNATURE
3404 	if (tp->t_flags & TF_SIGNATURE) {
3405 
3406 		sav = tcp_signature_getsav(m, th);
3407 
3408 		if (sav == NULL && tp->t_state == TCPS_LISTEN)
3409 			return (-1);
3410 	}
3411 
3412 	if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) {
3413 		if (sav == NULL)
3414 			return (-1);
3415 #ifdef FAST_IPSEC
3416 		KEY_FREESAV(&sav);
3417 #else
3418 		key_freesav(sav);
3419 #endif
3420 		return (-1);
3421 	}
3422 
3423 	if (sigp) {
3424 		char sig[TCP_SIGLEN];
3425 
3426 		tcp_fields_to_net(th);
3427 		if (tcp_signature(m, th, toff, sav, sig) < 0) {
3428 			tcp_fields_to_host(th);
3429 			if (sav == NULL)
3430 				return (-1);
3431 #ifdef FAST_IPSEC
3432 			KEY_FREESAV(&sav);
3433 #else
3434 			key_freesav(sav);
3435 #endif
3436 			return (-1);
3437 		}
3438 		tcp_fields_to_host(th);
3439 
3440 		if (memcmp(sig, sigp, TCP_SIGLEN)) {
3441 			TCP_STATINC(TCP_STAT_BADSIG);
3442 			if (sav == NULL)
3443 				return (-1);
3444 #ifdef FAST_IPSEC
3445 			KEY_FREESAV(&sav);
3446 #else
3447 			key_freesav(sav);
3448 #endif
3449 			return (-1);
3450 		} else
3451 			TCP_STATINC(TCP_STAT_GOODSIG);
3452 
3453 		key_sa_recordxfer(sav, m);
3454 #ifdef FAST_IPSEC
3455 		KEY_FREESAV(&sav);
3456 #else
3457 		key_freesav(sav);
3458 #endif
3459 	}
3460 #endif
3461 
3462 	return (0);
3463 }
3464 
3465 /*
3466  * Pull out of band byte out of a segment so
3467  * it doesn't appear in the user's data queue.
3468  * It is still reflected in the segment length for
3469  * sequencing purposes.
3470  */
3471 void
3472 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3473     struct mbuf *m, int off)
3474 {
3475 	int cnt = off + th->th_urp - 1;
3476 
3477 	while (cnt >= 0) {
3478 		if (m->m_len > cnt) {
3479 			char *cp = mtod(m, char *) + cnt;
3480 			struct tcpcb *tp = sototcpcb(so);
3481 
3482 			tp->t_iobc = *cp;
3483 			tp->t_oobflags |= TCPOOB_HAVEDATA;
3484 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3485 			m->m_len--;
3486 			return;
3487 		}
3488 		cnt -= m->m_len;
3489 		m = m->m_next;
3490 		if (m == 0)
3491 			break;
3492 	}
3493 	panic("tcp_pulloutofband");
3494 }
3495 
3496 /*
3497  * Collect new round-trip time estimate
3498  * and update averages and current timeout.
3499  *
3500  * rtt is in units of slow ticks (typically 500 ms) -- essentially the
3501  * difference of two timestamps.
3502  */
3503 void
3504 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3505 {
3506 	int32_t delta;
3507 
3508 	TCP_STATINC(TCP_STAT_RTTUPDATED);
3509 	if (tp->t_srtt != 0) {
3510 		/*
3511 		 * Compute the amount to add to srtt for smoothing,
3512 		 * *alpha, or 2^(-TCP_RTT_SHIFT).  Because
3513 		 * srtt is stored in 1/32 slow ticks, we conceptually
3514 		 * shift left 5 bits, subtract srtt to get the
3515 		 * diference, and then shift right by TCP_RTT_SHIFT
3516 		 * (3) to obtain 1/8 of the difference.
3517 		 */
3518 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3519 		/*
3520 		 * This can never happen, because delta's lowest
3521 		 * possible value is 1/8 of t_srtt.  But if it does,
3522 		 * set srtt to some reasonable value, here chosen
3523 		 * as 1/8 tick.
3524 		 */
3525 		if ((tp->t_srtt += delta) <= 0)
3526 			tp->t_srtt = 1 << 2;
3527 		/*
3528 		 * RFC2988 requires that rttvar be updated first.
3529 		 * This code is compliant because "delta" is the old
3530 		 * srtt minus the new observation (scaled).
3531 		 *
3532 		 * RFC2988 says:
3533 		 *   rttvar = (1-beta) * rttvar + beta * |srtt-observed|
3534 		 *
3535 		 * delta is in units of 1/32 ticks, and has then been
3536 		 * divided by 8.  This is equivalent to being in 1/16s
3537 		 * units and divided by 4.  Subtract from it 1/4 of
3538 		 * the existing rttvar to form the (signed) amount to
3539 		 * adjust.
3540 		 */
3541 		if (delta < 0)
3542 			delta = -delta;
3543 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3544 		/*
3545 		 * As with srtt, this should never happen.  There is
3546 		 * no support in RFC2988 for this operation.  But 1/4s
3547 		 * as rttvar when faced with something arguably wrong
3548 		 * is ok.
3549 		 */
3550 		if ((tp->t_rttvar += delta) <= 0)
3551 			tp->t_rttvar = 1 << 2;
3552 
3553 		/*
3554 		 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
3555 		 * Problem is: it doesn't work.  Disabled by defaulting
3556 		 * tcp_rttlocal to 0; see corresponding code in
3557 		 * tcp_subr that selects local vs remote in a different way.
3558 		 *
3559 		 * The static branch prediction hint here should be removed
3560 		 * when the rtt estimator is fixed and the rtt_enable code
3561 		 * is turned back on.
3562 		 */
3563 		if (__predict_false(tcp_rttlocal) && tcp_msl_enable
3564 		    && tp->t_srtt > tcp_msl_remote_threshold
3565 		    && tp->t_msl  < tcp_msl_remote) {
3566 			tp->t_msl = tcp_msl_remote;
3567 		}
3568 	} else {
3569 		/*
3570 		 * This is the first measurement.  Per RFC2988, 2.2,
3571 		 * set rtt=R and srtt=R/2.
3572 		 * For srtt, storage representation is 1/32 ticks,
3573 		 * so shift left by 5.
3574 		 * For rttvar, storage representation is 1/16 ticks,
3575 		 * So shift left by 4, but then right by 1 to halve.
3576 		 */
3577 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3578 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3579 	}
3580 	tp->t_rtttime = 0;
3581 	tp->t_rxtshift = 0;
3582 
3583 	/*
3584 	 * the retransmit should happen at rtt + 4 * rttvar.
3585 	 * Because of the way we do the smoothing, srtt and rttvar
3586 	 * will each average +1/2 tick of bias.  When we compute
3587 	 * the retransmit timer, we want 1/2 tick of rounding and
3588 	 * 1 extra tick because of +-1/2 tick uncertainty in the
3589 	 * firing of the timer.  The bias will give us exactly the
3590 	 * 1.5 tick we need.  But, because the bias is
3591 	 * statistical, we have to test that we don't drop below
3592 	 * the minimum feasible timer (which is 2 ticks).
3593 	 */
3594 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3595 	    max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3596 
3597 	/*
3598 	 * We received an ack for a packet that wasn't retransmitted;
3599 	 * it is probably safe to discard any error indications we've
3600 	 * received recently.  This isn't quite right, but close enough
3601 	 * for now (a route might have failed after we sent a segment,
3602 	 * and the return path might not be symmetrical).
3603 	 */
3604 	tp->t_softerror = 0;
3605 }
3606 
3607 
3608 /*
3609  * TCP compressed state engine.  Currently used to hold compressed
3610  * state for SYN_RECEIVED.
3611  */
3612 
3613 u_long	syn_cache_count;
3614 u_int32_t syn_hash1, syn_hash2;
3615 
3616 #define SYN_HASH(sa, sp, dp) \
3617 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3618 				     ((u_int32_t)(sp)))^syn_hash2)))
3619 #ifndef INET6
3620 #define	SYN_HASHALL(hash, src, dst) \
3621 do {									\
3622 	hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr,	\
3623 		((const struct sockaddr_in *)(src))->sin_port,		\
3624 		((const struct sockaddr_in *)(dst))->sin_port);		\
3625 } while (/*CONSTCOND*/ 0)
3626 #else
3627 #define SYN_HASH6(sa, sp, dp) \
3628 	((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3629 	  (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3630 	 & 0x7fffffff)
3631 
3632 #define SYN_HASHALL(hash, src, dst) \
3633 do {									\
3634 	switch ((src)->sa_family) {					\
3635 	case AF_INET:							\
3636 		hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3637 			((const struct sockaddr_in *)(src))->sin_port,	\
3638 			((const struct sockaddr_in *)(dst))->sin_port);	\
3639 		break;							\
3640 	case AF_INET6:							\
3641 		hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3642 			((const struct sockaddr_in6 *)(src))->sin6_port,	\
3643 			((const struct sockaddr_in6 *)(dst))->sin6_port);	\
3644 		break;							\
3645 	default:							\
3646 		hash = 0;						\
3647 	}								\
3648 } while (/*CONSTCOND*/0)
3649 #endif /* INET6 */
3650 
3651 static struct pool syn_cache_pool;
3652 
3653 /*
3654  * We don't estimate RTT with SYNs, so each packet starts with the default
3655  * RTT and each timer step has a fixed timeout value.
3656  */
3657 #define	SYN_CACHE_TIMER_ARM(sc)						\
3658 do {									\
3659 	TCPT_RANGESET((sc)->sc_rxtcur,					\
3660 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
3661 	    TCPTV_REXMTMAX);						\
3662 	callout_reset(&(sc)->sc_timer,					\
3663 	    (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc));	\
3664 } while (/*CONSTCOND*/0)
3665 
3666 #define	SYN_CACHE_TIMESTAMP(sc)	(tcp_now - (sc)->sc_timebase)
3667 
3668 static inline void
3669 syn_cache_rm(struct syn_cache *sc)
3670 {
3671 	TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket,
3672 	    sc, sc_bucketq);
3673 	sc->sc_tp = NULL;
3674 	LIST_REMOVE(sc, sc_tpq);
3675 	tcp_syn_cache[sc->sc_bucketidx].sch_length--;
3676 	callout_stop(&sc->sc_timer);
3677 	syn_cache_count--;
3678 }
3679 
3680 static inline void
3681 syn_cache_put(struct syn_cache *sc)
3682 {
3683 	if (sc->sc_ipopts)
3684 		(void) m_free(sc->sc_ipopts);
3685 	rtcache_free(&sc->sc_route);
3686 	sc->sc_flags |= SCF_DEAD;
3687 	if (!callout_invoking(&sc->sc_timer))
3688 		callout_schedule(&(sc)->sc_timer, 1);
3689 }
3690 
3691 void
3692 syn_cache_init(void)
3693 {
3694 	int i;
3695 
3696 	pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
3697 	    "synpl", NULL, IPL_SOFTNET);
3698 
3699 	/* Initialize the hash buckets. */
3700 	for (i = 0; i < tcp_syn_cache_size; i++)
3701 		TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3702 }
3703 
3704 void
3705 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3706 {
3707 	struct syn_cache_head *scp;
3708 	struct syn_cache *sc2;
3709 	int s;
3710 
3711 	/*
3712 	 * If there are no entries in the hash table, reinitialize
3713 	 * the hash secrets.
3714 	 */
3715 	if (syn_cache_count == 0) {
3716 		syn_hash1 = arc4random();
3717 		syn_hash2 = arc4random();
3718 	}
3719 
3720 	SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3721 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3722 	scp = &tcp_syn_cache[sc->sc_bucketidx];
3723 
3724 	/*
3725 	 * Make sure that we don't overflow the per-bucket
3726 	 * limit or the total cache size limit.
3727 	 */
3728 	s = splsoftnet();
3729 	if (scp->sch_length >= tcp_syn_bucket_limit) {
3730 		TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW);
3731 		/*
3732 		 * The bucket is full.  Toss the oldest element in the
3733 		 * bucket.  This will be the first entry in the bucket.
3734 		 */
3735 		sc2 = TAILQ_FIRST(&scp->sch_bucket);
3736 #ifdef DIAGNOSTIC
3737 		/*
3738 		 * This should never happen; we should always find an
3739 		 * entry in our bucket.
3740 		 */
3741 		if (sc2 == NULL)
3742 			panic("syn_cache_insert: bucketoverflow: impossible");
3743 #endif
3744 		syn_cache_rm(sc2);
3745 		syn_cache_put(sc2);	/* calls pool_put but see spl above */
3746 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
3747 		struct syn_cache_head *scp2, *sce;
3748 
3749 		TCP_STATINC(TCP_STAT_SC_OVERFLOWED);
3750 		/*
3751 		 * The cache is full.  Toss the oldest entry in the
3752 		 * first non-empty bucket we can find.
3753 		 *
3754 		 * XXX We would really like to toss the oldest
3755 		 * entry in the cache, but we hope that this
3756 		 * condition doesn't happen very often.
3757 		 */
3758 		scp2 = scp;
3759 		if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3760 			sce = &tcp_syn_cache[tcp_syn_cache_size];
3761 			for (++scp2; scp2 != scp; scp2++) {
3762 				if (scp2 >= sce)
3763 					scp2 = &tcp_syn_cache[0];
3764 				if (! TAILQ_EMPTY(&scp2->sch_bucket))
3765 					break;
3766 			}
3767 #ifdef DIAGNOSTIC
3768 			/*
3769 			 * This should never happen; we should always find a
3770 			 * non-empty bucket.
3771 			 */
3772 			if (scp2 == scp)
3773 				panic("syn_cache_insert: cacheoverflow: "
3774 				    "impossible");
3775 #endif
3776 		}
3777 		sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3778 		syn_cache_rm(sc2);
3779 		syn_cache_put(sc2);	/* calls pool_put but see spl above */
3780 	}
3781 
3782 	/*
3783 	 * Initialize the entry's timer.
3784 	 */
3785 	sc->sc_rxttot = 0;
3786 	sc->sc_rxtshift = 0;
3787 	SYN_CACHE_TIMER_ARM(sc);
3788 
3789 	/* Link it from tcpcb entry */
3790 	LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3791 
3792 	/* Put it into the bucket. */
3793 	TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3794 	scp->sch_length++;
3795 	syn_cache_count++;
3796 
3797 	TCP_STATINC(TCP_STAT_SC_ADDED);
3798 	splx(s);
3799 }
3800 
3801 /*
3802  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3803  * If we have retransmitted an entry the maximum number of times, expire
3804  * that entry.
3805  */
3806 void
3807 syn_cache_timer(void *arg)
3808 {
3809 	struct syn_cache *sc = arg;
3810 
3811 	mutex_enter(softnet_lock);
3812 	KERNEL_LOCK(1, NULL);
3813 	callout_ack(&sc->sc_timer);
3814 
3815 	if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3816 		TCP_STATINC(TCP_STAT_SC_DELAYED_FREE);
3817 		callout_destroy(&sc->sc_timer);
3818 		pool_put(&syn_cache_pool, sc);
3819 		KERNEL_UNLOCK_ONE(NULL);
3820 		mutex_exit(softnet_lock);
3821 		return;
3822 	}
3823 
3824 	if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3825 		/* Drop it -- too many retransmissions. */
3826 		goto dropit;
3827 	}
3828 
3829 	/*
3830 	 * Compute the total amount of time this entry has
3831 	 * been on a queue.  If this entry has been on longer
3832 	 * than the keep alive timer would allow, expire it.
3833 	 */
3834 	sc->sc_rxttot += sc->sc_rxtcur;
3835 	if (sc->sc_rxttot >= tcp_keepinit)
3836 		goto dropit;
3837 
3838 	TCP_STATINC(TCP_STAT_SC_RETRANSMITTED);
3839 	(void) syn_cache_respond(sc, NULL);
3840 
3841 	/* Advance the timer back-off. */
3842 	sc->sc_rxtshift++;
3843 	SYN_CACHE_TIMER_ARM(sc);
3844 
3845 	KERNEL_UNLOCK_ONE(NULL);
3846 	mutex_exit(softnet_lock);
3847 	return;
3848 
3849  dropit:
3850 	TCP_STATINC(TCP_STAT_SC_TIMED_OUT);
3851 	syn_cache_rm(sc);
3852 	if (sc->sc_ipopts)
3853 		(void) m_free(sc->sc_ipopts);
3854 	rtcache_free(&sc->sc_route);
3855 	callout_destroy(&sc->sc_timer);
3856 	pool_put(&syn_cache_pool, sc);
3857 	KERNEL_UNLOCK_ONE(NULL);
3858 	mutex_exit(softnet_lock);
3859 }
3860 
3861 /*
3862  * Remove syn cache created by the specified tcb entry,
3863  * because this does not make sense to keep them
3864  * (if there's no tcb entry, syn cache entry will never be used)
3865  */
3866 void
3867 syn_cache_cleanup(struct tcpcb *tp)
3868 {
3869 	struct syn_cache *sc, *nsc;
3870 	int s;
3871 
3872 	s = splsoftnet();
3873 
3874 	for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3875 		nsc = LIST_NEXT(sc, sc_tpq);
3876 
3877 #ifdef DIAGNOSTIC
3878 		if (sc->sc_tp != tp)
3879 			panic("invalid sc_tp in syn_cache_cleanup");
3880 #endif
3881 		syn_cache_rm(sc);
3882 		syn_cache_put(sc);	/* calls pool_put but see spl above */
3883 	}
3884 	/* just for safety */
3885 	LIST_INIT(&tp->t_sc);
3886 
3887 	splx(s);
3888 }
3889 
3890 /*
3891  * Find an entry in the syn cache.
3892  */
3893 struct syn_cache *
3894 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3895     struct syn_cache_head **headp)
3896 {
3897 	struct syn_cache *sc;
3898 	struct syn_cache_head *scp;
3899 	u_int32_t hash;
3900 	int s;
3901 
3902 	SYN_HASHALL(hash, src, dst);
3903 
3904 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3905 	*headp = scp;
3906 	s = splsoftnet();
3907 	for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3908 	     sc = TAILQ_NEXT(sc, sc_bucketq)) {
3909 		if (sc->sc_hash != hash)
3910 			continue;
3911 		if (!memcmp(&sc->sc_src, src, src->sa_len) &&
3912 		    !memcmp(&sc->sc_dst, dst, dst->sa_len)) {
3913 			splx(s);
3914 			return (sc);
3915 		}
3916 	}
3917 	splx(s);
3918 	return (NULL);
3919 }
3920 
3921 /*
3922  * This function gets called when we receive an ACK for a
3923  * socket in the LISTEN state.  We look up the connection
3924  * in the syn cache, and if its there, we pull it out of
3925  * the cache and turn it into a full-blown connection in
3926  * the SYN-RECEIVED state.
3927  *
3928  * The return values may not be immediately obvious, and their effects
3929  * can be subtle, so here they are:
3930  *
3931  *	NULL	SYN was not found in cache; caller should drop the
3932  *		packet and send an RST.
3933  *
3934  *	-1	We were unable to create the new connection, and are
3935  *		aborting it.  An ACK,RST is being sent to the peer
3936  *		(unless we got screwey sequence numbners; see below),
3937  *		because the 3-way handshake has been completed.  Caller
3938  *		should not free the mbuf, since we may be using it.  If
3939  *		we are not, we will free it.
3940  *
3941  *	Otherwise, the return value is a pointer to the new socket
3942  *	associated with the connection.
3943  */
3944 struct socket *
3945 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3946     struct tcphdr *th, unsigned int hlen, unsigned int tlen,
3947     struct socket *so, struct mbuf *m)
3948 {
3949 	struct syn_cache *sc;
3950 	struct syn_cache_head *scp;
3951 	struct inpcb *inp = NULL;
3952 #ifdef INET6
3953 	struct in6pcb *in6p = NULL;
3954 #endif
3955 	struct tcpcb *tp = 0;
3956 	struct mbuf *am;
3957 	int s;
3958 	struct socket *oso;
3959 
3960 	s = splsoftnet();
3961 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3962 		splx(s);
3963 		return (NULL);
3964 	}
3965 
3966 	/*
3967 	 * Verify the sequence and ack numbers.  Try getting the correct
3968 	 * response again.
3969 	 */
3970 	if ((th->th_ack != sc->sc_iss + 1) ||
3971 	    SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3972 	    SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3973 		(void) syn_cache_respond(sc, m);
3974 		splx(s);
3975 		return ((struct socket *)(-1));
3976 	}
3977 
3978 	/* Remove this cache entry */
3979 	syn_cache_rm(sc);
3980 	splx(s);
3981 
3982 	/*
3983 	 * Ok, create the full blown connection, and set things up
3984 	 * as they would have been set up if we had created the
3985 	 * connection when the SYN arrived.  If we can't create
3986 	 * the connection, abort it.
3987 	 */
3988 	/*
3989 	 * inp still has the OLD in_pcb stuff, set the
3990 	 * v6-related flags on the new guy, too.   This is
3991 	 * done particularly for the case where an AF_INET6
3992 	 * socket is bound only to a port, and a v4 connection
3993 	 * comes in on that port.
3994 	 * we also copy the flowinfo from the original pcb
3995 	 * to the new one.
3996 	 */
3997 	oso = so;
3998 	so = sonewconn(so, SS_ISCONNECTED);
3999 	if (so == NULL)
4000 		goto resetandabort;
4001 
4002 	switch (so->so_proto->pr_domain->dom_family) {
4003 #ifdef INET
4004 	case AF_INET:
4005 		inp = sotoinpcb(so);
4006 		break;
4007 #endif
4008 #ifdef INET6
4009 	case AF_INET6:
4010 		in6p = sotoin6pcb(so);
4011 		break;
4012 #endif
4013 	}
4014 	switch (src->sa_family) {
4015 #ifdef INET
4016 	case AF_INET:
4017 		if (inp) {
4018 			inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
4019 			inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
4020 			inp->inp_options = ip_srcroute();
4021 			in_pcbstate(inp, INP_BOUND);
4022 			if (inp->inp_options == NULL) {
4023 				inp->inp_options = sc->sc_ipopts;
4024 				sc->sc_ipopts = NULL;
4025 			}
4026 		}
4027 #ifdef INET6
4028 		else if (in6p) {
4029 			/* IPv4 packet to AF_INET6 socket */
4030 			memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr));
4031 			in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
4032 			bcopy(&((struct sockaddr_in *)dst)->sin_addr,
4033 				&in6p->in6p_laddr.s6_addr32[3],
4034 				sizeof(((struct sockaddr_in *)dst)->sin_addr));
4035 			in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
4036 			in6totcpcb(in6p)->t_family = AF_INET;
4037 			if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
4038 				in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
4039 			else
4040 				in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
4041 			in6_pcbstate(in6p, IN6P_BOUND);
4042 		}
4043 #endif
4044 		break;
4045 #endif
4046 #ifdef INET6
4047 	case AF_INET6:
4048 		if (in6p) {
4049 			in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
4050 			in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
4051 			in6_pcbstate(in6p, IN6P_BOUND);
4052 		}
4053 		break;
4054 #endif
4055 	}
4056 #ifdef INET6
4057 	if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
4058 		struct in6pcb *oin6p = sotoin6pcb(oso);
4059 		/* inherit socket options from the listening socket */
4060 		in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
4061 		if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
4062 			m_freem(in6p->in6p_options);
4063 			in6p->in6p_options = 0;
4064 		}
4065 		ip6_savecontrol(in6p, &in6p->in6p_options,
4066 			mtod(m, struct ip6_hdr *), m);
4067 	}
4068 #endif
4069 
4070 #if defined(IPSEC) || defined(FAST_IPSEC)
4071 	/*
4072 	 * we make a copy of policy, instead of sharing the policy,
4073 	 * for better behavior in terms of SA lookup and dead SA removal.
4074 	 */
4075 	if (inp) {
4076 		/* copy old policy into new socket's */
4077 		if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
4078 			printf("tcp_input: could not copy policy\n");
4079 	}
4080 #ifdef INET6
4081 	else if (in6p) {
4082 		/* copy old policy into new socket's */
4083 		if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
4084 		    in6p->in6p_sp))
4085 			printf("tcp_input: could not copy policy\n");
4086 	}
4087 #endif
4088 #endif
4089 
4090 	/*
4091 	 * Give the new socket our cached route reference.
4092 	 */
4093 	if (inp) {
4094 		rtcache_copy(&inp->inp_route, &sc->sc_route);
4095 		rtcache_free(&sc->sc_route);
4096 	}
4097 #ifdef INET6
4098 	else {
4099 		rtcache_copy(&in6p->in6p_route, &sc->sc_route);
4100 		rtcache_free(&sc->sc_route);
4101 	}
4102 #endif
4103 
4104 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
4105 	if (am == NULL)
4106 		goto resetandabort;
4107 	MCLAIM(am, &tcp_mowner);
4108 	am->m_len = src->sa_len;
4109 	bcopy(src, mtod(am, void *), src->sa_len);
4110 	if (inp) {
4111 		if (in_pcbconnect(inp, am, &lwp0)) {
4112 			(void) m_free(am);
4113 			goto resetandabort;
4114 		}
4115 	}
4116 #ifdef INET6
4117 	else if (in6p) {
4118 		if (src->sa_family == AF_INET) {
4119 			/* IPv4 packet to AF_INET6 socket */
4120 			struct sockaddr_in6 *sin6;
4121 			sin6 = mtod(am, struct sockaddr_in6 *);
4122 			am->m_len = sizeof(*sin6);
4123 			memset(sin6, 0, sizeof(*sin6));
4124 			sin6->sin6_family = AF_INET6;
4125 			sin6->sin6_len = sizeof(*sin6);
4126 			sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
4127 			sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
4128 			bcopy(&((struct sockaddr_in *)src)->sin_addr,
4129 				&sin6->sin6_addr.s6_addr32[3],
4130 				sizeof(sin6->sin6_addr.s6_addr32[3]));
4131 		}
4132 		if (in6_pcbconnect(in6p, am, NULL)) {
4133 			(void) m_free(am);
4134 			goto resetandabort;
4135 		}
4136 	}
4137 #endif
4138 	else {
4139 		(void) m_free(am);
4140 		goto resetandabort;
4141 	}
4142 	(void) m_free(am);
4143 
4144 	if (inp)
4145 		tp = intotcpcb(inp);
4146 #ifdef INET6
4147 	else if (in6p)
4148 		tp = in6totcpcb(in6p);
4149 #endif
4150 	else
4151 		tp = NULL;
4152 	tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
4153 	if (sc->sc_request_r_scale != 15) {
4154 		tp->requested_s_scale = sc->sc_requested_s_scale;
4155 		tp->request_r_scale = sc->sc_request_r_scale;
4156 		tp->snd_scale = sc->sc_requested_s_scale;
4157 		tp->rcv_scale = sc->sc_request_r_scale;
4158 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
4159 	}
4160 	if (sc->sc_flags & SCF_TIMESTAMP)
4161 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
4162 	tp->ts_timebase = sc->sc_timebase;
4163 
4164 	tp->t_template = tcp_template(tp);
4165 	if (tp->t_template == 0) {
4166 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
4167 		so = NULL;
4168 		m_freem(m);
4169 		goto abort;
4170 	}
4171 
4172 	tp->iss = sc->sc_iss;
4173 	tp->irs = sc->sc_irs;
4174 	tcp_sendseqinit(tp);
4175 	tcp_rcvseqinit(tp);
4176 	tp->t_state = TCPS_SYN_RECEIVED;
4177 	TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit);
4178 	TCP_STATINC(TCP_STAT_ACCEPTS);
4179 
4180 	if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
4181 		tp->t_flags |= TF_WILL_SACK;
4182 
4183 	if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
4184 		tp->t_flags |= TF_ECN_PERMIT;
4185 
4186 #ifdef TCP_SIGNATURE
4187 	if (sc->sc_flags & SCF_SIGNATURE)
4188 		tp->t_flags |= TF_SIGNATURE;
4189 #endif
4190 
4191 	/* Initialize tp->t_ourmss before we deal with the peer's! */
4192 	tp->t_ourmss = sc->sc_ourmaxseg;
4193 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
4194 
4195 	/*
4196 	 * Initialize the initial congestion window.  If we
4197 	 * had to retransmit the SYN,ACK, we must initialize cwnd
4198 	 * to 1 segment (i.e. the Loss Window).
4199 	 */
4200 	if (sc->sc_rxtshift)
4201 		tp->snd_cwnd = tp->t_peermss;
4202 	else {
4203 		int ss = tcp_init_win;
4204 #ifdef INET
4205 		if (inp != NULL && in_localaddr(inp->inp_faddr))
4206 			ss = tcp_init_win_local;
4207 #endif
4208 #ifdef INET6
4209 		if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
4210 			ss = tcp_init_win_local;
4211 #endif
4212 		tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
4213 	}
4214 
4215 	tcp_rmx_rtt(tp);
4216 	tp->snd_wl1 = sc->sc_irs;
4217 	tp->rcv_up = sc->sc_irs + 1;
4218 
4219 	/*
4220 	 * This is what whould have happened in tcp_output() when
4221 	 * the SYN,ACK was sent.
4222 	 */
4223 	tp->snd_up = tp->snd_una;
4224 	tp->snd_max = tp->snd_nxt = tp->iss+1;
4225 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
4226 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
4227 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
4228 	tp->last_ack_sent = tp->rcv_nxt;
4229 	tp->t_partialacks = -1;
4230 	tp->t_dupacks = 0;
4231 
4232 	TCP_STATINC(TCP_STAT_SC_COMPLETED);
4233 	s = splsoftnet();
4234 	syn_cache_put(sc);
4235 	splx(s);
4236 	return (so);
4237 
4238 resetandabort:
4239 	(void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
4240 abort:
4241 	if (so != NULL) {
4242 		(void) soqremque(so, 1);
4243 		(void) soabort(so);
4244 		mutex_enter(softnet_lock);
4245 	}
4246 	s = splsoftnet();
4247 	syn_cache_put(sc);
4248 	splx(s);
4249 	TCP_STATINC(TCP_STAT_SC_ABORTED);
4250 	return ((struct socket *)(-1));
4251 }
4252 
4253 /*
4254  * This function is called when we get a RST for a
4255  * non-existent connection, so that we can see if the
4256  * connection is in the syn cache.  If it is, zap it.
4257  */
4258 
4259 void
4260 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
4261 {
4262 	struct syn_cache *sc;
4263 	struct syn_cache_head *scp;
4264 	int s = splsoftnet();
4265 
4266 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4267 		splx(s);
4268 		return;
4269 	}
4270 	if (SEQ_LT(th->th_seq, sc->sc_irs) ||
4271 	    SEQ_GT(th->th_seq, sc->sc_irs+1)) {
4272 		splx(s);
4273 		return;
4274 	}
4275 	syn_cache_rm(sc);
4276 	TCP_STATINC(TCP_STAT_SC_RESET);
4277 	syn_cache_put(sc);	/* calls pool_put but see spl above */
4278 	splx(s);
4279 }
4280 
4281 void
4282 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
4283     struct tcphdr *th)
4284 {
4285 	struct syn_cache *sc;
4286 	struct syn_cache_head *scp;
4287 	int s;
4288 
4289 	s = splsoftnet();
4290 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4291 		splx(s);
4292 		return;
4293 	}
4294 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
4295 	if (ntohl (th->th_seq) != sc->sc_iss) {
4296 		splx(s);
4297 		return;
4298 	}
4299 
4300 	/*
4301 	 * If we've retransmitted 3 times and this is our second error,
4302 	 * we remove the entry.  Otherwise, we allow it to continue on.
4303 	 * This prevents us from incorrectly nuking an entry during a
4304 	 * spurious network outage.
4305 	 *
4306 	 * See tcp_notify().
4307 	 */
4308 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
4309 		sc->sc_flags |= SCF_UNREACH;
4310 		splx(s);
4311 		return;
4312 	}
4313 
4314 	syn_cache_rm(sc);
4315 	TCP_STATINC(TCP_STAT_SC_UNREACH);
4316 	syn_cache_put(sc);	/* calls pool_put but see spl above */
4317 	splx(s);
4318 }
4319 
4320 /*
4321  * Given a LISTEN socket and an inbound SYN request, add
4322  * this to the syn cache, and send back a segment:
4323  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
4324  * to the source.
4325  *
4326  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
4327  * Doing so would require that we hold onto the data and deliver it
4328  * to the application.  However, if we are the target of a SYN-flood
4329  * DoS attack, an attacker could send data which would eventually
4330  * consume all available buffer space if it were ACKed.  By not ACKing
4331  * the data, we avoid this DoS scenario.
4332  */
4333 
4334 int
4335 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
4336     unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
4337     int optlen, struct tcp_opt_info *oi)
4338 {
4339 	struct tcpcb tb, *tp;
4340 	long win;
4341 	struct syn_cache *sc;
4342 	struct syn_cache_head *scp;
4343 	struct mbuf *ipopts;
4344 	struct tcp_opt_info opti;
4345 	int s;
4346 
4347 	tp = sototcpcb(so);
4348 
4349 	memset(&opti, 0, sizeof(opti));
4350 
4351 	/*
4352 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
4353 	 *
4354 	 * Note this check is performed in tcp_input() very early on.
4355 	 */
4356 
4357 	/*
4358 	 * Initialize some local state.
4359 	 */
4360 	win = sbspace(&so->so_rcv);
4361 	if (win > TCP_MAXWIN)
4362 		win = TCP_MAXWIN;
4363 
4364 	switch (src->sa_family) {
4365 #ifdef INET
4366 	case AF_INET:
4367 		/*
4368 		 * Remember the IP options, if any.
4369 		 */
4370 		ipopts = ip_srcroute();
4371 		break;
4372 #endif
4373 	default:
4374 		ipopts = NULL;
4375 	}
4376 
4377 #ifdef TCP_SIGNATURE
4378 	if (optp || (tp->t_flags & TF_SIGNATURE))
4379 #else
4380 	if (optp)
4381 #endif
4382 	{
4383 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
4384 #ifdef TCP_SIGNATURE
4385 		tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
4386 #endif
4387 		tb.t_state = TCPS_LISTEN;
4388 		if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
4389 		    sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
4390 			return (0);
4391 	} else
4392 		tb.t_flags = 0;
4393 
4394 	/*
4395 	 * See if we already have an entry for this connection.
4396 	 * If we do, resend the SYN,ACK.  We do not count this
4397 	 * as a retransmission (XXX though maybe we should).
4398 	 */
4399 	if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
4400 		TCP_STATINC(TCP_STAT_SC_DUPESYN);
4401 		if (ipopts) {
4402 			/*
4403 			 * If we were remembering a previous source route,
4404 			 * forget it and use the new one we've been given.
4405 			 */
4406 			if (sc->sc_ipopts)
4407 				(void) m_free(sc->sc_ipopts);
4408 			sc->sc_ipopts = ipopts;
4409 		}
4410 		sc->sc_timestamp = tb.ts_recent;
4411 		if (syn_cache_respond(sc, m) == 0) {
4412 			uint64_t *tcps = TCP_STAT_GETREF();
4413 			tcps[TCP_STAT_SNDACKS]++;
4414 			tcps[TCP_STAT_SNDTOTAL]++;
4415 			TCP_STAT_PUTREF();
4416 		}
4417 		return (1);
4418 	}
4419 
4420 	s = splsoftnet();
4421 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
4422 	splx(s);
4423 	if (sc == NULL) {
4424 		if (ipopts)
4425 			(void) m_free(ipopts);
4426 		return (0);
4427 	}
4428 
4429 	/*
4430 	 * Fill in the cache, and put the necessary IP and TCP
4431 	 * options into the reply.
4432 	 */
4433 	memset(sc, 0, sizeof(struct syn_cache));
4434 	callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
4435 	bcopy(src, &sc->sc_src, src->sa_len);
4436 	bcopy(dst, &sc->sc_dst, dst->sa_len);
4437 	sc->sc_flags = 0;
4438 	sc->sc_ipopts = ipopts;
4439 	sc->sc_irs = th->th_seq;
4440 	switch (src->sa_family) {
4441 #ifdef INET
4442 	case AF_INET:
4443 	    {
4444 		struct sockaddr_in *srcin = (void *) src;
4445 		struct sockaddr_in *dstin = (void *) dst;
4446 
4447 		sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
4448 		    &srcin->sin_addr, dstin->sin_port,
4449 		    srcin->sin_port, sizeof(dstin->sin_addr), 0);
4450 		break;
4451 	    }
4452 #endif /* INET */
4453 #ifdef INET6
4454 	case AF_INET6:
4455 	    {
4456 		struct sockaddr_in6 *srcin6 = (void *) src;
4457 		struct sockaddr_in6 *dstin6 = (void *) dst;
4458 
4459 		sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
4460 		    &srcin6->sin6_addr, dstin6->sin6_port,
4461 		    srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
4462 		break;
4463 	    }
4464 #endif /* INET6 */
4465 	}
4466 	sc->sc_peermaxseg = oi->maxseg;
4467 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
4468 						m->m_pkthdr.rcvif : NULL,
4469 						sc->sc_src.sa.sa_family);
4470 	sc->sc_win = win;
4471 	sc->sc_timebase = tcp_now - 1;	/* see tcp_newtcpcb() */
4472 	sc->sc_timestamp = tb.ts_recent;
4473 	if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
4474 	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
4475 		sc->sc_flags |= SCF_TIMESTAMP;
4476 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
4477 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
4478 		sc->sc_requested_s_scale = tb.requested_s_scale;
4479 		sc->sc_request_r_scale = 0;
4480 		/*
4481 		 * Pick the smallest possible scaling factor that
4482 		 * will still allow us to scale up to sb_max.
4483 		 *
4484 		 * We do this because there are broken firewalls that
4485 		 * will corrupt the window scale option, leading to
4486 		 * the other endpoint believing that our advertised
4487 		 * window is unscaled.  At scale factors larger than
4488 		 * 5 the unscaled window will drop below 1500 bytes,
4489 		 * leading to serious problems when traversing these
4490 		 * broken firewalls.
4491 		 *
4492 		 * With the default sbmax of 256K, a scale factor
4493 		 * of 3 will be chosen by this algorithm.  Those who
4494 		 * choose a larger sbmax should watch out
4495 		 * for the compatiblity problems mentioned above.
4496 		 *
4497 		 * RFC1323: The Window field in a SYN (i.e., a <SYN>
4498 		 * or <SYN,ACK>) segment itself is never scaled.
4499 		 */
4500 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
4501 		    (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max)
4502 			sc->sc_request_r_scale++;
4503 	} else {
4504 		sc->sc_requested_s_scale = 15;
4505 		sc->sc_request_r_scale = 15;
4506 	}
4507 	if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
4508 		sc->sc_flags |= SCF_SACK_PERMIT;
4509 
4510 	/*
4511 	 * ECN setup packet recieved.
4512 	 */
4513 	if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn)
4514 		sc->sc_flags |= SCF_ECN_PERMIT;
4515 
4516 #ifdef TCP_SIGNATURE
4517 	if (tb.t_flags & TF_SIGNATURE)
4518 		sc->sc_flags |= SCF_SIGNATURE;
4519 #endif
4520 	sc->sc_tp = tp;
4521 	if (syn_cache_respond(sc, m) == 0) {
4522 		uint64_t *tcps = TCP_STAT_GETREF();
4523 		tcps[TCP_STAT_SNDACKS]++;
4524 		tcps[TCP_STAT_SNDTOTAL]++;
4525 		TCP_STAT_PUTREF();
4526 		syn_cache_insert(sc, tp);
4527 	} else {
4528 		s = splsoftnet();
4529 		/*
4530 		 * syn_cache_put() will try to schedule the timer, so
4531 		 * we need to initialize it
4532 		 */
4533 		SYN_CACHE_TIMER_ARM(sc);
4534 		syn_cache_put(sc);
4535 		splx(s);
4536 		TCP_STATINC(TCP_STAT_SC_DROPPED);
4537 	}
4538 	return (1);
4539 }
4540 
4541 int
4542 syn_cache_respond(struct syn_cache *sc, struct mbuf *m)
4543 {
4544 #ifdef INET6
4545 	struct rtentry *rt;
4546 #endif
4547 	struct route *ro;
4548 	u_int8_t *optp;
4549 	int optlen, error;
4550 	u_int16_t tlen;
4551 	struct ip *ip = NULL;
4552 #ifdef INET6
4553 	struct ip6_hdr *ip6 = NULL;
4554 #endif
4555 	struct tcpcb *tp = NULL;
4556 	struct tcphdr *th;
4557 	u_int hlen;
4558 	struct socket *so;
4559 
4560 	ro = &sc->sc_route;
4561 	switch (sc->sc_src.sa.sa_family) {
4562 	case AF_INET:
4563 		hlen = sizeof(struct ip);
4564 		break;
4565 #ifdef INET6
4566 	case AF_INET6:
4567 		hlen = sizeof(struct ip6_hdr);
4568 		break;
4569 #endif
4570 	default:
4571 		if (m)
4572 			m_freem(m);
4573 		return (EAFNOSUPPORT);
4574 	}
4575 
4576 	/* Compute the size of the TCP options. */
4577 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
4578 	    ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) +
4579 #ifdef TCP_SIGNATURE
4580 	    ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
4581 #endif
4582 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
4583 
4584 	tlen = hlen + sizeof(struct tcphdr) + optlen;
4585 
4586 	/*
4587 	 * Create the IP+TCP header from scratch.
4588 	 */
4589 	if (m)
4590 		m_freem(m);
4591 #ifdef DIAGNOSTIC
4592 	if (max_linkhdr + tlen > MCLBYTES)
4593 		return (ENOBUFS);
4594 #endif
4595 	MGETHDR(m, M_DONTWAIT, MT_DATA);
4596 	if (m && (max_linkhdr + tlen) > MHLEN) {
4597 		MCLGET(m, M_DONTWAIT);
4598 		if ((m->m_flags & M_EXT) == 0) {
4599 			m_freem(m);
4600 			m = NULL;
4601 		}
4602 	}
4603 	if (m == NULL)
4604 		return (ENOBUFS);
4605 	MCLAIM(m, &tcp_tx_mowner);
4606 
4607 	/* Fixup the mbuf. */
4608 	m->m_data += max_linkhdr;
4609 	m->m_len = m->m_pkthdr.len = tlen;
4610 	if (sc->sc_tp) {
4611 		tp = sc->sc_tp;
4612 		if (tp->t_inpcb)
4613 			so = tp->t_inpcb->inp_socket;
4614 #ifdef INET6
4615 		else if (tp->t_in6pcb)
4616 			so = tp->t_in6pcb->in6p_socket;
4617 #endif
4618 		else
4619 			so = NULL;
4620 	} else
4621 		so = NULL;
4622 	m->m_pkthdr.rcvif = NULL;
4623 	memset(mtod(m, u_char *), 0, tlen);
4624 
4625 	switch (sc->sc_src.sa.sa_family) {
4626 	case AF_INET:
4627 		ip = mtod(m, struct ip *);
4628 		ip->ip_v = 4;
4629 		ip->ip_dst = sc->sc_src.sin.sin_addr;
4630 		ip->ip_src = sc->sc_dst.sin.sin_addr;
4631 		ip->ip_p = IPPROTO_TCP;
4632 		th = (struct tcphdr *)(ip + 1);
4633 		th->th_dport = sc->sc_src.sin.sin_port;
4634 		th->th_sport = sc->sc_dst.sin.sin_port;
4635 		break;
4636 #ifdef INET6
4637 	case AF_INET6:
4638 		ip6 = mtod(m, struct ip6_hdr *);
4639 		ip6->ip6_vfc = IPV6_VERSION;
4640 		ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4641 		ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4642 		ip6->ip6_nxt = IPPROTO_TCP;
4643 		/* ip6_plen will be updated in ip6_output() */
4644 		th = (struct tcphdr *)(ip6 + 1);
4645 		th->th_dport = sc->sc_src.sin6.sin6_port;
4646 		th->th_sport = sc->sc_dst.sin6.sin6_port;
4647 		break;
4648 #endif
4649 	default:
4650 		th = NULL;
4651 	}
4652 
4653 	th->th_seq = htonl(sc->sc_iss);
4654 	th->th_ack = htonl(sc->sc_irs + 1);
4655 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4656 	th->th_flags = TH_SYN|TH_ACK;
4657 	th->th_win = htons(sc->sc_win);
4658 	/* th_sum already 0 */
4659 	/* th_urp already 0 */
4660 
4661 	/* Tack on the TCP options. */
4662 	optp = (u_int8_t *)(th + 1);
4663 	*optp++ = TCPOPT_MAXSEG;
4664 	*optp++ = 4;
4665 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4666 	*optp++ = sc->sc_ourmaxseg & 0xff;
4667 
4668 	if (sc->sc_request_r_scale != 15) {
4669 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4670 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4671 		    sc->sc_request_r_scale);
4672 		optp += 4;
4673 	}
4674 
4675 	if (sc->sc_flags & SCF_TIMESTAMP) {
4676 		u_int32_t *lp = (u_int32_t *)(optp);
4677 		/* Form timestamp option as shown in appendix A of RFC 1323. */
4678 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
4679 		*lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4680 		*lp   = htonl(sc->sc_timestamp);
4681 		optp += TCPOLEN_TSTAMP_APPA;
4682 	}
4683 
4684 	if (sc->sc_flags & SCF_SACK_PERMIT) {
4685 		u_int8_t *p = optp;
4686 
4687 		/* Let the peer know that we will SACK. */
4688 		p[0] = TCPOPT_SACK_PERMITTED;
4689 		p[1] = 2;
4690 		p[2] = TCPOPT_NOP;
4691 		p[3] = TCPOPT_NOP;
4692 		optp += 4;
4693 	}
4694 
4695 	/*
4696 	 * Send ECN SYN-ACK setup packet.
4697 	 * Routes can be asymetric, so, even if we receive a packet
4698 	 * with ECE and CWR set, we must not assume no one will block
4699 	 * the ECE packet we are about to send.
4700 	 */
4701 	if ((sc->sc_flags & SCF_ECN_PERMIT) && tp &&
4702 	    SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
4703 		th->th_flags |= TH_ECE;
4704 		TCP_STATINC(TCP_STAT_ECN_SHS);
4705 
4706 		/*
4707 		 * draft-ietf-tcpm-ecnsyn-00.txt
4708 		 *
4709 		 * "[...] a TCP node MAY respond to an ECN-setup
4710 		 * SYN packet by setting ECT in the responding
4711 		 * ECN-setup SYN/ACK packet, indicating to routers
4712 		 * that the SYN/ACK packet is ECN-Capable.
4713 		 * This allows a congested router along the path
4714 		 * to mark the packet instead of dropping the
4715 		 * packet as an indication of congestion."
4716 		 *
4717 		 * "[...] There can be a great benefit in setting
4718 		 * an ECN-capable codepoint in SYN/ACK packets [...]
4719 		 * Congestion is  most likely to occur in
4720 		 * the server-to-client direction.  As a result,
4721 		 * setting an ECN-capable codepoint in SYN/ACK
4722 		 * packets can reduce the occurence of three-second
4723 		 * retransmit timeouts resulting from the drop
4724 		 * of SYN/ACK packets."
4725 		 *
4726 		 * Page 4 and 6, January 2006.
4727 		 */
4728 
4729 		switch (sc->sc_src.sa.sa_family) {
4730 #ifdef INET
4731 		case AF_INET:
4732 			ip->ip_tos |= IPTOS_ECN_ECT0;
4733 			break;
4734 #endif
4735 #ifdef INET6
4736 		case AF_INET6:
4737 			ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
4738 			break;
4739 #endif
4740 		}
4741 		TCP_STATINC(TCP_STAT_ECN_ECT);
4742 	}
4743 
4744 #ifdef TCP_SIGNATURE
4745 	if (sc->sc_flags & SCF_SIGNATURE) {
4746 		struct secasvar *sav;
4747 		u_int8_t *sigp;
4748 
4749 		sav = tcp_signature_getsav(m, th);
4750 
4751 		if (sav == NULL) {
4752 			if (m)
4753 				m_freem(m);
4754 			return (EPERM);
4755 		}
4756 
4757 		*optp++ = TCPOPT_SIGNATURE;
4758 		*optp++ = TCPOLEN_SIGNATURE;
4759 		sigp = optp;
4760 		memset(optp, 0, TCP_SIGLEN);
4761 		optp += TCP_SIGLEN;
4762 		*optp++ = TCPOPT_NOP;
4763 		*optp++ = TCPOPT_EOL;
4764 
4765 		(void)tcp_signature(m, th, hlen, sav, sigp);
4766 
4767 		key_sa_recordxfer(sav, m);
4768 #ifdef FAST_IPSEC
4769 		KEY_FREESAV(&sav);
4770 #else
4771 		key_freesav(sav);
4772 #endif
4773 	}
4774 #endif
4775 
4776 	/* Compute the packet's checksum. */
4777 	switch (sc->sc_src.sa.sa_family) {
4778 	case AF_INET:
4779 		ip->ip_len = htons(tlen - hlen);
4780 		th->th_sum = 0;
4781 		th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4782 		break;
4783 #ifdef INET6
4784 	case AF_INET6:
4785 		ip6->ip6_plen = htons(tlen - hlen);
4786 		th->th_sum = 0;
4787 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4788 		break;
4789 #endif
4790 	}
4791 
4792 	/*
4793 	 * Fill in some straggling IP bits.  Note the stack expects
4794 	 * ip_len to be in host order, for convenience.
4795 	 */
4796 	switch (sc->sc_src.sa.sa_family) {
4797 #ifdef INET
4798 	case AF_INET:
4799 		ip->ip_len = htons(tlen);
4800 		ip->ip_ttl = ip_defttl;
4801 		/* XXX tos? */
4802 		break;
4803 #endif
4804 #ifdef INET6
4805 	case AF_INET6:
4806 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4807 		ip6->ip6_vfc |= IPV6_VERSION;
4808 		ip6->ip6_plen = htons(tlen - hlen);
4809 		/* ip6_hlim will be initialized afterwards */
4810 		/* XXX flowlabel? */
4811 		break;
4812 #endif
4813 	}
4814 
4815 	/* XXX use IPsec policy on listening socket, on SYN ACK */
4816 	tp = sc->sc_tp;
4817 
4818 	switch (sc->sc_src.sa.sa_family) {
4819 #ifdef INET
4820 	case AF_INET:
4821 		error = ip_output(m, sc->sc_ipopts, ro,
4822 		    (ip_mtudisc ? IP_MTUDISC : 0),
4823 		    (struct ip_moptions *)NULL, so);
4824 		break;
4825 #endif
4826 #ifdef INET6
4827 	case AF_INET6:
4828 		ip6->ip6_hlim = in6_selecthlim(NULL,
4829 				(rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp
4830 				                                    : NULL);
4831 
4832 		error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL, so, NULL);
4833 		break;
4834 #endif
4835 	default:
4836 		error = EAFNOSUPPORT;
4837 		break;
4838 	}
4839 	return (error);
4840 }
4841