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