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