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