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