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