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