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