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