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