xref: /netbsd-src/sys/netinet/tcp_input.c (revision 5f2f42719cd62ff11fd913b40b7ce19f07c4fd25)
1 /*	$NetBSD: tcp_input.c,v 1.434 2022/09/20 07:19:14 ozaki-r 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 #include <sys/cdefs.h>
141 __KERNEL_RCSID(0, "$NetBSD: tcp_input.c,v 1.434 2022/09/20 07:19:14 ozaki-r Exp $");
142 
143 #ifdef _KERNEL_OPT
144 #include "opt_inet.h"
145 #include "opt_ipsec.h"
146 #include "opt_inet_csum.h"
147 #include "opt_tcp_debug.h"
148 #endif
149 
150 #include <sys/param.h>
151 #include <sys/systm.h>
152 #include <sys/malloc.h>
153 #include <sys/mbuf.h>
154 #include <sys/protosw.h>
155 #include <sys/socket.h>
156 #include <sys/socketvar.h>
157 #include <sys/errno.h>
158 #include <sys/syslog.h>
159 #include <sys/pool.h>
160 #include <sys/domain.h>
161 #include <sys/kernel.h>
162 #ifdef TCP_SIGNATURE
163 #include <sys/md5.h>
164 #endif
165 #include <sys/lwp.h> /* for lwp0 */
166 #include <sys/cprng.h>
167 
168 #include <net/if.h>
169 #include <net/if_types.h>
170 
171 #include <netinet/in.h>
172 #include <netinet/in_systm.h>
173 #include <netinet/ip.h>
174 #include <netinet/in_pcb.h>
175 #include <netinet/in_var.h>
176 #include <netinet/ip_var.h>
177 #include <netinet/in_offload.h>
178 
179 #if NARP > 0
180 #include <netinet/if_inarp.h>
181 #endif
182 #ifdef INET6
183 #include <netinet/ip6.h>
184 #include <netinet6/ip6_var.h>
185 #include <netinet6/in6_pcb.h>
186 #include <netinet6/ip6_var.h>
187 #include <netinet6/in6_var.h>
188 #include <netinet/icmp6.h>
189 #include <netinet6/nd6.h>
190 #ifdef TCP_SIGNATURE
191 #include <netinet6/scope6_var.h>
192 #endif
193 #endif
194 
195 #ifndef INET6
196 #include <netinet/ip6.h>
197 #endif
198 
199 #include <netinet/tcp.h>
200 #include <netinet/tcp_fsm.h>
201 #include <netinet/tcp_seq.h>
202 #include <netinet/tcp_timer.h>
203 #include <netinet/tcp_var.h>
204 #include <netinet/tcp_private.h>
205 #include <netinet/tcp_congctl.h>
206 #include <netinet/tcp_debug.h>
207 #include <netinet/tcp_syncache.h>
208 
209 #ifdef INET6
210 #include "faith.h"
211 #if defined(NFAITH) && NFAITH > 0
212 #include <net/if_faith.h>
213 #endif
214 #endif
215 
216 #ifdef IPSEC
217 #include <netipsec/ipsec.h>
218 #include <netipsec/key.h>
219 #ifdef INET6
220 #include <netipsec/ipsec6.h>
221 #endif
222 #endif	/* IPSEC*/
223 
224 #include <netinet/tcp_vtw.h>
225 
226 int	tcprexmtthresh = 3;
227 int	tcp_log_refused;
228 
229 int	tcp_do_autorcvbuf = 1;
230 int	tcp_autorcvbuf_inc = 16 * 1024;
231 int	tcp_autorcvbuf_max = 256 * 1024;
232 int	tcp_msl = (TCPTV_MSL / PR_SLOWHZ);
233 
234 static int tcp_rst_ppslim_count = 0;
235 static struct timeval tcp_rst_ppslim_last;
236 static int tcp_ackdrop_ppslim_count = 0;
237 static struct timeval tcp_ackdrop_ppslim_last;
238 
239 #define TCP_PAWS_IDLE	(24U * 24 * 60 * 60 * PR_SLOWHZ)
240 
241 /* for modulo comparisons of timestamps */
242 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
243 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
244 
245 /*
246  * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
247  */
248 static void
249 nd_hint(struct tcpcb *tp)
250 {
251 	struct route *ro = NULL;
252 	struct rtentry *rt;
253 
254 	if (tp == NULL)
255 		return;
256 
257 	switch (tp->t_family) {
258 #if NARP > 0
259 	case AF_INET:
260 		if (tp->t_inpcb != NULL)
261 			ro = &tp->t_inpcb->inp_route;
262 		break;
263 #endif
264 #ifdef INET6
265 	case AF_INET6:
266 		if (tp->t_in6pcb != NULL)
267 			ro = &tp->t_in6pcb->in6p_route;
268 		break;
269 #endif
270 	}
271 
272 	if (ro == NULL)
273 		return;
274 
275 	rt = rtcache_validate(ro);
276 	if (rt == NULL)
277 		return;
278 
279 	switch (tp->t_family) {
280 #if NARP > 0
281 	case AF_INET:
282 		arp_nud_hint(rt);
283 		break;
284 #endif
285 #ifdef INET6
286 	case AF_INET6:
287 		nd6_nud_hint(rt);
288 		break;
289 #endif
290 	}
291 
292 	rtcache_unref(rt, ro);
293 }
294 
295 /*
296  * Compute ACK transmission behavior.  Delay the ACK unless
297  * we have already delayed an ACK (must send an ACK every two segments).
298  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
299  * option is enabled.
300  */
301 static void
302 tcp_setup_ack(struct tcpcb *tp, const struct tcphdr *th)
303 {
304 
305 	if (tp->t_flags & TF_DELACK ||
306 	    (tcp_ack_on_push && th->th_flags & TH_PUSH))
307 		tp->t_flags |= TF_ACKNOW;
308 	else
309 		TCP_SET_DELACK(tp);
310 }
311 
312 static void
313 icmp_check(struct tcpcb *tp, const struct tcphdr *th, int acked)
314 {
315 
316 	/*
317 	 * If we had a pending ICMP message that refers to data that have
318 	 * just been acknowledged, disregard the recorded ICMP message.
319 	 */
320 	if ((tp->t_flags & TF_PMTUD_PEND) &&
321 	    SEQ_GT(th->th_ack, tp->t_pmtud_th_seq))
322 		tp->t_flags &= ~TF_PMTUD_PEND;
323 
324 	/*
325 	 * Keep track of the largest chunk of data
326 	 * acknowledged since last PMTU update
327 	 */
328 	if (tp->t_pmtud_mss_acked < acked)
329 		tp->t_pmtud_mss_acked = acked;
330 }
331 
332 /*
333  * Convert TCP protocol fields to host order for easier processing.
334  */
335 static void
336 tcp_fields_to_host(struct tcphdr *th)
337 {
338 
339 	NTOHL(th->th_seq);
340 	NTOHL(th->th_ack);
341 	NTOHS(th->th_win);
342 	NTOHS(th->th_urp);
343 }
344 
345 /*
346  * ... and reverse the above.
347  */
348 static void
349 tcp_fields_to_net(struct tcphdr *th)
350 {
351 
352 	HTONL(th->th_seq);
353 	HTONL(th->th_ack);
354 	HTONS(th->th_win);
355 	HTONS(th->th_urp);
356 }
357 
358 static void
359 tcp_urp_drop(struct tcphdr *th, int todrop, int *tiflags)
360 {
361 	if (th->th_urp > todrop) {
362 		th->th_urp -= todrop;
363 	} else {
364 		*tiflags &= ~TH_URG;
365 		th->th_urp = 0;
366 	}
367 }
368 
369 #ifdef TCP_CSUM_COUNTERS
370 #include <sys/device.h>
371 
372 extern struct evcnt tcp_hwcsum_ok;
373 extern struct evcnt tcp_hwcsum_bad;
374 extern struct evcnt tcp_hwcsum_data;
375 extern struct evcnt tcp_swcsum;
376 #if defined(INET6)
377 extern struct evcnt tcp6_hwcsum_ok;
378 extern struct evcnt tcp6_hwcsum_bad;
379 extern struct evcnt tcp6_hwcsum_data;
380 extern struct evcnt tcp6_swcsum;
381 #endif /* defined(INET6) */
382 
383 #define	TCP_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
384 
385 #else
386 
387 #define	TCP_CSUM_COUNTER_INCR(ev)	/* nothing */
388 
389 #endif /* TCP_CSUM_COUNTERS */
390 
391 #ifdef TCP_REASS_COUNTERS
392 #include <sys/device.h>
393 
394 extern struct evcnt tcp_reass_;
395 extern struct evcnt tcp_reass_empty;
396 extern struct evcnt tcp_reass_iteration[8];
397 extern struct evcnt tcp_reass_prependfirst;
398 extern struct evcnt tcp_reass_prepend;
399 extern struct evcnt tcp_reass_insert;
400 extern struct evcnt tcp_reass_inserttail;
401 extern struct evcnt tcp_reass_append;
402 extern struct evcnt tcp_reass_appendtail;
403 extern struct evcnt tcp_reass_overlaptail;
404 extern struct evcnt tcp_reass_overlapfront;
405 extern struct evcnt tcp_reass_segdup;
406 extern struct evcnt tcp_reass_fragdup;
407 
408 #define	TCP_REASS_COUNTER_INCR(ev)	(ev)->ev_count++
409 
410 #else
411 
412 #define	TCP_REASS_COUNTER_INCR(ev)	/* nothing */
413 
414 #endif /* TCP_REASS_COUNTERS */
415 
416 static int tcp_reass(struct tcpcb *, const struct tcphdr *, struct mbuf *,
417     int);
418 
419 static void tcp4_log_refused(const struct ip *, const struct tcphdr *);
420 #ifdef INET6
421 static void tcp6_log_refused(const struct ip6_hdr *, const struct tcphdr *);
422 #endif
423 
424 #if defined(MBUFTRACE)
425 struct mowner tcp_reass_mowner = MOWNER_INIT("tcp", "reass");
426 #endif /* defined(MBUFTRACE) */
427 
428 static struct pool tcpipqent_pool;
429 
430 void
431 tcpipqent_init(void)
432 {
433 
434 	pool_init(&tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl",
435 	    NULL, IPL_VM);
436 }
437 
438 struct ipqent *
439 tcpipqent_alloc(void)
440 {
441 	struct ipqent *ipqe;
442 	int s;
443 
444 	s = splvm();
445 	ipqe = pool_get(&tcpipqent_pool, PR_NOWAIT);
446 	splx(s);
447 
448 	return ipqe;
449 }
450 
451 void
452 tcpipqent_free(struct ipqent *ipqe)
453 {
454 	int s;
455 
456 	s = splvm();
457 	pool_put(&tcpipqent_pool, ipqe);
458 	splx(s);
459 }
460 
461 /*
462  * Insert segment ti into reassembly queue of tcp with
463  * control block tp.  Return TH_FIN if reassembly now includes
464  * a segment with FIN.
465  */
466 static int
467 tcp_reass(struct tcpcb *tp, const struct tcphdr *th, struct mbuf *m, int tlen)
468 {
469 	struct ipqent *p, *q, *nq, *tiqe = NULL;
470 	struct socket *so = NULL;
471 	int pkt_flags;
472 	tcp_seq pkt_seq;
473 	unsigned pkt_len;
474 	u_long rcvpartdupbyte = 0;
475 	u_long rcvoobyte;
476 #ifdef TCP_REASS_COUNTERS
477 	u_int count = 0;
478 #endif
479 	uint64_t *tcps;
480 
481 	if (tp->t_inpcb)
482 		so = tp->t_inpcb->inp_socket;
483 #ifdef INET6
484 	else if (tp->t_in6pcb)
485 		so = tp->t_in6pcb->in6p_socket;
486 #endif
487 
488 	TCP_REASS_LOCK_CHECK(tp);
489 
490 	/*
491 	 * Call with th==NULL after become established to
492 	 * force pre-ESTABLISHED data up to user socket.
493 	 */
494 	if (th == NULL)
495 		goto present;
496 
497 	m_claimm(m, &tcp_reass_mowner);
498 
499 	rcvoobyte = tlen;
500 	/*
501 	 * Copy these to local variables because the TCP header gets munged
502 	 * while we are collapsing mbufs.
503 	 */
504 	pkt_seq = th->th_seq;
505 	pkt_len = tlen;
506 	pkt_flags = th->th_flags;
507 
508 	TCP_REASS_COUNTER_INCR(&tcp_reass_);
509 
510 	if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) {
511 		/*
512 		 * When we miss a packet, the vast majority of time we get
513 		 * packets that follow it in order.  So optimize for that.
514 		 */
515 		if (pkt_seq == p->ipqe_seq + p->ipqe_len) {
516 			p->ipqe_len += pkt_len;
517 			p->ipqe_flags |= pkt_flags;
518 			m_cat(p->ipqe_m, m);
519 			m = NULL;
520 			tiqe = p;
521 			TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq);
522 			TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail);
523 			goto skip_replacement;
524 		}
525 		/*
526 		 * While we're here, if the pkt is completely beyond
527 		 * anything we have, just insert it at the tail.
528 		 */
529 		if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) {
530 			TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail);
531 			goto insert_it;
532 		}
533 	}
534 
535 	q = TAILQ_FIRST(&tp->segq);
536 
537 	if (q != NULL) {
538 		/*
539 		 * If this segment immediately precedes the first out-of-order
540 		 * block, simply slap the segment in front of it and (mostly)
541 		 * skip the complicated logic.
542 		 */
543 		if (pkt_seq + pkt_len == q->ipqe_seq) {
544 			q->ipqe_seq = pkt_seq;
545 			q->ipqe_len += pkt_len;
546 			q->ipqe_flags |= pkt_flags;
547 			m_cat(m, q->ipqe_m);
548 			q->ipqe_m = m;
549 			tiqe = q;
550 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
551 			TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst);
552 			goto skip_replacement;
553 		}
554 	} else {
555 		TCP_REASS_COUNTER_INCR(&tcp_reass_empty);
556 	}
557 
558 	/*
559 	 * Find a segment which begins after this one does.
560 	 */
561 	for (p = NULL; q != NULL; q = nq) {
562 		nq = TAILQ_NEXT(q, ipqe_q);
563 #ifdef TCP_REASS_COUNTERS
564 		count++;
565 #endif
566 
567 		/*
568 		 * If the received segment is just right after this
569 		 * fragment, merge the two together and then check
570 		 * for further overlaps.
571 		 */
572 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
573 			pkt_len += q->ipqe_len;
574 			pkt_flags |= q->ipqe_flags;
575 			pkt_seq = q->ipqe_seq;
576 			m_cat(q->ipqe_m, m);
577 			m = q->ipqe_m;
578 			TCP_REASS_COUNTER_INCR(&tcp_reass_append);
579 			goto free_ipqe;
580 		}
581 
582 		/*
583 		 * If the received segment is completely past this
584 		 * fragment, we need to go to the next fragment.
585 		 */
586 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
587 			p = q;
588 			continue;
589 		}
590 
591 		/*
592 		 * If the fragment is past the received segment,
593 		 * it (or any following) can't be concatenated.
594 		 */
595 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) {
596 			TCP_REASS_COUNTER_INCR(&tcp_reass_insert);
597 			break;
598 		}
599 
600 		/*
601 		 * We've received all the data in this segment before.
602 		 * Mark it as a duplicate and return.
603 		 */
604 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
605 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
606 			tcps = TCP_STAT_GETREF();
607 			tcps[TCP_STAT_RCVDUPPACK]++;
608 			tcps[TCP_STAT_RCVDUPBYTE] += pkt_len;
609 			TCP_STAT_PUTREF();
610 			tcp_new_dsack(tp, pkt_seq, pkt_len);
611 			m_freem(m);
612 			if (tiqe != NULL) {
613 				tcpipqent_free(tiqe);
614 			}
615 			TCP_REASS_COUNTER_INCR(&tcp_reass_segdup);
616 			goto out;
617 		}
618 
619 		/*
620 		 * Received segment completely overlaps this fragment
621 		 * so we drop the fragment (this keeps the temporal
622 		 * ordering of segments correct).
623 		 */
624 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
625 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
626 			rcvpartdupbyte += q->ipqe_len;
627 			m_freem(q->ipqe_m);
628 			TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup);
629 			goto free_ipqe;
630 		}
631 
632 		/*
633 		 * Received segment extends past the end of the fragment.
634 		 * Drop the overlapping bytes, merge the fragment and
635 		 * segment, and treat as a longer received packet.
636 		 */
637 		if (SEQ_LT(q->ipqe_seq, pkt_seq) &&
638 		    SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
639 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
640 			m_adj(m, overlap);
641 			rcvpartdupbyte += overlap;
642 			m_cat(q->ipqe_m, m);
643 			m = q->ipqe_m;
644 			pkt_seq = q->ipqe_seq;
645 			pkt_len += q->ipqe_len - overlap;
646 			rcvoobyte -= overlap;
647 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail);
648 			goto free_ipqe;
649 		}
650 
651 		/*
652 		 * Received segment extends past the front of the fragment.
653 		 * Drop the overlapping bytes on the received packet. The
654 		 * packet will then be concatenated with this fragment a
655 		 * bit later.
656 		 */
657 		if (SEQ_GT(q->ipqe_seq, pkt_seq) &&
658 		    SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
659 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
660 			m_adj(m, -overlap);
661 			pkt_len -= overlap;
662 			rcvpartdupbyte += overlap;
663 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront);
664 			rcvoobyte -= overlap;
665 		}
666 
667 		/*
668 		 * If the received segment immediately precedes this
669 		 * fragment then tack the fragment onto this segment
670 		 * and reinsert the data.
671 		 */
672 		if (q->ipqe_seq == pkt_seq + pkt_len) {
673 			pkt_len += q->ipqe_len;
674 			pkt_flags |= q->ipqe_flags;
675 			m_cat(m, q->ipqe_m);
676 			TAILQ_REMOVE(&tp->segq, q, ipqe_q);
677 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
678 			tp->t_segqlen--;
679 			KASSERT(tp->t_segqlen >= 0);
680 			KASSERT(tp->t_segqlen != 0 ||
681 			    (TAILQ_EMPTY(&tp->segq) &&
682 			    TAILQ_EMPTY(&tp->timeq)));
683 			if (tiqe == NULL) {
684 				tiqe = q;
685 			} else {
686 				tcpipqent_free(q);
687 			}
688 			TCP_REASS_COUNTER_INCR(&tcp_reass_prepend);
689 			break;
690 		}
691 
692 		/*
693 		 * If the fragment is before the segment, remember it.
694 		 * When this loop is terminated, p will contain the
695 		 * pointer to the fragment that is right before the
696 		 * received segment.
697 		 */
698 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
699 			p = q;
700 
701 		continue;
702 
703 		/*
704 		 * This is a common operation.  It also will allow
705 		 * to save doing a malloc/free in most instances.
706 		 */
707 	  free_ipqe:
708 		TAILQ_REMOVE(&tp->segq, q, ipqe_q);
709 		TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
710 		tp->t_segqlen--;
711 		KASSERT(tp->t_segqlen >= 0);
712 		KASSERT(tp->t_segqlen != 0 ||
713 		    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
714 		if (tiqe == NULL) {
715 			tiqe = q;
716 		} else {
717 			tcpipqent_free(q);
718 		}
719 	}
720 
721 #ifdef TCP_REASS_COUNTERS
722 	if (count > 7)
723 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]);
724 	else if (count > 0)
725 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]);
726 #endif
727 
728 insert_it:
729 	/*
730 	 * Allocate a new queue entry (block) since the received segment
731 	 * did not collapse onto any other out-of-order block. If it had
732 	 * collapsed, tiqe would not be NULL and we would be reusing it.
733 	 *
734 	 * If the allocation fails, drop the packet.
735 	 */
736 	if (tiqe == NULL) {
737 		tiqe = tcpipqent_alloc();
738 		if (tiqe == NULL) {
739 			TCP_STATINC(TCP_STAT_RCVMEMDROP);
740 			m_freem(m);
741 			goto out;
742 		}
743 	}
744 
745 	/*
746 	 * Update the counters.
747 	 */
748 	tp->t_rcvoopack++;
749 	tcps = TCP_STAT_GETREF();
750 	tcps[TCP_STAT_RCVOOPACK]++;
751 	tcps[TCP_STAT_RCVOOBYTE] += rcvoobyte;
752 	if (rcvpartdupbyte) {
753 	    tcps[TCP_STAT_RCVPARTDUPPACK]++;
754 	    tcps[TCP_STAT_RCVPARTDUPBYTE] += rcvpartdupbyte;
755 	}
756 	TCP_STAT_PUTREF();
757 
758 	/*
759 	 * Insert the new fragment queue entry into both queues.
760 	 */
761 	tiqe->ipqe_m = m;
762 	tiqe->ipqe_seq = pkt_seq;
763 	tiqe->ipqe_len = pkt_len;
764 	tiqe->ipqe_flags = pkt_flags;
765 	if (p == NULL) {
766 		TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
767 	} else {
768 		TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q);
769 	}
770 	tp->t_segqlen++;
771 
772 skip_replacement:
773 	TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
774 
775 present:
776 	/*
777 	 * Present data to user, advancing rcv_nxt through
778 	 * completed sequence space.
779 	 */
780 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
781 		goto out;
782 	q = TAILQ_FIRST(&tp->segq);
783 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
784 		goto out;
785 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
786 		goto out;
787 
788 	tp->rcv_nxt += q->ipqe_len;
789 	pkt_flags = q->ipqe_flags & TH_FIN;
790 	nd_hint(tp);
791 
792 	TAILQ_REMOVE(&tp->segq, q, ipqe_q);
793 	TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
794 	tp->t_segqlen--;
795 	KASSERT(tp->t_segqlen >= 0);
796 	KASSERT(tp->t_segqlen != 0 ||
797 	    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
798 	if (so->so_state & SS_CANTRCVMORE)
799 		m_freem(q->ipqe_m);
800 	else
801 		sbappendstream(&so->so_rcv, q->ipqe_m);
802 	tcpipqent_free(q);
803 	TCP_REASS_UNLOCK(tp);
804 	sorwakeup(so);
805 	return pkt_flags;
806 
807 out:
808 	TCP_REASS_UNLOCK(tp);
809 	return 0;
810 }
811 
812 #ifdef INET6
813 int
814 tcp6_input(struct mbuf **mp, int *offp, int proto)
815 {
816 	struct mbuf *m = *mp;
817 
818 	/*
819 	 * draft-itojun-ipv6-tcp-to-anycast
820 	 * better place to put this in?
821 	 */
822 	if (m->m_flags & M_ANYCAST6) {
823 		struct ip6_hdr *ip6;
824 		if (m->m_len < sizeof(struct ip6_hdr)) {
825 			if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
826 				TCP_STATINC(TCP_STAT_RCVSHORT);
827 				return IPPROTO_DONE;
828 			}
829 		}
830 		ip6 = mtod(m, struct ip6_hdr *);
831 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
832 		    (char *)&ip6->ip6_dst - (char *)ip6);
833 		return IPPROTO_DONE;
834 	}
835 
836 	tcp_input(m, *offp, proto);
837 	return IPPROTO_DONE;
838 }
839 #endif
840 
841 static void
842 tcp4_log_refused(const struct ip *ip, const struct tcphdr *th)
843 {
844 	char src[INET_ADDRSTRLEN];
845 	char dst[INET_ADDRSTRLEN];
846 
847 	if (ip) {
848 		in_print(src, sizeof(src), &ip->ip_src);
849 		in_print(dst, sizeof(dst), &ip->ip_dst);
850 	} else {
851 		strlcpy(src, "(unknown)", sizeof(src));
852 		strlcpy(dst, "(unknown)", sizeof(dst));
853 	}
854 	log(LOG_INFO,
855 	    "Connection attempt to TCP %s:%d from %s:%d\n",
856 	    dst, ntohs(th->th_dport),
857 	    src, ntohs(th->th_sport));
858 }
859 
860 #ifdef INET6
861 static void
862 tcp6_log_refused(const struct ip6_hdr *ip6, const struct tcphdr *th)
863 {
864 	char src[INET6_ADDRSTRLEN];
865 	char dst[INET6_ADDRSTRLEN];
866 
867 	if (ip6) {
868 		in6_print(src, sizeof(src), &ip6->ip6_src);
869 		in6_print(dst, sizeof(dst), &ip6->ip6_dst);
870 	} else {
871 		strlcpy(src, "(unknown v6)", sizeof(src));
872 		strlcpy(dst, "(unknown v6)", sizeof(dst));
873 	}
874 	log(LOG_INFO,
875 	    "Connection attempt to TCP [%s]:%d from [%s]:%d\n",
876 	    dst, ntohs(th->th_dport),
877 	    src, ntohs(th->th_sport));
878 }
879 #endif
880 
881 /*
882  * Checksum extended TCP header and data.
883  */
884 int
885 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th,
886     int toff, int off, int tlen)
887 {
888 	struct ifnet *rcvif;
889 	int s;
890 
891 	/*
892 	 * XXX it's better to record and check if this mbuf is
893 	 * already checked.
894 	 */
895 
896 	rcvif = m_get_rcvif(m, &s);
897 	if (__predict_false(rcvif == NULL))
898 		goto badcsum; /* XXX */
899 
900 	switch (af) {
901 	case AF_INET:
902 		switch (m->m_pkthdr.csum_flags &
903 			((rcvif->if_csum_flags_rx & M_CSUM_TCPv4) |
904 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
905 		case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD:
906 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad);
907 			goto badcsum;
908 
909 		case M_CSUM_TCPv4|M_CSUM_DATA: {
910 			u_int32_t hw_csum = m->m_pkthdr.csum_data;
911 
912 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data);
913 			if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) {
914 				const struct ip *ip =
915 				    mtod(m, const struct ip *);
916 
917 				hw_csum = in_cksum_phdr(ip->ip_src.s_addr,
918 				    ip->ip_dst.s_addr,
919 				    htons(hw_csum + tlen + off + IPPROTO_TCP));
920 			}
921 			if ((hw_csum ^ 0xffff) != 0)
922 				goto badcsum;
923 			break;
924 		}
925 
926 		case M_CSUM_TCPv4:
927 			/* Checksum was okay. */
928 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok);
929 			break;
930 
931 		default:
932 			/*
933 			 * Must compute it ourselves.  Maybe skip checksum
934 			 * on loopback interfaces.
935 			 */
936 			if (__predict_true(!(rcvif->if_flags & IFF_LOOPBACK) ||
937 					   tcp_do_loopback_cksum)) {
938 				TCP_CSUM_COUNTER_INCR(&tcp_swcsum);
939 				if (in4_cksum(m, IPPROTO_TCP, toff,
940 					      tlen + off) != 0)
941 					goto badcsum;
942 			}
943 			break;
944 		}
945 		break;
946 
947 #ifdef INET6
948 	case AF_INET6:
949 		switch (m->m_pkthdr.csum_flags &
950 			((rcvif->if_csum_flags_rx & M_CSUM_TCPv6) |
951 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
952 		case M_CSUM_TCPv6|M_CSUM_TCP_UDP_BAD:
953 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_bad);
954 			goto badcsum;
955 
956 #if 0 /* notyet */
957 		case M_CSUM_TCPv6|M_CSUM_DATA:
958 #endif
959 
960 		case M_CSUM_TCPv6:
961 			/* Checksum was okay. */
962 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_ok);
963 			break;
964 
965 		default:
966 			/*
967 			 * Must compute it ourselves.  Maybe skip checksum
968 			 * on loopback interfaces.
969 			 */
970 			if (__predict_true((m->m_flags & M_LOOP) == 0 ||
971 			    tcp_do_loopback_cksum)) {
972 				TCP_CSUM_COUNTER_INCR(&tcp6_swcsum);
973 				if (in6_cksum(m, IPPROTO_TCP, toff,
974 				    tlen + off) != 0)
975 					goto badcsum;
976 			}
977 		}
978 		break;
979 #endif /* INET6 */
980 	}
981 	m_put_rcvif(rcvif, &s);
982 
983 	return 0;
984 
985 badcsum:
986 	m_put_rcvif(rcvif, &s);
987 	TCP_STATINC(TCP_STAT_RCVBADSUM);
988 	return -1;
989 }
990 
991 /*
992  * When a packet arrives addressed to a vestigial tcpbp, we
993  * nevertheless have to respond to it per the spec.
994  *
995  * This code is duplicated from the one in tcp_input().
996  */
997 static void tcp_vtw_input(struct tcphdr *th, vestigial_inpcb_t *vp,
998     struct mbuf *m, int tlen)
999 {
1000 	int tiflags;
1001 	int todrop;
1002 	uint32_t t_flags = 0;
1003 	uint64_t *tcps;
1004 
1005 	tiflags = th->th_flags;
1006 	todrop  = vp->rcv_nxt - th->th_seq;
1007 
1008 	if (todrop > 0) {
1009 		if (tiflags & TH_SYN) {
1010 			tiflags &= ~TH_SYN;
1011 			th->th_seq++;
1012 			tcp_urp_drop(th, 1, &tiflags);
1013 			todrop--;
1014 		}
1015 		if (todrop > tlen ||
1016 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1017 			/*
1018 			 * Any valid FIN or RST must be to the left of the
1019 			 * window.  At this point the FIN or RST must be a
1020 			 * duplicate or out of sequence; drop it.
1021 			 */
1022 			if (tiflags & TH_RST)
1023 				goto drop;
1024 			tiflags &= ~(TH_FIN|TH_RST);
1025 
1026 			/*
1027 			 * Send an ACK to resynchronize and drop any data.
1028 			 * But keep on processing for RST or ACK.
1029 			 */
1030 			t_flags |= TF_ACKNOW;
1031 			todrop = tlen;
1032 			tcps = TCP_STAT_GETREF();
1033 			tcps[TCP_STAT_RCVDUPPACK] += 1;
1034 			tcps[TCP_STAT_RCVDUPBYTE] += todrop;
1035 			TCP_STAT_PUTREF();
1036 		} else if ((tiflags & TH_RST) &&
1037 		    th->th_seq != vp->rcv_nxt) {
1038 			/*
1039 			 * Test for reset before adjusting the sequence
1040 			 * number for overlapping data.
1041 			 */
1042 			goto dropafterack_ratelim;
1043 		} else {
1044 			tcps = TCP_STAT_GETREF();
1045 			tcps[TCP_STAT_RCVPARTDUPPACK] += 1;
1046 			tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
1047 			TCP_STAT_PUTREF();
1048 		}
1049 
1050 //		tcp_new_dsack(tp, th->th_seq, todrop);
1051 //		hdroptlen += todrop;	/*drop from head afterwards*/
1052 
1053 		th->th_seq += todrop;
1054 		tlen -= todrop;
1055 		tcp_urp_drop(th, todrop, &tiflags);
1056 	}
1057 
1058 	/*
1059 	 * If new data are received on a connection after the
1060 	 * user processes are gone, then RST the other end.
1061 	 */
1062 	if (tlen) {
1063 		TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
1064 		goto dropwithreset;
1065 	}
1066 
1067 	/*
1068 	 * If segment ends after window, drop trailing data
1069 	 * (and PUSH and FIN); if nothing left, just ACK.
1070 	 */
1071 	todrop = (th->th_seq + tlen) - (vp->rcv_nxt + vp->rcv_wnd);
1072 
1073 	if (todrop > 0) {
1074 		TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
1075 		if (todrop >= tlen) {
1076 			/*
1077 			 * The segment actually starts after the window.
1078 			 * th->th_seq + tlen - vp->rcv_nxt - vp->rcv_wnd >= tlen
1079 			 * th->th_seq - vp->rcv_nxt - vp->rcv_wnd >= 0
1080 			 * th->th_seq >= vp->rcv_nxt + vp->rcv_wnd
1081 			 */
1082 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
1083 
1084 			/*
1085 			 * If a new connection request is received
1086 			 * while in TIME_WAIT, drop the old connection
1087 			 * and start over if the sequence numbers
1088 			 * are above the previous ones.
1089 			 */
1090 			if ((tiflags & TH_SYN) &&
1091 			    SEQ_GT(th->th_seq, vp->rcv_nxt)) {
1092 				/*
1093 				 * We only support this in the !NOFDREF case, which
1094 				 * is to say: not here.
1095 				 */
1096 				goto dropwithreset;
1097 			}
1098 
1099 			/*
1100 			 * If window is closed can only take segments at
1101 			 * window edge, and have to drop data and PUSH from
1102 			 * incoming segments.  Continue processing, but
1103 			 * remember to ack.  Otherwise, drop segment
1104 			 * and (if not RST) ack.
1105 			 */
1106 			if (vp->rcv_wnd == 0 && th->th_seq == vp->rcv_nxt) {
1107 				t_flags |= TF_ACKNOW;
1108 				TCP_STATINC(TCP_STAT_RCVWINPROBE);
1109 			} else {
1110 				goto dropafterack;
1111 			}
1112 		} else {
1113 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
1114 		}
1115 		m_adj(m, -todrop);
1116 		tlen -= todrop;
1117 		tiflags &= ~(TH_PUSH|TH_FIN);
1118 	}
1119 
1120 	if (tiflags & TH_RST) {
1121 		if (th->th_seq != vp->rcv_nxt)
1122 			goto dropafterack_ratelim;
1123 
1124 		vtw_del(vp->ctl, vp->vtw);
1125 		goto drop;
1126 	}
1127 
1128 	/*
1129 	 * If the ACK bit is off we drop the segment and return.
1130 	 */
1131 	if ((tiflags & TH_ACK) == 0) {
1132 		if (t_flags & TF_ACKNOW)
1133 			goto dropafterack;
1134 		goto drop;
1135 	}
1136 
1137 	/*
1138 	 * In TIME_WAIT state the only thing that should arrive
1139 	 * is a retransmission of the remote FIN.  Acknowledge
1140 	 * it and restart the finack timer.
1141 	 */
1142 	vtw_restart(vp);
1143 	goto dropafterack;
1144 
1145 dropafterack:
1146 	/*
1147 	 * Generate an ACK dropping incoming segment if it occupies
1148 	 * sequence space, where the ACK reflects our state.
1149 	 */
1150 	if (tiflags & TH_RST)
1151 		goto drop;
1152 	goto dropafterack2;
1153 
1154 dropafterack_ratelim:
1155 	/*
1156 	 * We may want to rate-limit ACKs against SYN/RST attack.
1157 	 */
1158 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
1159 	    tcp_ackdrop_ppslim) == 0) {
1160 		/* XXX stat */
1161 		goto drop;
1162 	}
1163 	/* ...fall into dropafterack2... */
1164 
1165 dropafterack2:
1166 	(void)tcp_respond(0, m, m, th, th->th_seq + tlen, th->th_ack, TH_ACK);
1167 	return;
1168 
1169 dropwithreset:
1170 	/*
1171 	 * Generate a RST, dropping incoming segment.
1172 	 * Make ACK acceptable to originator of segment.
1173 	 */
1174 	if (tiflags & TH_RST)
1175 		goto drop;
1176 
1177 	if (tiflags & TH_ACK) {
1178 		tcp_respond(0, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
1179 	} else {
1180 		if (tiflags & TH_SYN)
1181 			++tlen;
1182 		(void)tcp_respond(0, m, m, th, th->th_seq + tlen, (tcp_seq)0,
1183 		    TH_RST|TH_ACK);
1184 	}
1185 	return;
1186 drop:
1187 	m_freem(m);
1188 }
1189 
1190 /*
1191  * TCP input routine, follows pages 65-76 of RFC 793 very closely.
1192  */
1193 void
1194 tcp_input(struct mbuf *m, int off, int proto)
1195 {
1196 	struct tcphdr *th;
1197 	struct ip *ip;
1198 	struct inpcb *inp;
1199 #ifdef INET6
1200 	struct ip6_hdr *ip6;
1201 	struct in6pcb *in6p;
1202 #endif
1203 	u_int8_t *optp = NULL;
1204 	int optlen = 0;
1205 	int len, tlen, hdroptlen = 0;
1206 	struct tcpcb *tp = NULL;
1207 	int tiflags;
1208 	struct socket *so = NULL;
1209 	int todrop, acked, ourfinisacked, needoutput = 0;
1210 	bool dupseg;
1211 #ifdef TCP_DEBUG
1212 	short ostate = 0;
1213 #endif
1214 	u_long tiwin;
1215 	struct tcp_opt_info opti;
1216 	int thlen, iphlen;
1217 	int af;		/* af on the wire */
1218 	struct mbuf *tcp_saveti = NULL;
1219 	uint32_t ts_rtt;
1220 	uint8_t iptos;
1221 	uint64_t *tcps;
1222 	vestigial_inpcb_t vestige;
1223 
1224 	vestige.valid = 0;
1225 
1226 	MCLAIM(m, &tcp_rx_mowner);
1227 
1228 	TCP_STATINC(TCP_STAT_RCVTOTAL);
1229 
1230 	memset(&opti, 0, sizeof(opti));
1231 	opti.ts_present = 0;
1232 	opti.maxseg = 0;
1233 
1234 	/*
1235 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
1236 	 *
1237 	 * TCP is, by definition, unicast, so we reject all
1238 	 * multicast outright.
1239 	 *
1240 	 * Note, there are additional src/dst address checks in
1241 	 * the AF-specific code below.
1242 	 */
1243 	if (m->m_flags & (M_BCAST|M_MCAST)) {
1244 		/* XXX stat */
1245 		goto drop;
1246 	}
1247 #ifdef INET6
1248 	if (m->m_flags & M_ANYCAST6) {
1249 		/* XXX stat */
1250 		goto drop;
1251 	}
1252 #endif
1253 
1254 	M_REGION_GET(th, struct tcphdr *, m, off, sizeof(struct tcphdr));
1255 	if (th == NULL) {
1256 		TCP_STATINC(TCP_STAT_RCVSHORT);
1257 		return;
1258 	}
1259 
1260 	/*
1261 	 * Enforce alignment requirements that are violated in
1262 	 * some cases, see kern/50766 for details.
1263 	 */
1264 	if (ACCESSIBLE_POINTER(th, struct tcphdr) == 0) {
1265 		m = m_copyup(m, off + sizeof(struct tcphdr), 0);
1266 		if (m == NULL) {
1267 			TCP_STATINC(TCP_STAT_RCVSHORT);
1268 			return;
1269 		}
1270 		th = (struct tcphdr *)(mtod(m, char *) + off);
1271 	}
1272 	KASSERT(ACCESSIBLE_POINTER(th, struct tcphdr));
1273 
1274 	/*
1275 	 * Get IP and TCP header.
1276 	 * Note: IP leaves IP header in first mbuf.
1277 	 */
1278 	ip = mtod(m, struct ip *);
1279 #ifdef INET6
1280 	ip6 = mtod(m, struct ip6_hdr *);
1281 #endif
1282 	switch (ip->ip_v) {
1283 	case 4:
1284 		af = AF_INET;
1285 		iphlen = sizeof(struct ip);
1286 
1287 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1288 		    in_broadcast(ip->ip_dst, m_get_rcvif_NOMPSAFE(m)))
1289 			goto drop;
1290 
1291 		/* We do the checksum after PCB lookup... */
1292 		len = ntohs(ip->ip_len);
1293 		tlen = len - off;
1294 		iptos = ip->ip_tos;
1295 		break;
1296 #ifdef INET6
1297 	case 6:
1298 		iphlen = sizeof(struct ip6_hdr);
1299 		af = AF_INET6;
1300 
1301 		/*
1302 		 * Be proactive about unspecified IPv6 address in source.
1303 		 * As we use all-zero to indicate unbounded/unconnected pcb,
1304 		 * unspecified IPv6 address can be used to confuse us.
1305 		 *
1306 		 * Note that packets with unspecified IPv6 destination is
1307 		 * already dropped in ip6_input.
1308 		 */
1309 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1310 			/* XXX stat */
1311 			goto drop;
1312 		}
1313 
1314 		/*
1315 		 * Make sure destination address is not multicast.
1316 		 * Source address checked in ip6_input().
1317 		 */
1318 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1319 			/* XXX stat */
1320 			goto drop;
1321 		}
1322 
1323 		/* We do the checksum after PCB lookup... */
1324 		len = m->m_pkthdr.len;
1325 		tlen = len - off;
1326 		iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1327 		break;
1328 #endif
1329 	default:
1330 		m_freem(m);
1331 		return;
1332 	}
1333 
1334 
1335 	/*
1336 	 * Check that TCP offset makes sense, pull out TCP options and
1337 	 * adjust length.
1338 	 */
1339 	thlen = th->th_off << 2;
1340 	if (thlen < sizeof(struct tcphdr) || thlen > tlen) {
1341 		TCP_STATINC(TCP_STAT_RCVBADOFF);
1342 		goto drop;
1343 	}
1344 	tlen -= thlen;
1345 
1346 	if (thlen > sizeof(struct tcphdr)) {
1347 		M_REGION_GET(th, struct tcphdr *, m, off, thlen);
1348 		if (th == NULL) {
1349 			TCP_STATINC(TCP_STAT_RCVSHORT);
1350 			return;
1351 		}
1352 		KASSERT(ACCESSIBLE_POINTER(th, struct tcphdr));
1353 		optlen = thlen - sizeof(struct tcphdr);
1354 		optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1355 
1356 		/*
1357 		 * Do quick retrieval of timestamp options.
1358 		 *
1359 		 * If timestamp is the only option and it's formatted as
1360 		 * recommended in RFC 1323 appendix A, we quickly get the
1361 		 * values now and don't bother calling tcp_dooptions(),
1362 		 * etc.
1363 		 */
1364 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
1365 		     (optlen > TCPOLEN_TSTAMP_APPA &&
1366 		      optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1367 		    be32dec(optp) == TCPOPT_TSTAMP_HDR &&
1368 		    (th->th_flags & TH_SYN) == 0) {
1369 			opti.ts_present = 1;
1370 			opti.ts_val = be32dec(optp + 4);
1371 			opti.ts_ecr = be32dec(optp + 8);
1372 			optp = NULL;	/* we've parsed the options */
1373 		}
1374 	}
1375 	tiflags = th->th_flags;
1376 
1377 	/*
1378 	 * Checksum extended TCP header and data
1379 	 */
1380 	if (tcp_input_checksum(af, m, th, off, thlen, tlen))
1381 		goto badcsum;
1382 
1383 	/*
1384 	 * Locate pcb for segment.
1385 	 */
1386 findpcb:
1387 	inp = NULL;
1388 #ifdef INET6
1389 	in6p = NULL;
1390 #endif
1391 	switch (af) {
1392 	case AF_INET:
1393 		inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1394 		    ip->ip_dst, th->th_dport, &vestige);
1395 		if (inp == NULL && !vestige.valid) {
1396 			TCP_STATINC(TCP_STAT_PCBHASHMISS);
1397 			inp = in_pcblookup_bind(&tcbtable, ip->ip_dst,
1398 			    th->th_dport);
1399 		}
1400 #ifdef INET6
1401 		if (inp == NULL && !vestige.valid) {
1402 			struct in6_addr s, d;
1403 
1404 			/* mapped addr case */
1405 			in6_in_2_v4mapin6(&ip->ip_src, &s);
1406 			in6_in_2_v4mapin6(&ip->ip_dst, &d);
1407 			in6p = in6_pcblookup_connect(&tcbtable, &s,
1408 			    th->th_sport, &d, th->th_dport, 0, &vestige);
1409 			if (in6p == 0 && !vestige.valid) {
1410 				TCP_STATINC(TCP_STAT_PCBHASHMISS);
1411 				in6p = in6_pcblookup_bind(&tcbtable, &d,
1412 				    th->th_dport, 0);
1413 			}
1414 		}
1415 #endif
1416 #ifndef INET6
1417 		if (inp == NULL && !vestige.valid)
1418 #else
1419 		if (inp == NULL && in6p == NULL && !vestige.valid)
1420 #endif
1421 		{
1422 			TCP_STATINC(TCP_STAT_NOPORT);
1423 			if (tcp_log_refused &&
1424 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1425 				tcp4_log_refused(ip, th);
1426 			}
1427 			tcp_fields_to_host(th);
1428 			goto dropwithreset_ratelim;
1429 		}
1430 #if defined(IPSEC)
1431 		if (ipsec_used) {
1432 			if (inp && ipsec_in_reject(m, inp)) {
1433 				goto drop;
1434 			}
1435 #ifdef INET6
1436 			else if (in6p && ipsec_in_reject(m, in6p)) {
1437 				goto drop;
1438 			}
1439 #endif
1440 		}
1441 #endif /*IPSEC*/
1442 		break;
1443 #ifdef INET6
1444 	case AF_INET6:
1445 	    {
1446 		int faith;
1447 
1448 #if defined(NFAITH) && NFAITH > 0
1449 		faith = faithprefix(&ip6->ip6_dst);
1450 #else
1451 		faith = 0;
1452 #endif
1453 		in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1454 		    th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
1455 		if (!in6p && !vestige.valid) {
1456 			TCP_STATINC(TCP_STAT_PCBHASHMISS);
1457 			in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1458 			    th->th_dport, faith);
1459 		}
1460 		if (!in6p && !vestige.valid) {
1461 			TCP_STATINC(TCP_STAT_NOPORT);
1462 			if (tcp_log_refused &&
1463 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1464 				tcp6_log_refused(ip6, th);
1465 			}
1466 			tcp_fields_to_host(th);
1467 			goto dropwithreset_ratelim;
1468 		}
1469 #if defined(IPSEC)
1470 		if (ipsec_used && in6p && ipsec_in_reject(m, in6p)) {
1471 			goto drop;
1472 		}
1473 #endif
1474 		break;
1475 	    }
1476 #endif
1477 	}
1478 
1479 	tcp_fields_to_host(th);
1480 
1481 	/*
1482 	 * If the state is CLOSED (i.e., TCB does not exist) then
1483 	 * all data in the incoming segment is discarded.
1484 	 * If the TCB exists but is in CLOSED state, it is embryonic,
1485 	 * but should either do a listen or a connect soon.
1486 	 */
1487 	tp = NULL;
1488 	so = NULL;
1489 	if (inp) {
1490 		/* Check the minimum TTL for socket. */
1491 		if (ip->ip_ttl < inp->inp_ip_minttl)
1492 			goto drop;
1493 
1494 		tp = intotcpcb(inp);
1495 		so = inp->inp_socket;
1496 	}
1497 #ifdef INET6
1498 	else if (in6p) {
1499 		tp = in6totcpcb(in6p);
1500 		so = in6p->in6p_socket;
1501 	}
1502 #endif
1503 	else if (vestige.valid) {
1504 		/* We do not support the resurrection of vtw tcpcps. */
1505 		tcp_vtw_input(th, &vestige, m, tlen);
1506 		m = NULL;
1507 		goto drop;
1508 	}
1509 
1510 	if (tp == NULL)
1511 		goto dropwithreset_ratelim;
1512 	if (tp->t_state == TCPS_CLOSED)
1513 		goto drop;
1514 
1515 	KASSERT(so->so_lock == softnet_lock);
1516 	KASSERT(solocked(so));
1517 
1518 	/* Unscale the window into a 32-bit value. */
1519 	if ((tiflags & TH_SYN) == 0)
1520 		tiwin = th->th_win << tp->snd_scale;
1521 	else
1522 		tiwin = th->th_win;
1523 
1524 #ifdef INET6
1525 	/* save packet options if user wanted */
1526 	if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1527 		if (in6p->in6p_options) {
1528 			m_freem(in6p->in6p_options);
1529 			in6p->in6p_options = NULL;
1530 		}
1531 		ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1532 	}
1533 #endif
1534 
1535 	if (so->so_options & SO_DEBUG) {
1536 #ifdef TCP_DEBUG
1537 		ostate = tp->t_state;
1538 #endif
1539 
1540 		tcp_saveti = NULL;
1541 		if (iphlen + sizeof(struct tcphdr) > MHLEN)
1542 			goto nosave;
1543 
1544 		if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1545 			tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1546 			if (tcp_saveti == NULL)
1547 				goto nosave;
1548 		} else {
1549 			MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1550 			if (tcp_saveti == NULL)
1551 				goto nosave;
1552 			MCLAIM(m, &tcp_mowner);
1553 			tcp_saveti->m_len = iphlen;
1554 			m_copydata(m, 0, iphlen,
1555 			    mtod(tcp_saveti, void *));
1556 		}
1557 
1558 		if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1559 			m_freem(tcp_saveti);
1560 			tcp_saveti = NULL;
1561 		} else {
1562 			tcp_saveti->m_len += sizeof(struct tcphdr);
1563 			memcpy(mtod(tcp_saveti, char *) + iphlen, th,
1564 			    sizeof(struct tcphdr));
1565 		}
1566 nosave:;
1567 	}
1568 
1569 	if (so->so_options & SO_ACCEPTCONN) {
1570 		union syn_cache_sa src;
1571 		union syn_cache_sa dst;
1572 
1573 		KASSERT(tp->t_state == TCPS_LISTEN);
1574 
1575 		memset(&src, 0, sizeof(src));
1576 		memset(&dst, 0, sizeof(dst));
1577 		switch (af) {
1578 		case AF_INET:
1579 			src.sin.sin_len = sizeof(struct sockaddr_in);
1580 			src.sin.sin_family = AF_INET;
1581 			src.sin.sin_addr = ip->ip_src;
1582 			src.sin.sin_port = th->th_sport;
1583 
1584 			dst.sin.sin_len = sizeof(struct sockaddr_in);
1585 			dst.sin.sin_family = AF_INET;
1586 			dst.sin.sin_addr = ip->ip_dst;
1587 			dst.sin.sin_port = th->th_dport;
1588 			break;
1589 #ifdef INET6
1590 		case AF_INET6:
1591 			src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1592 			src.sin6.sin6_family = AF_INET6;
1593 			src.sin6.sin6_addr = ip6->ip6_src;
1594 			src.sin6.sin6_port = th->th_sport;
1595 
1596 			dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1597 			dst.sin6.sin6_family = AF_INET6;
1598 			dst.sin6.sin6_addr = ip6->ip6_dst;
1599 			dst.sin6.sin6_port = th->th_dport;
1600 			break;
1601 #endif
1602 		}
1603 
1604 		if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1605 			if (tiflags & TH_RST) {
1606 				syn_cache_reset(&src.sa, &dst.sa, th);
1607 			} else if ((tiflags & (TH_ACK|TH_SYN)) ==
1608 			    (TH_ACK|TH_SYN)) {
1609 				/*
1610 				 * Received a SYN,ACK. This should never
1611 				 * happen while we are in LISTEN. Send an RST.
1612 				 */
1613 				goto badsyn;
1614 			} else if (tiflags & TH_ACK) {
1615 				so = syn_cache_get(&src.sa, &dst.sa, th, so, m);
1616 				if (so == NULL) {
1617 					/*
1618 					 * We don't have a SYN for this ACK;
1619 					 * send an RST.
1620 					 */
1621 					goto badsyn;
1622 				} else if (so == (struct socket *)(-1)) {
1623 					/*
1624 					 * We were unable to create the
1625 					 * connection. If the 3-way handshake
1626 					 * was completed, and RST has been
1627 					 * sent to the peer. Since the mbuf
1628 					 * might be in use for the reply, do
1629 					 * not free it.
1630 					 */
1631 					m = NULL;
1632 				} else {
1633 					/*
1634 					 * We have created a full-blown
1635 					 * connection.
1636 					 */
1637 					tp = NULL;
1638 					inp = NULL;
1639 #ifdef INET6
1640 					in6p = NULL;
1641 #endif
1642 					switch (so->so_proto->pr_domain->dom_family) {
1643 					case AF_INET:
1644 						inp = sotoinpcb(so);
1645 						tp = intotcpcb(inp);
1646 						break;
1647 #ifdef INET6
1648 					case AF_INET6:
1649 						in6p = sotoin6pcb(so);
1650 						tp = in6totcpcb(in6p);
1651 						break;
1652 #endif
1653 					}
1654 					if (tp == NULL)
1655 						goto badsyn;	/*XXX*/
1656 					tiwin <<= tp->snd_scale;
1657 					goto after_listen;
1658 				}
1659 			} else {
1660 				/*
1661 				 * None of RST, SYN or ACK was set.
1662 				 * This is an invalid packet for a
1663 				 * TCB in LISTEN state.  Send a RST.
1664 				 */
1665 				goto badsyn;
1666 			}
1667 		} else {
1668 			/*
1669 			 * Received a SYN.
1670 			 */
1671 
1672 #ifdef INET6
1673 			/*
1674 			 * If deprecated address is forbidden, we do
1675 			 * not accept SYN to deprecated interface
1676 			 * address to prevent any new inbound
1677 			 * connection from getting established.
1678 			 * When we do not accept SYN, we send a TCP
1679 			 * RST, with deprecated source address (instead
1680 			 * of dropping it).  We compromise it as it is
1681 			 * much better for peer to send a RST, and
1682 			 * RST will be the final packet for the
1683 			 * exchange.
1684 			 *
1685 			 * If we do not forbid deprecated addresses, we
1686 			 * accept the SYN packet.  RFC2462 does not
1687 			 * suggest dropping SYN in this case.
1688 			 * If we decipher RFC2462 5.5.4, it says like
1689 			 * this:
1690 			 * 1. use of deprecated addr with existing
1691 			 *    communication is okay - "SHOULD continue
1692 			 *    to be used"
1693 			 * 2. use of it with new communication:
1694 			 *   (2a) "SHOULD NOT be used if alternate
1695 			 *        address with sufficient scope is
1696 			 *        available"
1697 			 *   (2b) nothing mentioned otherwise.
1698 			 * Here we fall into (2b) case as we have no
1699 			 * choice in our source address selection - we
1700 			 * must obey the peer.
1701 			 *
1702 			 * The wording in RFC2462 is confusing, and
1703 			 * there are multiple description text for
1704 			 * deprecated address handling - worse, they
1705 			 * are not exactly the same.  I believe 5.5.4
1706 			 * is the best one, so we follow 5.5.4.
1707 			 */
1708 			if (af == AF_INET6 && !ip6_use_deprecated) {
1709 				struct in6_ifaddr *ia6;
1710 				int s;
1711 				struct ifnet *rcvif = m_get_rcvif(m, &s);
1712 				if (rcvif == NULL)
1713 					goto dropwithreset; /* XXX */
1714 				if ((ia6 = in6ifa_ifpwithaddr(rcvif,
1715 				    &ip6->ip6_dst)) &&
1716 				    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1717 					tp = NULL;
1718 					m_put_rcvif(rcvif, &s);
1719 					goto dropwithreset;
1720 				}
1721 				m_put_rcvif(rcvif, &s);
1722 			}
1723 #endif
1724 
1725 			/*
1726 			 * LISTEN socket received a SYN from itself? This
1727 			 * can't possibly be valid; drop the packet.
1728 			 */
1729 			if (th->th_sport == th->th_dport) {
1730 				int eq = 0;
1731 
1732 				switch (af) {
1733 				case AF_INET:
1734 					eq = in_hosteq(ip->ip_src, ip->ip_dst);
1735 					break;
1736 #ifdef INET6
1737 				case AF_INET6:
1738 					eq = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src,
1739 					    &ip6->ip6_dst);
1740 					break;
1741 #endif
1742 				}
1743 				if (eq) {
1744 					TCP_STATINC(TCP_STAT_BADSYN);
1745 					goto drop;
1746 				}
1747 			}
1748 
1749 			/*
1750 			 * SYN looks ok; create compressed TCP
1751 			 * state for it.
1752 			 */
1753 			if (so->so_qlen <= so->so_qlimit &&
1754 			    syn_cache_add(&src.sa, &dst.sa, th, off,
1755 			    so, m, optp, optlen, &opti))
1756 				m = NULL;
1757 		}
1758 
1759 		goto drop;
1760 	}
1761 
1762 after_listen:
1763 	/*
1764 	 * From here on, we're dealing with !LISTEN.
1765 	 */
1766 	KASSERT(tp->t_state != TCPS_LISTEN);
1767 
1768 	/*
1769 	 * Segment received on connection.
1770 	 * Reset idle time and keep-alive timer.
1771 	 */
1772 	tp->t_rcvtime = tcp_now;
1773 	if (TCPS_HAVEESTABLISHED(tp->t_state))
1774 		TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
1775 
1776 	/*
1777 	 * Process options.
1778 	 */
1779 #ifdef TCP_SIGNATURE
1780 	if (optp || (tp->t_flags & TF_SIGNATURE))
1781 #else
1782 	if (optp)
1783 #endif
1784 		if (tcp_dooptions(tp, optp, optlen, th, m, off, &opti) < 0)
1785 			goto drop;
1786 
1787 	if (TCP_SACK_ENABLED(tp)) {
1788 		tcp_del_sackholes(tp, th);
1789 	}
1790 
1791 	if (TCP_ECN_ALLOWED(tp)) {
1792 		if (tiflags & TH_CWR) {
1793 			tp->t_flags &= ~TF_ECN_SND_ECE;
1794 		}
1795 		switch (iptos & IPTOS_ECN_MASK) {
1796 		case IPTOS_ECN_CE:
1797 			tp->t_flags |= TF_ECN_SND_ECE;
1798 			TCP_STATINC(TCP_STAT_ECN_CE);
1799 			break;
1800 		case IPTOS_ECN_ECT0:
1801 			TCP_STATINC(TCP_STAT_ECN_ECT);
1802 			break;
1803 		case IPTOS_ECN_ECT1:
1804 			/* XXX: ignore for now -- rpaulo */
1805 			break;
1806 		}
1807 		/*
1808 		 * Congestion experienced.
1809 		 * Ignore if we are already trying to recover.
1810 		 */
1811 		if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
1812 			tp->t_congctl->cong_exp(tp);
1813 	}
1814 
1815 	if (opti.ts_present && opti.ts_ecr) {
1816 		/*
1817 		 * Calculate the RTT from the returned time stamp and the
1818 		 * connection's time base.  If the time stamp is later than
1819 		 * the current time, or is extremely old, fall back to non-1323
1820 		 * RTT calculation.  Since ts_rtt is unsigned, we can test both
1821 		 * at the same time.
1822 		 *
1823 		 * Note that ts_rtt is in units of slow ticks (500
1824 		 * ms).  Since most earthbound RTTs are < 500 ms,
1825 		 * observed values will have large quantization noise.
1826 		 * Our smoothed RTT is then the fraction of observed
1827 		 * samples that are 1 tick instead of 0 (times 500
1828 		 * ms).
1829 		 *
1830 		 * ts_rtt is increased by 1 to denote a valid sample,
1831 		 * with 0 indicating an invalid measurement.  This
1832 		 * extra 1 must be removed when ts_rtt is used, or
1833 		 * else an erroneous extra 500 ms will result.
1834 		 */
1835 		ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1836 		if (ts_rtt > TCP_PAWS_IDLE)
1837 			ts_rtt = 0;
1838 	} else {
1839 		ts_rtt = 0;
1840 	}
1841 
1842 	/*
1843 	 * Fast path: check for the two common cases of a uni-directional
1844 	 * data transfer. If:
1845 	 *    o We are in the ESTABLISHED state, and
1846 	 *    o The packet has no control flags, and
1847 	 *    o The packet is in-sequence, and
1848 	 *    o The window didn't change, and
1849 	 *    o We are not retransmitting
1850 	 * It's a candidate.
1851 	 *
1852 	 * If the length (tlen) is zero and the ack moved forward, we're
1853 	 * the sender side of the transfer. Just free the data acked and
1854 	 * wake any higher level process that was blocked waiting for
1855 	 * space.
1856 	 *
1857 	 * If the length is non-zero and the ack didn't move, we're the
1858 	 * receiver side. If we're getting packets in-order (the reassembly
1859 	 * queue is empty), add the data to the socket buffer and note
1860 	 * that we need a delayed ack.
1861 	 */
1862 	if (tp->t_state == TCPS_ESTABLISHED &&
1863 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
1864 	        == TH_ACK &&
1865 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1866 	    th->th_seq == tp->rcv_nxt &&
1867 	    tiwin && tiwin == tp->snd_wnd &&
1868 	    tp->snd_nxt == tp->snd_max) {
1869 
1870 		/*
1871 		 * If last ACK falls within this segment's sequence numbers,
1872 		 * record the timestamp.
1873 		 * NOTE that the test is modified according to the latest
1874 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1875 		 *
1876 		 * note that we already know
1877 		 *	TSTMP_GEQ(opti.ts_val, tp->ts_recent)
1878 		 */
1879 		if (opti.ts_present && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1880 			tp->ts_recent_age = tcp_now;
1881 			tp->ts_recent = opti.ts_val;
1882 		}
1883 
1884 		if (tlen == 0) {
1885 			/* Ack prediction. */
1886 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1887 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1888 			    tp->snd_cwnd >= tp->snd_wnd &&
1889 			    tp->t_partialacks < 0) {
1890 				/*
1891 				 * this is a pure ack for outstanding data.
1892 				 */
1893 				if (ts_rtt)
1894 					tcp_xmit_timer(tp, ts_rtt - 1);
1895 				else if (tp->t_rtttime &&
1896 				    SEQ_GT(th->th_ack, tp->t_rtseq))
1897 					tcp_xmit_timer(tp,
1898 					  tcp_now - tp->t_rtttime);
1899 				acked = th->th_ack - tp->snd_una;
1900 				tcps = TCP_STAT_GETREF();
1901 				tcps[TCP_STAT_PREDACK]++;
1902 				tcps[TCP_STAT_RCVACKPACK]++;
1903 				tcps[TCP_STAT_RCVACKBYTE] += acked;
1904 				TCP_STAT_PUTREF();
1905 				nd_hint(tp);
1906 
1907 				if (acked > (tp->t_lastoff - tp->t_inoff))
1908 					tp->t_lastm = NULL;
1909 				sbdrop(&so->so_snd, acked);
1910 				tp->t_lastoff -= acked;
1911 
1912 				icmp_check(tp, th, acked);
1913 
1914 				tp->snd_una = th->th_ack;
1915 				tp->snd_fack = tp->snd_una;
1916 				if (SEQ_LT(tp->snd_high, tp->snd_una))
1917 					tp->snd_high = tp->snd_una;
1918 				/*
1919 				 * drag snd_wl2 along so only newer
1920 				 * ACKs can update the window size.
1921 				 * also avoids the state where snd_wl2
1922 				 * is eventually larger than th_ack and thus
1923 				 * blocking the window update mechanism and
1924 				 * the connection gets stuck for a loooong
1925 				 * time in the zero sized send window state.
1926 				 *
1927 				 * see PR/kern 55567
1928 				 */
1929 				tp->snd_wl2 = tp->snd_una;
1930 
1931 				m_freem(m);
1932 
1933 				/*
1934 				 * If all outstanding data are acked, stop
1935 				 * retransmit timer, otherwise restart timer
1936 				 * using current (possibly backed-off) value.
1937 				 * If process is waiting for space,
1938 				 * wakeup/selnotify/signal.  If data
1939 				 * are ready to send, let tcp_output
1940 				 * decide between more output or persist.
1941 				 */
1942 				if (tp->snd_una == tp->snd_max)
1943 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
1944 				else if (TCP_TIMER_ISARMED(tp,
1945 				    TCPT_PERSIST) == 0)
1946 					TCP_TIMER_ARM(tp, TCPT_REXMT,
1947 					    tp->t_rxtcur);
1948 
1949 				sowwakeup(so);
1950 				if (so->so_snd.sb_cc) {
1951 					KERNEL_LOCK(1, NULL);
1952 					(void)tcp_output(tp);
1953 					KERNEL_UNLOCK_ONE(NULL);
1954 				}
1955 				if (tcp_saveti)
1956 					m_freem(tcp_saveti);
1957 				return;
1958 			}
1959 		} else if (th->th_ack == tp->snd_una &&
1960 		    TAILQ_FIRST(&tp->segq) == NULL &&
1961 		    tlen <= sbspace(&so->so_rcv)) {
1962 			int newsize = 0;
1963 
1964 			/*
1965 			 * this is a pure, in-sequence data packet
1966 			 * with nothing on the reassembly queue and
1967 			 * we have enough buffer space to take it.
1968 			 */
1969 			tp->rcv_nxt += tlen;
1970 
1971 			/*
1972 			 * Pull rcv_up up to prevent seq wrap relative to
1973 			 * rcv_nxt.
1974 			 */
1975 			tp->rcv_up = tp->rcv_nxt;
1976 
1977 			/*
1978 			 * Pull snd_wl1 up to prevent seq wrap relative to
1979 			 * th_seq.
1980 			 */
1981 			tp->snd_wl1 = th->th_seq;
1982 
1983 			tcps = TCP_STAT_GETREF();
1984 			tcps[TCP_STAT_PREDDAT]++;
1985 			tcps[TCP_STAT_RCVPACK]++;
1986 			tcps[TCP_STAT_RCVBYTE] += tlen;
1987 			TCP_STAT_PUTREF();
1988 			nd_hint(tp);
1989 		/*
1990 		 * Automatic sizing enables the performance of large buffers
1991 		 * and most of the efficiency of small ones by only allocating
1992 		 * space when it is needed.
1993 		 *
1994 		 * On the receive side the socket buffer memory is only rarely
1995 		 * used to any significant extent.  This allows us to be much
1996 		 * more aggressive in scaling the receive socket buffer.  For
1997 		 * the case that the buffer space is actually used to a large
1998 		 * extent and we run out of kernel memory we can simply drop
1999 		 * the new segments; TCP on the sender will just retransmit it
2000 		 * later.  Setting the buffer size too big may only consume too
2001 		 * much kernel memory if the application doesn't read() from
2002 		 * the socket or packet loss or reordering makes use of the
2003 		 * reassembly queue.
2004 		 *
2005 		 * The criteria to step up the receive buffer one notch are:
2006 		 *  1. the number of bytes received during the time it takes
2007 		 *     one timestamp to be reflected back to us (the RTT);
2008 		 *  2. received bytes per RTT is within seven eighth of the
2009 		 *     current socket buffer size;
2010 		 *  3. receive buffer size has not hit maximal automatic size;
2011 		 *
2012 		 * This algorithm does one step per RTT at most and only if
2013 		 * we receive a bulk stream w/o packet losses or reorderings.
2014 		 * Shrinking the buffer during idle times is not necessary as
2015 		 * it doesn't consume any memory when idle.
2016 		 *
2017 		 * TODO: Only step up if the application is actually serving
2018 		 * the buffer to better manage the socket buffer resources.
2019 		 */
2020 			if (tcp_do_autorcvbuf &&
2021 			    opti.ts_ecr &&
2022 			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
2023 				if (opti.ts_ecr > tp->rfbuf_ts &&
2024 				    opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
2025 					if (tp->rfbuf_cnt >
2026 					    (so->so_rcv.sb_hiwat / 8 * 7) &&
2027 					    so->so_rcv.sb_hiwat <
2028 					    tcp_autorcvbuf_max) {
2029 						newsize =
2030 						    uimin(so->so_rcv.sb_hiwat +
2031 						    tcp_autorcvbuf_inc,
2032 						    tcp_autorcvbuf_max);
2033 					}
2034 					/* Start over with next RTT. */
2035 					tp->rfbuf_ts = 0;
2036 					tp->rfbuf_cnt = 0;
2037 				} else
2038 					tp->rfbuf_cnt += tlen;	/* add up */
2039 			}
2040 
2041 			/*
2042 			 * Drop TCP, IP headers and TCP options then add data
2043 			 * to socket buffer.
2044 			 */
2045 			if (so->so_state & SS_CANTRCVMORE) {
2046 				m_freem(m);
2047 			} else {
2048 				/*
2049 				 * Set new socket buffer size.
2050 				 * Give up when limit is reached.
2051 				 */
2052 				if (newsize)
2053 					if (!sbreserve(&so->so_rcv,
2054 					    newsize, so))
2055 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
2056 				m_adj(m, off + thlen);
2057 				sbappendstream(&so->so_rcv, m);
2058 			}
2059 			sorwakeup(so);
2060 			tcp_setup_ack(tp, th);
2061 			if (tp->t_flags & TF_ACKNOW) {
2062 				KERNEL_LOCK(1, NULL);
2063 				(void)tcp_output(tp);
2064 				KERNEL_UNLOCK_ONE(NULL);
2065 			}
2066 			if (tcp_saveti)
2067 				m_freem(tcp_saveti);
2068 			return;
2069 		}
2070 	}
2071 
2072 	/*
2073 	 * Compute mbuf offset to TCP data segment.
2074 	 */
2075 	hdroptlen = off + thlen;
2076 
2077 	/*
2078 	 * Calculate amount of space in receive window. Receive window is
2079 	 * amount of space in rcv queue, but not less than advertised
2080 	 * window.
2081 	 */
2082 	{
2083 		int win;
2084 		win = sbspace(&so->so_rcv);
2085 		if (win < 0)
2086 			win = 0;
2087 		tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
2088 	}
2089 
2090 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
2091 	tp->rfbuf_ts = 0;
2092 	tp->rfbuf_cnt = 0;
2093 
2094 	switch (tp->t_state) {
2095 	/*
2096 	 * If the state is SYN_SENT:
2097 	 *	if seg contains an ACK, but not for our SYN, drop the input.
2098 	 *	if seg contains a RST, then drop the connection.
2099 	 *	if seg does not contain SYN, then drop it.
2100 	 * Otherwise this is an acceptable SYN segment
2101 	 *	initialize tp->rcv_nxt and tp->irs
2102 	 *	if seg contains ack then advance tp->snd_una
2103 	 *	if seg contains a ECE and ECN support is enabled, the stream
2104 	 *	    is ECN capable.
2105 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2106 	 *	arrange for segment to be acked (eventually)
2107 	 *	continue processing rest of data/controls, beginning with URG
2108 	 */
2109 	case TCPS_SYN_SENT:
2110 		if ((tiflags & TH_ACK) &&
2111 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
2112 		     SEQ_GT(th->th_ack, tp->snd_max)))
2113 			goto dropwithreset;
2114 		if (tiflags & TH_RST) {
2115 			if (tiflags & TH_ACK)
2116 				tp = tcp_drop(tp, ECONNREFUSED);
2117 			goto drop;
2118 		}
2119 		if ((tiflags & TH_SYN) == 0)
2120 			goto drop;
2121 		if (tiflags & TH_ACK) {
2122 			tp->snd_una = th->th_ack;
2123 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2124 				tp->snd_nxt = tp->snd_una;
2125 			if (SEQ_LT(tp->snd_high, tp->snd_una))
2126 				tp->snd_high = tp->snd_una;
2127 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
2128 
2129 			if ((tiflags & TH_ECE) && tcp_do_ecn) {
2130 				tp->t_flags |= TF_ECN_PERMIT;
2131 				TCP_STATINC(TCP_STAT_ECN_SHS);
2132 			}
2133 		}
2134 		tp->irs = th->th_seq;
2135 		tcp_rcvseqinit(tp);
2136 		tp->t_flags |= TF_ACKNOW;
2137 		tcp_mss_from_peer(tp, opti.maxseg);
2138 
2139 		/*
2140 		 * Initialize the initial congestion window.  If we
2141 		 * had to retransmit the SYN, we must initialize cwnd
2142 		 * to 1 segment (i.e. the Loss Window).
2143 		 */
2144 		if (tp->t_flags & TF_SYN_REXMT)
2145 			tp->snd_cwnd = tp->t_peermss;
2146 		else {
2147 			int ss = tcp_init_win;
2148 			if (inp != NULL && in_localaddr(inp->inp_faddr))
2149 				ss = tcp_init_win_local;
2150 #ifdef INET6
2151 			if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
2152 				ss = tcp_init_win_local;
2153 #endif
2154 			tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
2155 		}
2156 
2157 		tcp_rmx_rtt(tp);
2158 		if (tiflags & TH_ACK) {
2159 			TCP_STATINC(TCP_STAT_CONNECTS);
2160 			/*
2161 			 * move tcp_established before soisconnected
2162 			 * because upcall handler can drive tcp_output
2163 			 * functionality.
2164 			 * XXX we might call soisconnected at the end of
2165 			 * all processing
2166 			 */
2167 			tcp_established(tp);
2168 			soisconnected(so);
2169 			/* Do window scaling on this connection? */
2170 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2171 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2172 				tp->snd_scale = tp->requested_s_scale;
2173 				tp->rcv_scale = tp->request_r_scale;
2174 			}
2175 			TCP_REASS_LOCK(tp);
2176 			(void)tcp_reass(tp, NULL, NULL, tlen);
2177 			/*
2178 			 * if we didn't have to retransmit the SYN,
2179 			 * use its rtt as our initial srtt & rtt var.
2180 			 */
2181 			if (tp->t_rtttime)
2182 				tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2183 		} else {
2184 			tp->t_state = TCPS_SYN_RECEIVED;
2185 		}
2186 
2187 		/*
2188 		 * Advance th->th_seq to correspond to first data byte.
2189 		 * If data, trim to stay within window,
2190 		 * dropping FIN if necessary.
2191 		 */
2192 		th->th_seq++;
2193 		if (tlen > tp->rcv_wnd) {
2194 			todrop = tlen - tp->rcv_wnd;
2195 			m_adj(m, -todrop);
2196 			tlen = tp->rcv_wnd;
2197 			tiflags &= ~TH_FIN;
2198 			tcps = TCP_STAT_GETREF();
2199 			tcps[TCP_STAT_RCVPACKAFTERWIN]++;
2200 			tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
2201 			TCP_STAT_PUTREF();
2202 		}
2203 		tp->snd_wl1 = th->th_seq - 1;
2204 		tp->rcv_up = th->th_seq;
2205 		goto step6;
2206 
2207 	/*
2208 	 * If the state is SYN_RECEIVED:
2209 	 *	If seg contains an ACK, but not for our SYN, drop the input
2210 	 *	and generate an RST.  See page 36, rfc793
2211 	 */
2212 	case TCPS_SYN_RECEIVED:
2213 		if ((tiflags & TH_ACK) &&
2214 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
2215 		     SEQ_GT(th->th_ack, tp->snd_max)))
2216 			goto dropwithreset;
2217 		break;
2218 	}
2219 
2220 	/*
2221 	 * From here on, we're dealing with !LISTEN and !SYN_SENT.
2222 	 */
2223 	KASSERT(tp->t_state != TCPS_LISTEN &&
2224 	    tp->t_state != TCPS_SYN_SENT);
2225 
2226 	/*
2227 	 * RFC1323 PAWS: if we have a timestamp reply on this segment and
2228 	 * it's less than ts_recent, drop it.
2229 	 */
2230 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
2231 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
2232 		/* Check to see if ts_recent is over 24 days old.  */
2233 		if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
2234 			/*
2235 			 * Invalidate ts_recent.  If this segment updates
2236 			 * ts_recent, the age will be reset later and ts_recent
2237 			 * will get a valid value.  If it does not, setting
2238 			 * ts_recent to zero will at least satisfy the
2239 			 * requirement that zero be placed in the timestamp
2240 			 * echo reply when ts_recent isn't valid.  The
2241 			 * age isn't reset until we get a valid ts_recent
2242 			 * because we don't want out-of-order segments to be
2243 			 * dropped when ts_recent is old.
2244 			 */
2245 			tp->ts_recent = 0;
2246 		} else {
2247 			tcps = TCP_STAT_GETREF();
2248 			tcps[TCP_STAT_RCVDUPPACK]++;
2249 			tcps[TCP_STAT_RCVDUPBYTE] += tlen;
2250 			tcps[TCP_STAT_PAWSDROP]++;
2251 			TCP_STAT_PUTREF();
2252 			tcp_new_dsack(tp, th->th_seq, tlen);
2253 			goto dropafterack;
2254 		}
2255 	}
2256 
2257 	/*
2258 	 * Check that at least some bytes of the segment are within the
2259 	 * receive window. If segment begins before rcv_nxt, drop leading
2260 	 * data (and SYN); if nothing left, just ack.
2261 	 */
2262 	todrop = tp->rcv_nxt - th->th_seq;
2263 	dupseg = false;
2264 	if (todrop > 0) {
2265 		if (tiflags & TH_SYN) {
2266 			tiflags &= ~TH_SYN;
2267 			th->th_seq++;
2268 			tcp_urp_drop(th, 1, &tiflags);
2269 			todrop--;
2270 		}
2271 		if (todrop > tlen ||
2272 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
2273 			/*
2274 			 * Any valid FIN or RST must be to the left of the
2275 			 * window.  At this point the FIN or RST must be a
2276 			 * duplicate or out of sequence; drop it.
2277 			 */
2278 			if (tiflags & TH_RST)
2279 				goto drop;
2280 			tiflags &= ~(TH_FIN|TH_RST);
2281 
2282 			/*
2283 			 * Send an ACK to resynchronize and drop any data.
2284 			 * But keep on processing for RST or ACK.
2285 			 */
2286 			tp->t_flags |= TF_ACKNOW;
2287 			todrop = tlen;
2288 			dupseg = true;
2289 			tcps = TCP_STAT_GETREF();
2290 			tcps[TCP_STAT_RCVDUPPACK]++;
2291 			tcps[TCP_STAT_RCVDUPBYTE] += todrop;
2292 			TCP_STAT_PUTREF();
2293 		} else if ((tiflags & TH_RST) && th->th_seq != tp->rcv_nxt) {
2294 			/*
2295 			 * Test for reset before adjusting the sequence
2296 			 * number for overlapping data.
2297 			 */
2298 			goto dropafterack_ratelim;
2299 		} else {
2300 			tcps = TCP_STAT_GETREF();
2301 			tcps[TCP_STAT_RCVPARTDUPPACK]++;
2302 			tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
2303 			TCP_STAT_PUTREF();
2304 		}
2305 		tcp_new_dsack(tp, th->th_seq, todrop);
2306 		hdroptlen += todrop;	/* drop from head afterwards (m_adj) */
2307 		th->th_seq += todrop;
2308 		tlen -= todrop;
2309 		tcp_urp_drop(th, todrop, &tiflags);
2310 	}
2311 
2312 	/*
2313 	 * If new data is received on a connection after the user processes
2314 	 * are gone, then RST the other end.
2315 	 */
2316 	if ((so->so_state & SS_NOFDREF) &&
2317 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2318 		tp = tcp_close(tp);
2319 		TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
2320 		goto dropwithreset;
2321 	}
2322 
2323 	/*
2324 	 * If the segment ends after the window, drop trailing data (and
2325 	 * PUSH and FIN); if nothing left, just ACK.
2326 	 */
2327 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2328 	if (todrop > 0) {
2329 		TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
2330 		if (todrop >= tlen) {
2331 			/*
2332 			 * The segment actually starts after the window.
2333 			 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2334 			 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2335 			 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2336 			 */
2337 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
2338 
2339 			/*
2340 			 * If a new connection request is received while in
2341 			 * TIME_WAIT, drop the old connection and start over
2342 			 * if the sequence numbers are above the previous
2343 			 * ones.
2344 			 *
2345 			 * NOTE: We need to put the header fields back into
2346 			 * network order.
2347 			 */
2348 			if ((tiflags & TH_SYN) &&
2349 			    tp->t_state == TCPS_TIME_WAIT &&
2350 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2351 				tp = tcp_close(tp);
2352 				tcp_fields_to_net(th);
2353 				m_freem(tcp_saveti);
2354 				tcp_saveti = NULL;
2355 				goto findpcb;
2356 			}
2357 
2358 			/*
2359 			 * If window is closed can only take segments at
2360 			 * window edge, and have to drop data and PUSH from
2361 			 * incoming segments.  Continue processing, but
2362 			 * remember to ack.  Otherwise, drop segment
2363 			 * and (if not RST) ack.
2364 			 */
2365 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2366 				KASSERT(todrop == tlen);
2367 				tp->t_flags |= TF_ACKNOW;
2368 				TCP_STATINC(TCP_STAT_RCVWINPROBE);
2369 			} else {
2370 				goto dropafterack;
2371 			}
2372 		} else {
2373 			TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
2374 		}
2375 		m_adj(m, -todrop);
2376 		tlen -= todrop;
2377 		tiflags &= ~(TH_PUSH|TH_FIN);
2378 	}
2379 
2380 	/*
2381 	 * If last ACK falls within this segment's sequence numbers,
2382 	 *  record the timestamp.
2383 	 * NOTE:
2384 	 * 1) That the test incorporates suggestions from the latest
2385 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
2386 	 * 2) That updating only on newer timestamps interferes with
2387 	 *    our earlier PAWS tests, so this check should be solely
2388 	 *    predicated on the sequence space of this segment.
2389 	 * 3) That we modify the segment boundary check to be
2390 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
2391 	 *    instead of RFC1323's
2392 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
2393 	 *    This modified check allows us to overcome RFC1323's
2394 	 *    limitations as described in Stevens TCP/IP Illustrated
2395 	 *    Vol. 2 p.869. In such cases, we can still calculate the
2396 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
2397 	 */
2398 	if (opti.ts_present &&
2399 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2400 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2401 	         ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2402 		tp->ts_recent_age = tcp_now;
2403 		tp->ts_recent = opti.ts_val;
2404 	}
2405 
2406 	/*
2407 	 * If the RST bit is set examine the state:
2408 	 *    RECEIVED state:
2409 	 *        If passive open, return to LISTEN state.
2410 	 *        If active open, inform user that connection was refused.
2411 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT states:
2412 	 *        Inform user that connection was reset, and close tcb.
2413 	 *    CLOSING, LAST_ACK, TIME_WAIT states:
2414 	 *        Close the tcb.
2415 	 */
2416 	if (tiflags & TH_RST) {
2417 		if (th->th_seq != tp->rcv_nxt)
2418 			goto dropafterack_ratelim;
2419 
2420 		switch (tp->t_state) {
2421 		case TCPS_SYN_RECEIVED:
2422 			so->so_error = ECONNREFUSED;
2423 			goto close;
2424 
2425 		case TCPS_ESTABLISHED:
2426 		case TCPS_FIN_WAIT_1:
2427 		case TCPS_FIN_WAIT_2:
2428 		case TCPS_CLOSE_WAIT:
2429 			so->so_error = ECONNRESET;
2430 		close:
2431 			tp->t_state = TCPS_CLOSED;
2432 			TCP_STATINC(TCP_STAT_DROPS);
2433 			tp = tcp_close(tp);
2434 			goto drop;
2435 
2436 		case TCPS_CLOSING:
2437 		case TCPS_LAST_ACK:
2438 		case TCPS_TIME_WAIT:
2439 			tp = tcp_close(tp);
2440 			goto drop;
2441 		}
2442 	}
2443 
2444 	/*
2445 	 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2446 	 * we must be in a synchronized state.  RFC793 states (under Reset
2447 	 * Generation) that any unacceptable segment (an out-of-order SYN
2448 	 * qualifies) received in a synchronized state must elicit only an
2449 	 * empty acknowledgment segment ... and the connection remains in
2450 	 * the same state.
2451 	 */
2452 	if (tiflags & TH_SYN) {
2453 		if (tp->rcv_nxt == th->th_seq) {
2454 			tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2455 			    TH_ACK);
2456 			if (tcp_saveti)
2457 				m_freem(tcp_saveti);
2458 			return;
2459 		}
2460 
2461 		goto dropafterack_ratelim;
2462 	}
2463 
2464 	/*
2465 	 * If the ACK bit is off we drop the segment and return.
2466 	 */
2467 	if ((tiflags & TH_ACK) == 0) {
2468 		if (tp->t_flags & TF_ACKNOW)
2469 			goto dropafterack;
2470 		goto drop;
2471 	}
2472 
2473 	/*
2474 	 * From here on, we're doing ACK processing.
2475 	 */
2476 
2477 	switch (tp->t_state) {
2478 	/*
2479 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2480 	 * ESTABLISHED state and continue processing, otherwise
2481 	 * send an RST.
2482 	 */
2483 	case TCPS_SYN_RECEIVED:
2484 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
2485 		    SEQ_GT(th->th_ack, tp->snd_max))
2486 			goto dropwithreset;
2487 		TCP_STATINC(TCP_STAT_CONNECTS);
2488 		soisconnected(so);
2489 		tcp_established(tp);
2490 		/* Do window scaling? */
2491 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2492 		    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2493 			tp->snd_scale = tp->requested_s_scale;
2494 			tp->rcv_scale = tp->request_r_scale;
2495 		}
2496 		TCP_REASS_LOCK(tp);
2497 		(void)tcp_reass(tp, NULL, NULL, tlen);
2498 		tp->snd_wl1 = th->th_seq - 1;
2499 		/* FALLTHROUGH */
2500 
2501 	/*
2502 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2503 	 * ACKs.  If the ack is in the range
2504 	 *	tp->snd_una < th->th_ack <= tp->snd_max
2505 	 * then advance tp->snd_una to th->th_ack and drop
2506 	 * data from the retransmission queue.  If this ACK reflects
2507 	 * more up to date window information we update our window information.
2508 	 */
2509 	case TCPS_ESTABLISHED:
2510 	case TCPS_FIN_WAIT_1:
2511 	case TCPS_FIN_WAIT_2:
2512 	case TCPS_CLOSE_WAIT:
2513 	case TCPS_CLOSING:
2514 	case TCPS_LAST_ACK:
2515 	case TCPS_TIME_WAIT:
2516 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2517 			if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2518 				TCP_STATINC(TCP_STAT_RCVDUPACK);
2519 				/*
2520 				 * If we have outstanding data (other than
2521 				 * a window probe), this is a completely
2522 				 * duplicate ack (ie, window info didn't
2523 				 * change), the ack is the biggest we've
2524 				 * seen and we've seen exactly our rexmt
2525 				 * threshold of them, assume a packet
2526 				 * has been dropped and retransmit it.
2527 				 * Kludge snd_nxt & the congestion
2528 				 * window so we send only this one
2529 				 * packet.
2530 				 */
2531 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2532 				    th->th_ack != tp->snd_una)
2533 					tp->t_dupacks = 0;
2534 				else if (tp->t_partialacks < 0 &&
2535 				    (++tp->t_dupacks == tcprexmtthresh ||
2536 				     TCP_FACK_FASTRECOV(tp))) {
2537 					/*
2538 					 * Do the fast retransmit, and adjust
2539 					 * congestion control parameters.
2540 					 */
2541 					if (tp->t_congctl->fast_retransmit(tp, th)) {
2542 						/* False fast retransmit */
2543 						break;
2544 					}
2545 					goto drop;
2546 				} else if (tp->t_dupacks > tcprexmtthresh) {
2547 					tp->snd_cwnd += tp->t_segsz;
2548 					KERNEL_LOCK(1, NULL);
2549 					(void)tcp_output(tp);
2550 					KERNEL_UNLOCK_ONE(NULL);
2551 					goto drop;
2552 				}
2553 			} else {
2554 				/*
2555 				 * If the ack appears to be very old, only
2556 				 * allow data that is in-sequence.  This
2557 				 * makes it somewhat more difficult to insert
2558 				 * forged data by guessing sequence numbers.
2559 				 * Sent an ack to try to update the send
2560 				 * sequence number on the other side.
2561 				 */
2562 				if (tlen && th->th_seq != tp->rcv_nxt &&
2563 				    SEQ_LT(th->th_ack,
2564 				    tp->snd_una - tp->max_sndwnd))
2565 					goto dropafterack;
2566 			}
2567 			break;
2568 		}
2569 		/*
2570 		 * If the congestion window was inflated to account
2571 		 * for the other side's cached packets, retract it.
2572 		 */
2573 		tp->t_congctl->fast_retransmit_newack(tp, th);
2574 
2575 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
2576 			TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
2577 			goto dropafterack;
2578 		}
2579 		acked = th->th_ack - tp->snd_una;
2580 		tcps = TCP_STAT_GETREF();
2581 		tcps[TCP_STAT_RCVACKPACK]++;
2582 		tcps[TCP_STAT_RCVACKBYTE] += acked;
2583 		TCP_STAT_PUTREF();
2584 
2585 		/*
2586 		 * If we have a timestamp reply, update smoothed
2587 		 * round trip time.  If no timestamp is present but
2588 		 * transmit timer is running and timed sequence
2589 		 * number was acked, update smoothed round trip time.
2590 		 * Since we now have an rtt measurement, cancel the
2591 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2592 		 * Recompute the initial retransmit timer.
2593 		 */
2594 		if (ts_rtt)
2595 			tcp_xmit_timer(tp, ts_rtt - 1);
2596 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2597 			tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2598 
2599 		/*
2600 		 * If all outstanding data is acked, stop retransmit
2601 		 * timer and remember to restart (more output or persist).
2602 		 * If there is more data to be acked, restart retransmit
2603 		 * timer, using current (possibly backed-off) value.
2604 		 */
2605 		if (th->th_ack == tp->snd_max) {
2606 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
2607 			needoutput = 1;
2608 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2609 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2610 
2611 		/*
2612 		 * New data has been acked, adjust the congestion window.
2613 		 */
2614 		tp->t_congctl->newack(tp, th);
2615 
2616 		nd_hint(tp);
2617 		if (acked > so->so_snd.sb_cc) {
2618 			tp->snd_wnd -= so->so_snd.sb_cc;
2619 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2620 			ourfinisacked = 1;
2621 		} else {
2622 			if (acked > (tp->t_lastoff - tp->t_inoff))
2623 				tp->t_lastm = NULL;
2624 			sbdrop(&so->so_snd, acked);
2625 			tp->t_lastoff -= acked;
2626 			if (tp->snd_wnd > acked)
2627 				tp->snd_wnd -= acked;
2628 			else
2629 				tp->snd_wnd = 0;
2630 			ourfinisacked = 0;
2631 		}
2632 		sowwakeup(so);
2633 
2634 		icmp_check(tp, th, acked);
2635 
2636 		tp->snd_una = th->th_ack;
2637 		if (SEQ_GT(tp->snd_una, tp->snd_fack))
2638 			tp->snd_fack = tp->snd_una;
2639 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2640 			tp->snd_nxt = tp->snd_una;
2641 		if (SEQ_LT(tp->snd_high, tp->snd_una))
2642 			tp->snd_high = tp->snd_una;
2643 
2644 		switch (tp->t_state) {
2645 
2646 		/*
2647 		 * In FIN_WAIT_1 STATE in addition to the processing
2648 		 * for the ESTABLISHED state if our FIN is now acknowledged
2649 		 * then enter FIN_WAIT_2.
2650 		 */
2651 		case TCPS_FIN_WAIT_1:
2652 			if (ourfinisacked) {
2653 				/*
2654 				 * If we can't receive any more
2655 				 * data, then closing user can proceed.
2656 				 * Starting the timer is contrary to the
2657 				 * specification, but if we don't get a FIN
2658 				 * we'll hang forever.
2659 				 */
2660 				if (so->so_state & SS_CANTRCVMORE) {
2661 					soisdisconnected(so);
2662 					if (tp->t_maxidle > 0)
2663 						TCP_TIMER_ARM(tp, TCPT_2MSL,
2664 						    tp->t_maxidle);
2665 				}
2666 				tp->t_state = TCPS_FIN_WAIT_2;
2667 			}
2668 			break;
2669 
2670 	 	/*
2671 		 * In CLOSING STATE in addition to the processing for
2672 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2673 		 * then enter the TIME-WAIT state, otherwise ignore
2674 		 * the segment.
2675 		 */
2676 		case TCPS_CLOSING:
2677 			if (ourfinisacked) {
2678 				tp->t_state = TCPS_TIME_WAIT;
2679 				tcp_canceltimers(tp);
2680 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2681 				soisdisconnected(so);
2682 			}
2683 			break;
2684 
2685 		/*
2686 		 * In LAST_ACK, we may still be waiting for data to drain
2687 		 * and/or to be acked, as well as for the ack of our FIN.
2688 		 * If our FIN is now acknowledged, delete the TCB,
2689 		 * enter the closed state and return.
2690 		 */
2691 		case TCPS_LAST_ACK:
2692 			if (ourfinisacked) {
2693 				tp = tcp_close(tp);
2694 				goto drop;
2695 			}
2696 			break;
2697 
2698 		/*
2699 		 * In TIME_WAIT state the only thing that should arrive
2700 		 * is a retransmission of the remote FIN.  Acknowledge
2701 		 * it and restart the finack timer.
2702 		 */
2703 		case TCPS_TIME_WAIT:
2704 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2705 			goto dropafterack;
2706 		}
2707 	}
2708 
2709 step6:
2710 	/*
2711 	 * Update window information.
2712 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2713 	 */
2714 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2715 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2716 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2717 		/* keep track of pure window updates */
2718 		if (tlen == 0 &&
2719 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2720 			TCP_STATINC(TCP_STAT_RCVWINUPD);
2721 		tp->snd_wnd = tiwin;
2722 		tp->snd_wl1 = th->th_seq;
2723 		tp->snd_wl2 = th->th_ack;
2724 		if (tp->snd_wnd > tp->max_sndwnd)
2725 			tp->max_sndwnd = tp->snd_wnd;
2726 		needoutput = 1;
2727 	}
2728 
2729 	/*
2730 	 * Process segments with URG.
2731 	 */
2732 	if ((tiflags & TH_URG) && th->th_urp &&
2733 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2734 		/*
2735 		 * This is a kludge, but if we receive and accept
2736 		 * random urgent pointers, we'll crash in
2737 		 * soreceive.  It's hard to imagine someone
2738 		 * actually wanting to send this much urgent data.
2739 		 */
2740 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2741 			th->th_urp = 0;			/* XXX */
2742 			tiflags &= ~TH_URG;		/* XXX */
2743 			goto dodata;			/* XXX */
2744 		}
2745 
2746 		/*
2747 		 * If this segment advances the known urgent pointer,
2748 		 * then mark the data stream.  This should not happen
2749 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2750 		 * a FIN has been received from the remote side.
2751 		 * In these states we ignore the URG.
2752 		 *
2753 		 * According to RFC961 (Assigned Protocols),
2754 		 * the urgent pointer points to the last octet
2755 		 * of urgent data.  We continue, however,
2756 		 * to consider it to indicate the first octet
2757 		 * of data past the urgent section as the original
2758 		 * spec states (in one of two places).
2759 		 */
2760 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2761 			tp->rcv_up = th->th_seq + th->th_urp;
2762 			so->so_oobmark = so->so_rcv.sb_cc +
2763 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2764 			if (so->so_oobmark == 0)
2765 				so->so_state |= SS_RCVATMARK;
2766 			sohasoutofband(so);
2767 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2768 		}
2769 
2770 		/*
2771 		 * Remove out of band data so doesn't get presented to user.
2772 		 * This can happen independent of advancing the URG pointer,
2773 		 * but if two URG's are pending at once, some out-of-band
2774 		 * data may creep in... ick.
2775 		 */
2776 		if (th->th_urp <= (u_int16_t)tlen &&
2777 		    (so->so_options & SO_OOBINLINE) == 0)
2778 			tcp_pulloutofband(so, th, m, hdroptlen);
2779 	} else {
2780 		/*
2781 		 * If no out of band data is expected,
2782 		 * pull receive urgent pointer along
2783 		 * with the receive window.
2784 		 */
2785 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2786 			tp->rcv_up = tp->rcv_nxt;
2787 	}
2788 dodata:
2789 
2790 	/*
2791 	 * Process the segment text, merging it into the TCP sequencing queue,
2792 	 * and arranging for acknowledgement of receipt if necessary.
2793 	 * This process logically involves adjusting tp->rcv_wnd as data
2794 	 * is presented to the user (this happens in tcp_usrreq.c,
2795 	 * tcp_rcvd()).  If a FIN has already been received on this
2796 	 * connection then we just ignore the text.
2797 	 */
2798 	if ((tlen || (tiflags & TH_FIN)) &&
2799 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2800 		/*
2801 		 * Handle the common case:
2802 		 *  o Segment is the next to be received, and
2803 		 *  o The queue is empty, and
2804 		 *  o The connection is established
2805 		 * In this case, we avoid calling tcp_reass.
2806 		 *
2807 		 * tcp_setup_ack: set DELACK for segments received in order,
2808 		 * but ack immediately when segments are out of order (so that
2809 		 * fast retransmit can work).
2810 		 */
2811 		TCP_REASS_LOCK(tp);
2812 		if (th->th_seq == tp->rcv_nxt &&
2813 		    TAILQ_FIRST(&tp->segq) == NULL &&
2814 		    tp->t_state == TCPS_ESTABLISHED) {
2815 			tcp_setup_ack(tp, th);
2816 			tp->rcv_nxt += tlen;
2817 			tiflags = th->th_flags & TH_FIN;
2818 			tcps = TCP_STAT_GETREF();
2819 			tcps[TCP_STAT_RCVPACK]++;
2820 			tcps[TCP_STAT_RCVBYTE] += tlen;
2821 			TCP_STAT_PUTREF();
2822 			nd_hint(tp);
2823 			if (so->so_state & SS_CANTRCVMORE) {
2824 				m_freem(m);
2825 			} else {
2826 				m_adj(m, hdroptlen);
2827 				sbappendstream(&(so)->so_rcv, m);
2828 			}
2829 			TCP_REASS_UNLOCK(tp);
2830 			sorwakeup(so);
2831 		} else {
2832 			m_adj(m, hdroptlen);
2833 			tiflags = tcp_reass(tp, th, m, tlen);
2834 			tp->t_flags |= TF_ACKNOW;
2835 		}
2836 
2837 		/*
2838 		 * Note the amount of data that peer has sent into
2839 		 * our window, in order to estimate the sender's
2840 		 * buffer size.
2841 		 */
2842 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2843 	} else {
2844 		m_freem(m);
2845 		m = NULL;
2846 		tiflags &= ~TH_FIN;
2847 	}
2848 
2849 	/*
2850 	 * If FIN is received ACK the FIN and let the user know
2851 	 * that the connection is closing.  Ignore a FIN received before
2852 	 * the connection is fully established.
2853 	 */
2854 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2855 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2856 			socantrcvmore(so);
2857 			tp->t_flags |= TF_ACKNOW;
2858 			tp->rcv_nxt++;
2859 		}
2860 		switch (tp->t_state) {
2861 
2862 	 	/*
2863 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2864 		 */
2865 		case TCPS_ESTABLISHED:
2866 			tp->t_state = TCPS_CLOSE_WAIT;
2867 			break;
2868 
2869 	 	/*
2870 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2871 		 * enter the CLOSING state.
2872 		 */
2873 		case TCPS_FIN_WAIT_1:
2874 			tp->t_state = TCPS_CLOSING;
2875 			break;
2876 
2877 	 	/*
2878 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2879 		 * starting the time-wait timer, turning off the other
2880 		 * standard timers.
2881 		 */
2882 		case TCPS_FIN_WAIT_2:
2883 			tp->t_state = TCPS_TIME_WAIT;
2884 			tcp_canceltimers(tp);
2885 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2886 			soisdisconnected(so);
2887 			break;
2888 
2889 		/*
2890 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2891 		 */
2892 		case TCPS_TIME_WAIT:
2893 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2894 			break;
2895 		}
2896 	}
2897 #ifdef TCP_DEBUG
2898 	if (so->so_options & SO_DEBUG)
2899 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2900 #endif
2901 
2902 	/*
2903 	 * Return any desired output.
2904 	 */
2905 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2906 		KERNEL_LOCK(1, NULL);
2907 		(void)tcp_output(tp);
2908 		KERNEL_UNLOCK_ONE(NULL);
2909 	}
2910 	if (tcp_saveti)
2911 		m_freem(tcp_saveti);
2912 
2913 	if (tp->t_state == TCPS_TIME_WAIT
2914 	    && (so->so_state & SS_NOFDREF)
2915 	    && (tp->t_inpcb || af != AF_INET)
2916 	    && (tp->t_in6pcb || af != AF_INET6)
2917 	    && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
2918 	    && TAILQ_EMPTY(&tp->segq)
2919 	    && vtw_add(af, tp)) {
2920 		;
2921 	}
2922 	return;
2923 
2924 badsyn:
2925 	/*
2926 	 * Received a bad SYN.  Increment counters and dropwithreset.
2927 	 */
2928 	TCP_STATINC(TCP_STAT_BADSYN);
2929 	tp = NULL;
2930 	goto dropwithreset;
2931 
2932 dropafterack:
2933 	/*
2934 	 * Generate an ACK dropping incoming segment if it occupies
2935 	 * sequence space, where the ACK reflects our state.
2936 	 */
2937 	if (tiflags & TH_RST)
2938 		goto drop;
2939 	goto dropafterack2;
2940 
2941 dropafterack_ratelim:
2942 	/*
2943 	 * We may want to rate-limit ACKs against SYN/RST attack.
2944 	 */
2945 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
2946 	    tcp_ackdrop_ppslim) == 0) {
2947 		/* XXX stat */
2948 		goto drop;
2949 	}
2950 
2951 dropafterack2:
2952 	m_freem(m);
2953 	tp->t_flags |= TF_ACKNOW;
2954 	KERNEL_LOCK(1, NULL);
2955 	(void)tcp_output(tp);
2956 	KERNEL_UNLOCK_ONE(NULL);
2957 	if (tcp_saveti)
2958 		m_freem(tcp_saveti);
2959 	return;
2960 
2961 dropwithreset_ratelim:
2962 	/*
2963 	 * We may want to rate-limit RSTs in certain situations,
2964 	 * particularly if we are sending an RST in response to
2965 	 * an attempt to connect to or otherwise communicate with
2966 	 * a port for which we have no socket.
2967 	 */
2968 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2969 	    tcp_rst_ppslim) == 0) {
2970 		/* XXX stat */
2971 		goto drop;
2972 	}
2973 
2974 dropwithreset:
2975 	/*
2976 	 * Generate a RST, dropping incoming segment.
2977 	 * Make ACK acceptable to originator of segment.
2978 	 */
2979 	if (tiflags & TH_RST)
2980 		goto drop;
2981 	if (tiflags & TH_ACK) {
2982 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2983 	} else {
2984 		if (tiflags & TH_SYN)
2985 			tlen++;
2986 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2987 		    TH_RST|TH_ACK);
2988 	}
2989 	if (tcp_saveti)
2990 		m_freem(tcp_saveti);
2991 	return;
2992 
2993 badcsum:
2994 drop:
2995 	/*
2996 	 * Drop space held by incoming segment and return.
2997 	 */
2998 	if (tp) {
2999 		if (tp->t_inpcb)
3000 			so = tp->t_inpcb->inp_socket;
3001 #ifdef INET6
3002 		else if (tp->t_in6pcb)
3003 			so = tp->t_in6pcb->in6p_socket;
3004 #endif
3005 		else
3006 			so = NULL;
3007 #ifdef TCP_DEBUG
3008 		if (so && (so->so_options & SO_DEBUG) != 0)
3009 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
3010 #endif
3011 	}
3012 	if (tcp_saveti)
3013 		m_freem(tcp_saveti);
3014 	m_freem(m);
3015 	return;
3016 }
3017 
3018 #ifdef TCP_SIGNATURE
3019 int
3020 tcp_signature_apply(void *fstate, void *data, u_int len)
3021 {
3022 
3023 	MD5Update(fstate, (u_char *)data, len);
3024 	return (0);
3025 }
3026 
3027 struct secasvar *
3028 tcp_signature_getsav(struct mbuf *m)
3029 {
3030 	struct ip *ip;
3031 	struct ip6_hdr *ip6;
3032 
3033 	ip = mtod(m, struct ip *);
3034 	switch (ip->ip_v) {
3035 	case 4:
3036 		ip = mtod(m, struct ip *);
3037 		ip6 = NULL;
3038 		break;
3039 	case 6:
3040 		ip = NULL;
3041 		ip6 = mtod(m, struct ip6_hdr *);
3042 		break;
3043 	default:
3044 		return (NULL);
3045 	}
3046 
3047 #ifdef IPSEC
3048 	union sockaddr_union dst;
3049 
3050 	/* Extract the destination from the IP header in the mbuf. */
3051 	memset(&dst, 0, sizeof(union sockaddr_union));
3052 	if (ip != NULL) {
3053 		dst.sa.sa_len = sizeof(struct sockaddr_in);
3054 		dst.sa.sa_family = AF_INET;
3055 		dst.sin.sin_addr = ip->ip_dst;
3056 	} else {
3057 		dst.sa.sa_len = sizeof(struct sockaddr_in6);
3058 		dst.sa.sa_family = AF_INET6;
3059 		dst.sin6.sin6_addr = ip6->ip6_dst;
3060 	}
3061 
3062 	/*
3063 	 * Look up an SADB entry which matches the address of the peer.
3064 	 */
3065 	return KEY_LOOKUP_SA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0);
3066 #else
3067 	return NULL;
3068 #endif
3069 }
3070 
3071 int
3072 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
3073     struct secasvar *sav, char *sig)
3074 {
3075 	MD5_CTX ctx;
3076 	struct ip *ip;
3077 	struct ipovly *ipovly;
3078 #ifdef INET6
3079 	struct ip6_hdr *ip6;
3080 	struct ip6_hdr_pseudo ip6pseudo;
3081 #endif
3082 	struct ippseudo ippseudo;
3083 	struct tcphdr th0;
3084 	int l, tcphdrlen;
3085 
3086 	if (sav == NULL)
3087 		return (-1);
3088 
3089 	tcphdrlen = th->th_off * 4;
3090 
3091 	switch (mtod(m, struct ip *)->ip_v) {
3092 	case 4:
3093 		MD5Init(&ctx);
3094 		ip = mtod(m, struct ip *);
3095 		memset(&ippseudo, 0, sizeof(ippseudo));
3096 		ipovly = (struct ipovly *)ip;
3097 		ippseudo.ippseudo_src = ipovly->ih_src;
3098 		ippseudo.ippseudo_dst = ipovly->ih_dst;
3099 		ippseudo.ippseudo_pad = 0;
3100 		ippseudo.ippseudo_p = IPPROTO_TCP;
3101 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
3102 		MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
3103 		break;
3104 #if INET6
3105 	case 6:
3106 		MD5Init(&ctx);
3107 		ip6 = mtod(m, struct ip6_hdr *);
3108 		memset(&ip6pseudo, 0, sizeof(ip6pseudo));
3109 		ip6pseudo.ip6ph_src = ip6->ip6_src;
3110 		in6_clearscope(&ip6pseudo.ip6ph_src);
3111 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
3112 		in6_clearscope(&ip6pseudo.ip6ph_dst);
3113 		ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
3114 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
3115 		MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
3116 		break;
3117 #endif
3118 	default:
3119 		return (-1);
3120 	}
3121 
3122 	th0 = *th;
3123 	th0.th_sum = 0;
3124 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
3125 
3126 	l = m->m_pkthdr.len - thoff - tcphdrlen;
3127 	if (l > 0)
3128 		m_apply(m, thoff + tcphdrlen,
3129 		    m->m_pkthdr.len - thoff - tcphdrlen,
3130 		    tcp_signature_apply, &ctx);
3131 
3132 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3133 	MD5Final(sig, &ctx);
3134 
3135 	return (0);
3136 }
3137 #endif
3138 
3139 /*
3140  * Parse and process tcp options.
3141  *
3142  * Returns -1 if this segment should be dropped.  (eg. wrong signature)
3143  * Otherwise returns 0.
3144  */
3145 int
3146 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt, struct tcphdr *th,
3147     struct mbuf *m, int toff, struct tcp_opt_info *oi)
3148 {
3149 	u_int16_t mss;
3150 	int opt, optlen = 0;
3151 #ifdef TCP_SIGNATURE
3152 	void *sigp = NULL;
3153 	char sigbuf[TCP_SIGLEN];
3154 	struct secasvar *sav = NULL;
3155 #endif
3156 
3157 	for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
3158 		opt = cp[0];
3159 		if (opt == TCPOPT_EOL)
3160 			break;
3161 		if (opt == TCPOPT_NOP)
3162 			optlen = 1;
3163 		else {
3164 			if (cnt < 2)
3165 				break;
3166 			optlen = cp[1];
3167 			if (optlen < 2 || optlen > cnt)
3168 				break;
3169 		}
3170 		switch (opt) {
3171 
3172 		default:
3173 			continue;
3174 
3175 		case TCPOPT_MAXSEG:
3176 			if (optlen != TCPOLEN_MAXSEG)
3177 				continue;
3178 			if (!(th->th_flags & TH_SYN))
3179 				continue;
3180 			if (TCPS_HAVERCVDSYN(tp->t_state))
3181 				continue;
3182 			memcpy(&mss, cp + 2, sizeof(mss));
3183 			oi->maxseg = ntohs(mss);
3184 			break;
3185 
3186 		case TCPOPT_WINDOW:
3187 			if (optlen != TCPOLEN_WINDOW)
3188 				continue;
3189 			if (!(th->th_flags & TH_SYN))
3190 				continue;
3191 			if (TCPS_HAVERCVDSYN(tp->t_state))
3192 				continue;
3193 			tp->t_flags |= TF_RCVD_SCALE;
3194 			tp->requested_s_scale = cp[2];
3195 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
3196 				char buf[INET6_ADDRSTRLEN];
3197 				struct ip *ip = mtod(m, struct ip *);
3198 #ifdef INET6
3199 				struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
3200 #endif
3201 
3202 				switch (ip->ip_v) {
3203 				case 4:
3204 					in_print(buf, sizeof(buf),
3205 					    &ip->ip_src);
3206 					break;
3207 #ifdef INET6
3208 				case 6:
3209 					in6_print(buf, sizeof(buf),
3210 					    &ip6->ip6_src);
3211 					break;
3212 #endif
3213 				default:
3214 					strlcpy(buf, "(unknown)", sizeof(buf));
3215 					break;
3216 				}
3217 
3218 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
3219 				    "assuming %d\n",
3220 				    tp->requested_s_scale, buf,
3221 				    TCP_MAX_WINSHIFT);
3222 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
3223 			}
3224 			break;
3225 
3226 		case TCPOPT_TIMESTAMP:
3227 			if (optlen != TCPOLEN_TIMESTAMP)
3228 				continue;
3229 			oi->ts_present = 1;
3230 			memcpy(&oi->ts_val, cp + 2, sizeof(oi->ts_val));
3231 			NTOHL(oi->ts_val);
3232 			memcpy(&oi->ts_ecr, cp + 6, sizeof(oi->ts_ecr));
3233 			NTOHL(oi->ts_ecr);
3234 
3235 			if (!(th->th_flags & TH_SYN))
3236 				continue;
3237 			if (TCPS_HAVERCVDSYN(tp->t_state))
3238 				continue;
3239 			/*
3240 			 * A timestamp received in a SYN makes
3241 			 * it ok to send timestamp requests and replies.
3242 			 */
3243 			tp->t_flags |= TF_RCVD_TSTMP;
3244 			tp->ts_recent = oi->ts_val;
3245 			tp->ts_recent_age = tcp_now;
3246                         break;
3247 
3248 		case TCPOPT_SACK_PERMITTED:
3249 			if (optlen != TCPOLEN_SACK_PERMITTED)
3250 				continue;
3251 			if (!(th->th_flags & TH_SYN))
3252 				continue;
3253 			if (TCPS_HAVERCVDSYN(tp->t_state))
3254 				continue;
3255 			if (tcp_do_sack) {
3256 				tp->t_flags |= TF_SACK_PERMIT;
3257 				tp->t_flags |= TF_WILL_SACK;
3258 			}
3259 			break;
3260 
3261 		case TCPOPT_SACK:
3262 			tcp_sack_option(tp, th, cp, optlen);
3263 			break;
3264 #ifdef TCP_SIGNATURE
3265 		case TCPOPT_SIGNATURE:
3266 			if (optlen != TCPOLEN_SIGNATURE)
3267 				continue;
3268 			if (sigp &&
3269 			    !consttime_memequal(sigp, cp + 2, TCP_SIGLEN))
3270 				return (-1);
3271 
3272 			sigp = sigbuf;
3273 			memcpy(sigbuf, cp + 2, TCP_SIGLEN);
3274 			tp->t_flags |= TF_SIGNATURE;
3275 			break;
3276 #endif
3277 		}
3278 	}
3279 
3280 #ifndef TCP_SIGNATURE
3281 	return 0;
3282 #else
3283 	if (tp->t_flags & TF_SIGNATURE) {
3284 		sav = tcp_signature_getsav(m);
3285 		if (sav == NULL && tp->t_state == TCPS_LISTEN)
3286 			return (-1);
3287 	}
3288 
3289 	if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE))
3290 		goto out;
3291 
3292 	if (sigp) {
3293 		char sig[TCP_SIGLEN];
3294 
3295 		tcp_fields_to_net(th);
3296 		if (tcp_signature(m, th, toff, sav, sig) < 0) {
3297 			tcp_fields_to_host(th);
3298 			goto out;
3299 		}
3300 		tcp_fields_to_host(th);
3301 
3302 		if (!consttime_memequal(sig, sigp, TCP_SIGLEN)) {
3303 			TCP_STATINC(TCP_STAT_BADSIG);
3304 			goto out;
3305 		} else
3306 			TCP_STATINC(TCP_STAT_GOODSIG);
3307 
3308 		key_sa_recordxfer(sav, m);
3309 		KEY_SA_UNREF(&sav);
3310 	}
3311 	return 0;
3312 out:
3313 	if (sav != NULL)
3314 		KEY_SA_UNREF(&sav);
3315 	return -1;
3316 #endif
3317 }
3318 
3319 /*
3320  * Pull out of band byte out of a segment so
3321  * it doesn't appear in the user's data queue.
3322  * It is still reflected in the segment length for
3323  * sequencing purposes.
3324  */
3325 void
3326 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3327     struct mbuf *m, int off)
3328 {
3329 	int cnt = off + th->th_urp - 1;
3330 
3331 	while (cnt >= 0) {
3332 		if (m->m_len > cnt) {
3333 			char *cp = mtod(m, char *) + cnt;
3334 			struct tcpcb *tp = sototcpcb(so);
3335 
3336 			tp->t_iobc = *cp;
3337 			tp->t_oobflags |= TCPOOB_HAVEDATA;
3338 			memmove(cp, cp + 1, (unsigned)(m->m_len - cnt - 1));
3339 			m->m_len--;
3340 			return;
3341 		}
3342 		cnt -= m->m_len;
3343 		m = m->m_next;
3344 		if (m == NULL)
3345 			break;
3346 	}
3347 	panic("tcp_pulloutofband");
3348 }
3349 
3350 /*
3351  * Collect new round-trip time estimate
3352  * and update averages and current timeout.
3353  *
3354  * rtt is in units of slow ticks (typically 500 ms) -- essentially the
3355  * difference of two timestamps.
3356  */
3357 void
3358 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3359 {
3360 	int32_t delta;
3361 
3362 	TCP_STATINC(TCP_STAT_RTTUPDATED);
3363 	if (tp->t_srtt != 0) {
3364 		/*
3365 		 * Compute the amount to add to srtt for smoothing,
3366 		 * *alpha, or 2^(-TCP_RTT_SHIFT).  Because
3367 		 * srtt is stored in 1/32 slow ticks, we conceptually
3368 		 * shift left 5 bits, subtract srtt to get the
3369 		 * difference, and then shift right by TCP_RTT_SHIFT
3370 		 * (3) to obtain 1/8 of the difference.
3371 		 */
3372 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3373 		/*
3374 		 * This can never happen, because delta's lowest
3375 		 * possible value is 1/8 of t_srtt.  But if it does,
3376 		 * set srtt to some reasonable value, here chosen
3377 		 * as 1/8 tick.
3378 		 */
3379 		if ((tp->t_srtt += delta) <= 0)
3380 			tp->t_srtt = 1 << 2;
3381 		/*
3382 		 * RFC2988 requires that rttvar be updated first.
3383 		 * This code is compliant because "delta" is the old
3384 		 * srtt minus the new observation (scaled).
3385 		 *
3386 		 * RFC2988 says:
3387 		 *   rttvar = (1-beta) * rttvar + beta * |srtt-observed|
3388 		 *
3389 		 * delta is in units of 1/32 ticks, and has then been
3390 		 * divided by 8.  This is equivalent to being in 1/16s
3391 		 * units and divided by 4.  Subtract from it 1/4 of
3392 		 * the existing rttvar to form the (signed) amount to
3393 		 * adjust.
3394 		 */
3395 		if (delta < 0)
3396 			delta = -delta;
3397 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3398 		/*
3399 		 * As with srtt, this should never happen.  There is
3400 		 * no support in RFC2988 for this operation.  But 1/4s
3401 		 * as rttvar when faced with something arguably wrong
3402 		 * is ok.
3403 		 */
3404 		if ((tp->t_rttvar += delta) <= 0)
3405 			tp->t_rttvar = 1 << 2;
3406 
3407 		/*
3408 		 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
3409 		 * Problem is: it doesn't work.  Disabled by defaulting
3410 		 * tcp_rttlocal to 0; see corresponding code in
3411 		 * tcp_subr that selects local vs remote in a different way.
3412 		 *
3413 		 * The static branch prediction hint here should be removed
3414 		 * when the rtt estimator is fixed and the rtt_enable code
3415 		 * is turned back on.
3416 		 */
3417 		if (__predict_false(tcp_rttlocal) && tcp_msl_enable
3418 		    && tp->t_srtt > tcp_msl_remote_threshold
3419 		    && tp->t_msl  < tcp_msl_remote) {
3420 			tp->t_msl = MIN(tcp_msl_remote, TCP_MAXMSL);
3421 		}
3422 	} else {
3423 		/*
3424 		 * This is the first measurement.  Per RFC2988, 2.2,
3425 		 * set rtt=R and srtt=R/2.
3426 		 * For srtt, storage representation is 1/32 ticks,
3427 		 * so shift left by 5.
3428 		 * For rttvar, storage representation is 1/16 ticks,
3429 		 * So shift left by 4, but then right by 1 to halve.
3430 		 */
3431 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3432 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3433 	}
3434 	tp->t_rtttime = 0;
3435 	tp->t_rxtshift = 0;
3436 
3437 	/*
3438 	 * the retransmit should happen at rtt + 4 * rttvar.
3439 	 * Because of the way we do the smoothing, srtt and rttvar
3440 	 * will each average +1/2 tick of bias.  When we compute
3441 	 * the retransmit timer, we want 1/2 tick of rounding and
3442 	 * 1 extra tick because of +-1/2 tick uncertainty in the
3443 	 * firing of the timer.  The bias will give us exactly the
3444 	 * 1.5 tick we need.  But, because the bias is
3445 	 * statistical, we have to test that we don't drop below
3446 	 * the minimum feasible timer (which is 2 ticks).
3447 	 */
3448 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3449 	    uimax(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3450 
3451 	/*
3452 	 * We received an ack for a packet that wasn't retransmitted;
3453 	 * it is probably safe to discard any error indications we've
3454 	 * received recently.  This isn't quite right, but close enough
3455 	 * for now (a route might have failed after we sent a segment,
3456 	 * and the return path might not be symmetrical).
3457 	 */
3458 	tp->t_softerror = 0;
3459 }
3460