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