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