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