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