xref: /openbsd-src/sys/netinet/tcp_input.c (revision 33b792a3c1c87b47219fdf9a73548c4003214de3)
1 /*	$OpenBSD: tcp_input.c,v 1.104 2002/01/24 22:42:48 provos 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. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
37  *
38  * NRL grants permission for redistribution and use in source and binary
39  * forms, with or without modification, of the software and documentation
40  * created at NRL provided that the following conditions are met:
41  *
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. All advertising materials mentioning features or use of this software
48  *    must display the following acknowledgements:
49  * 	This product includes software developed by the University of
50  * 	California, Berkeley and its contributors.
51  * 	This product includes software developed at the Information
52  * 	Technology Division, US Naval Research Laboratory.
53  * 4. Neither the name of the NRL nor the names of its contributors
54  *    may be used to endorse or promote products derived from this software
55  *    without specific prior written permission.
56  *
57  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
58  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
59  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
60  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
61  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
62  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
63  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
64  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
65  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
66  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
67  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
68  *
69  * The views and conclusions contained in the software and documentation
70  * are those of the authors and should not be interpreted as representing
71  * official policies, either expressed or implied, of the US Naval
72  * Research Laboratory (NRL).
73  */
74 
75 #ifndef TUBA_INCLUDE
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/mbuf.h>
79 #include <sys/protosw.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 
83 #include <net/if.h>
84 #include <net/route.h>
85 
86 #include <netinet/in.h>
87 #include <netinet/in_systm.h>
88 #include <netinet/ip.h>
89 #include <netinet/in_pcb.h>
90 #include <netinet/ip_var.h>
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_debug.h>
98 
99 #ifdef INET6
100 #include <netinet6/in6_var.h>
101 #include <netinet6/nd6.h>
102 
103 struct	tcpiphdr tcp_saveti;
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 int	tcprexmtthresh = 3;
113 struct	tcpiphdr tcp_saveti;
114 int	tcptv_keep_init = TCPTV_KEEP_INIT;
115 
116 extern u_long sb_max;
117 
118 int tcp_rst_ppslim = 100;		/* 100pps */
119 int tcp_rst_ppslim_count = 0;
120 struct timeval tcp_rst_ppslim_last;
121 
122 #endif /* TUBA_INCLUDE */
123 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
124 
125 /* for modulo comparisons of timestamps */
126 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
127 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
128 
129 /*
130  * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
131  */
132 #ifdef INET6
133 #define ND6_HINT(tp) \
134 do { \
135 	if (tp && tp->t_inpcb && (tp->t_inpcb->inp_flags & INP_IPV6) && \
136 	    tp->t_inpcb->inp_route6.ro_rt) { \
137 		nd6_nud_hint(tp->t_inpcb->inp_route6.ro_rt, NULL, 0); \
138 	} \
139 } while (0)
140 #else
141 #define ND6_HINT(tp)
142 #endif
143 
144 /*
145  * Insert segment ti into reassembly queue of tcp with
146  * control block tp.  Return TH_FIN if reassembly now includes
147  * a segment with FIN.  The macro form does the common case inline
148  * (segment is the next to be received on an established connection,
149  * and the queue is empty), avoiding linkage into and removal
150  * from the queue and repetition of various conversions.
151  * Set DELACK for segments received in order, but ack immediately
152  * when segments are out of order (so fast retransmit can work).
153  */
154 
155 #ifndef TUBA_INCLUDE
156 
157 int
158 tcp_reass(tp, th, m, tlen)
159 	register struct tcpcb *tp;
160 	register struct tcphdr *th;
161 	struct mbuf *m;
162 	int *tlen;
163 {
164 	register struct ipqent *p, *q, *nq, *tiqe;
165 	struct socket *so = tp->t_inpcb->inp_socket;
166 	int flags;
167 
168 	/*
169 	 * Call with th==0 after become established to
170 	 * force pre-ESTABLISHED data up to user socket.
171 	 */
172 	if (th == 0)
173 		goto present;
174 
175 	/*
176 	 * Allocate a new queue entry, before we throw away any data.
177 	 * If we can't, just drop the packet.  XXX
178 	 */
179 	tiqe =  pool_get(&ipqent_pool, PR_NOWAIT);
180 	if (tiqe == NULL) {
181 		tcpstat.tcps_rcvmemdrop++;
182 		m_freem(m);
183 		return (0);
184 	}
185 
186 	/*
187 	 * Find a segment which begins after this one does.
188 	 */
189 	for (p = NULL, q = tp->segq.lh_first; q != NULL;
190 	    p = q, q = q->ipqe_q.le_next)
191 		if (SEQ_GT(q->ipqe_tcp->th_seq, th->th_seq))
192 			break;
193 
194 	/*
195 	 * If there is a preceding segment, it may provide some of
196 	 * our data already.  If so, drop the data from the incoming
197 	 * segment.  If it provides all of our data, drop us.
198 	 */
199 	if (p != NULL) {
200 		register struct tcphdr *phdr = p->ipqe_tcp;
201 		register int i;
202 
203 		/* conversion to int (in i) handles seq wraparound */
204 		i = phdr->th_seq + phdr->th_reseqlen - th->th_seq;
205 		if (i > 0) {
206 		        if (i >= *tlen) {
207 				tcpstat.tcps_rcvduppack++;
208 				tcpstat.tcps_rcvdupbyte += *tlen;
209 				m_freem(m);
210 				pool_put(&ipqent_pool, tiqe);
211 				return (0);
212 			}
213 			m_adj(m, i);
214 			*tlen -= i;
215 			th->th_seq += i;
216 		}
217 	}
218 	tcpstat.tcps_rcvoopack++;
219 	tcpstat.tcps_rcvoobyte += *tlen;
220 
221 	/*
222 	 * While we overlap succeeding segments trim them or,
223 	 * if they are completely covered, dequeue them.
224 	 */
225 	for (; q != NULL; q = nq) {
226 		register struct tcphdr *qhdr = q->ipqe_tcp;
227 		register int i = (th->th_seq + *tlen) - qhdr->th_seq;
228 
229 		if (i <= 0)
230 			break;
231 		if (i < qhdr->th_reseqlen) {
232 			qhdr->th_seq += i;
233 			qhdr->th_reseqlen -= i;
234 			m_adj(q->ipqe_m, i);
235 			break;
236 		}
237 		nq = q->ipqe_q.le_next;
238 		m_freem(q->ipqe_m);
239 		LIST_REMOVE(q, ipqe_q);
240 		pool_put(&ipqent_pool, q);
241 	}
242 
243 	/* Insert the new fragment queue entry into place. */
244 	tiqe->ipqe_m = m;
245 	th->th_reseqlen = *tlen;
246 	tiqe->ipqe_tcp = th;
247 	if (p == NULL) {
248 		LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
249 	} else {
250 		LIST_INSERT_AFTER(p, tiqe, ipqe_q);
251 	}
252 
253 present:
254 	/*
255 	 * Present data to user, advancing rcv_nxt through
256 	 * completed sequence space.
257 	 */
258 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
259 		return (0);
260 	q = tp->segq.lh_first;
261 	if (q == NULL || q->ipqe_tcp->th_seq != tp->rcv_nxt)
262 		return (0);
263 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_tcp->th_reseqlen)
264 		return (0);
265 	do {
266 		tp->rcv_nxt += q->ipqe_tcp->th_reseqlen;
267 		flags = q->ipqe_tcp->th_flags & TH_FIN;
268 
269 		nq = q->ipqe_q.le_next;
270 		LIST_REMOVE(q, ipqe_q);
271 		ND6_HINT(tp);
272 		if (so->so_state & SS_CANTRCVMORE)
273 			m_freem(q->ipqe_m);
274 		else
275 			sbappend(&so->so_rcv, q->ipqe_m);
276 		pool_put(&ipqent_pool, q);
277 		q = nq;
278 	} while (q != NULL && q->ipqe_tcp->th_seq == tp->rcv_nxt);
279 	sorwakeup(so);
280 	return (flags);
281 }
282 
283 /*
284  * First check for a port-specific bomb. We do not want to drop half-opens
285  * for other ports if this is the only port being bombed.  We only check
286  * the bottom 40 half open connections, to avoid wasting too much time.
287  *
288  * Or, otherwise it is more likely a generic syn bomb, so delete the oldest
289  * half-open connection.
290  */
291 void
292 tcpdropoldhalfopen(avoidtp, port)
293 	struct tcpcb *avoidtp;
294 	u_int16_t port;
295 {
296 	register struct inpcb *inp;
297 	register struct tcpcb *tp;
298 	int ncheck = 40;
299 	int s;
300 
301 	s = splnet();
302 	inp = tcbtable.inpt_queue.cqh_first;
303 	if (inp)						/* XXX */
304 	for (; inp != (struct inpcb *)&tcbtable.inpt_queue && --ncheck;
305 	    inp = inp->inp_queue.cqe_prev) {
306 		if ((tp = (struct tcpcb *)inp->inp_ppcb) &&
307 		    tp != avoidtp &&
308 		    tp->t_state == TCPS_SYN_RECEIVED &&
309 		    port == inp->inp_lport) {
310 			tcp_close(tp);
311 			goto done;
312 		}
313 	}
314 
315 	inp = tcbtable.inpt_queue.cqh_first;
316 	if (inp)						/* XXX */
317 	for (; inp != (struct inpcb *)&tcbtable.inpt_queue;
318 	    inp = inp->inp_queue.cqe_prev) {
319 		if ((tp = (struct tcpcb *)inp->inp_ppcb) &&
320 		    tp != avoidtp &&
321 		    tp->t_state == TCPS_SYN_RECEIVED) {
322 			tcp_close(tp);
323 			goto done;
324 		}
325 	}
326 done:
327 	splx(s);
328 }
329 
330 #ifdef INET6
331 int
332 tcp6_input(mp, offp, proto)
333 	struct mbuf **mp;
334 	int *offp, proto;
335 {
336 	struct mbuf *m = *mp;
337 
338 #if defined(NFAITH) && 0 < NFAITH
339 	if (m->m_pkthdr.rcvif) {
340 		if (m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
341 			/* XXX send icmp6 host/port unreach? */
342 			m_freem(m);
343 			return IPPROTO_DONE;
344 		}
345 	}
346 #endif
347 
348 	/*
349 	 * draft-itojun-ipv6-tcp-to-anycast
350 	 * better place to put this in?
351 	 */
352 	if (m->m_flags & M_ANYCAST6) {
353 		if (m->m_len >= sizeof(struct ip6_hdr)) {
354 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
355 			icmp6_error(m, ICMP6_DST_UNREACH,
356 				ICMP6_DST_UNREACH_ADDR,
357 				(caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
358 		} else
359 			m_freem(m);
360 		return IPPROTO_DONE;
361 	}
362 
363 	tcp_input(m, *offp, proto);
364 	return IPPROTO_DONE;
365 }
366 #endif
367 
368 /*
369  * TCP input routine, follows pages 65-76 of the
370  * protocol specification dated September, 1981 very closely.
371  */
372 void
373 #if __STDC__
374 tcp_input(struct mbuf *m, ...)
375 #else
376 tcp_input(m, va_alist)
377 	register struct mbuf *m;
378 #endif
379 {
380 	struct ip *ip;
381 	register struct inpcb *inp;
382 	caddr_t optp = NULL;
383 	int optlen = 0;
384 	int len, tlen, off;
385 	register struct tcpcb *tp = 0;
386 	register int tiflags;
387 	struct socket *so = NULL;
388 	int todrop, acked, ourfinisacked, needoutput = 0;
389 	int hdroptlen = 0;
390 	short ostate = 0;
391 	struct in_addr laddr;
392 	int dropsocket = 0;
393 	int iss = 0;
394 	u_long tiwin;
395 	u_int32_t ts_val, ts_ecr;
396 	int ts_present = 0;
397 	int iphlen;
398 	va_list ap;
399 	register struct tcphdr *th;
400 #ifdef INET6
401 	struct in6_addr laddr6;
402 	struct ip6_hdr *ipv6 = NULL;
403 #endif /* INET6 */
404 #ifdef IPSEC
405 	struct m_tag *mtag;
406 	struct tdb_ident *tdbi;
407 	struct tdb *tdb;
408 	int error, s;
409 #endif /* IPSEC */
410 	int af;
411 
412 	va_start(ap, m);
413 	iphlen = va_arg(ap, int);
414 	va_end(ap);
415 
416 	tcpstat.tcps_rcvtotal++;
417 
418 	/*
419 	 * Before we do ANYTHING, we have to figure out if it's TCP/IPv6 or
420 	 * TCP/IPv4.
421  	 */
422 	switch (mtod(m, struct ip *)->ip_v) {
423 #ifdef INET6
424 	case 6:
425 		af = AF_INET6;
426 		break;
427 #endif
428 	case 4:
429 		af = AF_INET;
430 		break;
431 	default:
432 		m_freem(m);
433 		return;	/*EAFNOSUPPORT*/
434 	}
435 
436 	/*
437 	 * Get IP and TCP header together in first mbuf.
438 	 * Note: IP leaves IP header in first mbuf.
439 	 */
440 	switch (af) {
441 	case AF_INET:
442 #ifdef DIAGNOSTIC
443 		if (iphlen < sizeof(struct ip)) {
444 			m_freem(m);
445 			return;
446 		}
447 #endif /* DIAGNOSTIC */
448 		if (iphlen > sizeof(struct ip)) {
449 #if 0	/*XXX*/
450 			ip_stripoptions(m, (struct mbuf *)0);
451 			iphlen = sizeof(struct ip);
452 #else
453 			m_freem(m);
454 			return;
455 #endif
456 		}
457 		break;
458 #ifdef INET6
459 	case AF_INET6:
460 #ifdef DIAGNOSTIC
461 		if (iphlen < sizeof(struct ip6_hdr)) {
462 			m_freem(m);
463 			return;
464 		}
465 #endif /* DIAGNOSTIC */
466 		if (iphlen > sizeof(struct ip6_hdr)) {
467 #if 0 /*XXX*/
468 			ipv6_stripoptions(m, iphlen);
469 			iphlen = sizeof(struct ip6_hdr);
470 #else
471 			m_freem(m);
472 			return;
473 #endif
474 		}
475 		break;
476 #endif
477 	default:
478 		m_freem(m);
479 		return;
480 	}
481 
482 	if (m->m_len < iphlen + sizeof(struct tcphdr)) {
483 		m = m_pullup2(m, iphlen + sizeof(struct tcphdr));
484 		if (m == NULL) {
485 			tcpstat.tcps_rcvshort++;
486 			return;
487 		}
488 	}
489 
490 	ip = NULL;
491 #ifdef INET6
492 	ipv6 = NULL;
493 #endif
494 	switch (af) {
495 	case AF_INET:
496 	    {
497 		struct tcpiphdr *ti;
498 
499 		ip = mtod(m, struct ip *);
500 #if 1
501 		tlen = m->m_pkthdr.len - iphlen;
502 #else
503 		tlen = ((struct ip *)ti)->ip_len;
504 #endif
505 		ti = mtod(m, struct tcpiphdr *);
506 
507 		/*
508 		 * Checksum extended TCP header and data.
509 		 */
510 		len = sizeof(struct ip) + tlen;
511 		bzero(ti->ti_x1, sizeof ti->ti_x1);
512 		ti->ti_len = (u_int16_t)tlen;
513 		HTONS(ti->ti_len);
514 		if ((m->m_pkthdr.csum & M_TCP_CSUM_IN_OK) == 0) {
515 			if (m->m_pkthdr.csum & M_TCP_CSUM_IN_BAD) {
516 				tcpstat.tcps_inhwcsum++;
517 				tcpstat.tcps_rcvbadsum++;
518 				goto drop;
519 			}
520 			if ((ti->ti_sum = in_cksum(m, len)) != 0) {
521 				tcpstat.tcps_rcvbadsum++;
522 				goto drop;
523 			}
524 		} else {
525 			m->m_pkthdr.csum &= ~M_TCP_CSUM_IN_OK;
526 			tcpstat.tcps_inhwcsum++;
527 		}
528 		break;
529 	    }
530 #ifdef INET6
531 	case AF_INET6:
532 		ipv6 = mtod(m, struct ip6_hdr *);
533 		tlen = m->m_pkthdr.len - iphlen;
534 
535 		/* Be proactive about malicious use of IPv4 mapped address */
536 		if (IN6_IS_ADDR_V4MAPPED(&ipv6->ip6_src) ||
537 		    IN6_IS_ADDR_V4MAPPED(&ipv6->ip6_dst)) {
538 			/* XXX stat */
539 			goto drop;
540 		}
541 
542 		/*
543 		 * Be proactive about unspecified IPv6 address in source.
544 		 * As we use all-zero to indicate unbounded/unconnected pcb,
545 		 * unspecified IPv6 address can be used to confuse us.
546 		 *
547 		 * Note that packets with unspecified IPv6 destination is
548 		 * already dropped in ip6_input.
549 		 */
550 		if (IN6_IS_ADDR_UNSPECIFIED(&ipv6->ip6_src)) {
551 			/* XXX stat */
552 			goto drop;
553 		}
554 
555 		/*
556 		 * Checksum extended TCP header and data.
557 		 */
558 		if (in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr), tlen)) {
559 			tcpstat.tcps_rcvbadsum++;
560 			goto drop;
561 		}
562 		break;
563 #endif
564 	}
565 #endif /* TUBA_INCLUDE */
566 
567 	th = (struct tcphdr *)(mtod(m, caddr_t) + iphlen);
568 
569 	/*
570 	 * Check that TCP offset makes sense,
571 	 * pull out TCP options and adjust length.		XXX
572 	 */
573 	off = th->th_off << 2;
574 	if (off < sizeof(struct tcphdr) || off > tlen) {
575 		tcpstat.tcps_rcvbadoff++;
576 		goto drop;
577 	}
578 	tlen -= off;
579 	if (off > sizeof(struct tcphdr)) {
580 		if (m->m_len < iphlen + off) {
581 			if ((m = m_pullup2(m, iphlen + off)) == NULL) {
582 				tcpstat.tcps_rcvshort++;
583 				return;
584 			}
585 			switch (af) {
586 			case AF_INET:
587 				ip = mtod(m, struct ip *);
588 				break;
589 #ifdef INET6
590 			case AF_INET6:
591 				ipv6 = mtod(m, struct ip6_hdr *);
592 				break;
593 #endif
594 			}
595 			th = (struct tcphdr *)(mtod(m, caddr_t) + iphlen);
596 		}
597 		optlen = off - sizeof(struct tcphdr);
598 		optp = mtod(m, caddr_t) + iphlen + sizeof(struct tcphdr);
599 		/*
600 		 * Do quick retrieval of timestamp options ("options
601 		 * prediction?").  If timestamp is the only option and it's
602 		 * formatted as recommended in RFC 1323 appendix A, we
603 		 * quickly get the values now and not bother calling
604 		 * tcp_dooptions(), etc.
605 		 */
606 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
607 		     (optlen > TCPOLEN_TSTAMP_APPA &&
608 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
609 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
610 		     (th->th_flags & TH_SYN) == 0) {
611 			ts_present = 1;
612 			ts_val = ntohl(*(u_int32_t *)(optp + 4));
613 			ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
614 			optp = NULL;	/* we've parsed the options */
615 		}
616 	}
617 	tiflags = th->th_flags;
618 
619 	/*
620 	 * Convert TCP protocol specific fields to host format.
621 	 */
622 	NTOHL(th->th_seq);
623 	NTOHL(th->th_ack);
624 	NTOHS(th->th_win);
625 	NTOHS(th->th_urp);
626 
627 	/*
628 	 * Locate pcb for segment.
629 	 */
630 findpcb:
631 	switch (af) {
632 #ifdef INET6
633 	case AF_INET6:
634 		inp = in6_pcbhashlookup(&tcbtable, &ipv6->ip6_src, th->th_sport,
635 		    &ipv6->ip6_dst, th->th_dport);
636 		break;
637 #endif
638 	case AF_INET:
639 		inp = in_pcbhashlookup(&tcbtable, ip->ip_src, th->th_sport,
640 		    ip->ip_dst, th->th_dport);
641 		break;
642 	}
643 	if (inp == 0) {
644 		++tcpstat.tcps_pcbhashmiss;
645 		switch (af) {
646 #ifdef INET6
647 		case AF_INET6:
648 			inp = in_pcblookup(&tcbtable, &ipv6->ip6_src,
649 			    th->th_sport, &ipv6->ip6_dst, th->th_dport,
650 			    INPLOOKUP_WILDCARD | INPLOOKUP_IPV6);
651 			break;
652 #endif /* INET6 */
653 		case AF_INET:
654 			inp = in_pcblookup(&tcbtable, &ip->ip_src, th->th_sport,
655 			    &ip->ip_dst, th->th_dport, INPLOOKUP_WILDCARD);
656 			break;
657 		}
658 		/*
659 		 * If the state is CLOSED (i.e., TCB does not exist) then
660 		 * all data in the incoming segment is discarded.
661 		 * If the TCB exists but is in CLOSED state, it is embryonic,
662 		 * but should either do a listen or a connect soon.
663 		 */
664 		if (inp == 0) {
665 			++tcpstat.tcps_noport;
666 			goto dropwithreset_ratelim;
667 		}
668 	}
669 
670 	tp = intotcpcb(inp);
671 	if (tp == 0)
672 		goto dropwithreset_ratelim;
673 	if (tp->t_state == TCPS_CLOSED)
674 		goto drop;
675 
676 	/* Unscale the window into a 32-bit value. */
677 	if ((tiflags & TH_SYN) == 0)
678 		tiwin = th->th_win << tp->snd_scale;
679 	else
680 		tiwin = th->th_win;
681 
682 	so = inp->inp_socket;
683 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
684 		if (so->so_options & SO_DEBUG) {
685 			ostate = tp->t_state;
686 			switch (af) {
687 #ifdef INET6
688 			case AF_INET6:
689 				tcp_saveti6 = *(mtod(m, struct tcpipv6hdr *));
690 				break;
691 #endif
692 			case AF_INET:
693 				tcp_saveti = *(mtod(m, struct tcpiphdr *));
694 				break;
695 			}
696 		}
697 		if (so->so_options & SO_ACCEPTCONN) {
698 			struct socket *so1;
699 
700 			so1 = sonewconn(so, 0);
701 			if (so1 == NULL) {
702 				tcpdropoldhalfopen(tp, th->th_dport);
703 				so1 = sonewconn(so, 0);
704 				if (so1 == NULL)
705 					goto drop;
706 			}
707 			so = so1;
708 			/*
709 			 * This is ugly, but ....
710 			 *
711 			 * Mark socket as temporary until we're
712 			 * committed to keeping it.  The code at
713 			 * ``drop'' and ``dropwithreset'' check the
714 			 * flag dropsocket to see if the temporary
715 			 * socket created here should be discarded.
716 			 * We mark the socket as discardable until
717 			 * we're committed to it below in TCPS_LISTEN.
718 			 */
719 			dropsocket++;
720 #ifdef IPSEC
721 			/*
722 			 * We need to copy the required security levels
723 			 * from the old pcb. Ditto for any other
724 			 * IPsec-related information.
725 			 */
726 			{
727 			  struct inpcb *newinp = (struct inpcb *)so->so_pcb;
728 			  bcopy(inp->inp_seclevel, newinp->inp_seclevel,
729 				sizeof(inp->inp_seclevel));
730 			  newinp->inp_secrequire = inp->inp_secrequire;
731 			  if (inp->inp_ipsec_localid != NULL) {
732 			  	newinp->inp_ipsec_localid = inp->inp_ipsec_localid;
733 				inp->inp_ipsec_localid->ref_count++;
734 			  }
735 			  if (inp->inp_ipsec_remoteid != NULL) {
736 			  	newinp->inp_ipsec_remoteid = inp->inp_ipsec_remoteid;
737 				inp->inp_ipsec_remoteid->ref_count++;
738 			  }
739 			  if (inp->inp_ipsec_localcred != NULL) {
740 			  	newinp->inp_ipsec_localcred = inp->inp_ipsec_localcred;
741 				inp->inp_ipsec_localcred->ref_count++;
742 			  }
743 			  if (inp->inp_ipsec_remotecred != NULL) {
744 			  	newinp->inp_ipsec_remotecred = inp->inp_ipsec_remotecred;
745 				inp->inp_ipsec_remotecred->ref_count++;
746 			  }
747 			  if (inp->inp_ipsec_localauth != NULL) {
748 			  	newinp->inp_ipsec_localauth
749 				  = inp->inp_ipsec_localauth;
750 				inp->inp_ipsec_localauth->ref_count++;
751 			  }
752 			  if (inp->inp_ipsec_remoteauth != NULL) {
753 			  	newinp->inp_ipsec_remoteauth
754 				  = inp->inp_ipsec_remoteauth;
755 				inp->inp_ipsec_remoteauth->ref_count++;
756 			  }
757 			}
758 #endif /* IPSEC */
759 #ifdef INET6
760 			/*
761 			 * inp still has the OLD in_pcb stuff, set the
762 			 * v6-related flags on the new guy, too.   This is
763 			 * done particularly for the case where an AF_INET6
764 			 * socket is bound only to a port, and a v4 connection
765 			 * comes in on that port.
766 			 * we also copy the flowinfo from the original pcb
767 			 * to the new one.
768 			 */
769 			{
770 			  int flags = inp->inp_flags;
771 			  struct inpcb *oldinpcb = inp;
772 
773 			  inp = (struct inpcb *)so->so_pcb;
774 			  inp->inp_flags |= (flags & INP_IPV6);
775 			  if ((inp->inp_flags & INP_IPV6) != 0) {
776 			    inp->inp_ipv6.ip6_hlim =
777 			      oldinpcb->inp_ipv6.ip6_hlim;
778 			    inp->inp_ipv6.ip6_flow =
779 			      oldinpcb->inp_ipv6.ip6_flow;
780 			  }
781 			}
782 #else /* INET6 */
783 			inp = (struct inpcb *)so->so_pcb;
784 #endif /* INET6 */
785 			inp->inp_lport = th->th_dport;
786 			switch (af) {
787 #ifdef INET6
788 			case AF_INET6:
789 				inp->inp_laddr6 = ipv6->ip6_dst;
790 
791 				/*inp->inp_options = ip6_srcroute();*/ /* soon. */
792 				/*
793 				 * still need to tweak outbound options
794 				 * processing to include this mbuf in
795 				 * the right place and put the correct
796 				 * NextHdr values in the right places.
797 				 * XXX  rja
798 				 */
799 				break;
800 #endif /* INET6 */
801 			case AF_INET:
802 				inp->inp_laddr = ip->ip_dst;
803 				inp->inp_options = ip_srcroute();
804 				break;
805 			}
806 			in_pcbrehash(inp);
807 			tp = intotcpcb(inp);
808 			tp->t_state = TCPS_LISTEN;
809 
810 			/* Compute proper scaling value from buffer space */
811 			tcp_rscale(tp, so->so_rcv.sb_hiwat);
812 		}
813 	}
814 
815 #ifdef IPSEC
816 	/* Find most recent IPsec tag */
817 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
818         s = splnet();
819 	if (mtag != NULL) {
820 		tdbi = (struct tdb_ident *)(mtag + 1);
821 	        tdb = gettdb(tdbi->spi, &tdbi->dst, tdbi->proto);
822 	} else
823 		tdb = NULL;
824 	ipsp_spd_lookup(m, af, iphlen, &error, IPSP_DIRECTION_IN,
825 	    tdb, inp);
826 
827 	/* Latch SA */
828 	if (inp->inp_tdb_in != tdb) {
829 		if (tdb) {
830 		        tdb_add_inp(tdb, inp, 1);
831 			if (inp->inp_ipsec_remoteid == NULL &&
832 			    tdb->tdb_srcid != NULL) {
833 				inp->inp_ipsec_remoteid = tdb->tdb_srcid;
834 				tdb->tdb_srcid->ref_count++;
835 			}
836 			if (inp->inp_ipsec_remotecred == NULL &&
837 			    tdb->tdb_remote_cred != NULL) {
838 				inp->inp_ipsec_remotecred =
839 				    tdb->tdb_remote_cred;
840 				tdb->tdb_remote_cred->ref_count++;
841 			}
842 			if (inp->inp_ipsec_remoteauth == NULL &&
843 			    tdb->tdb_remote_auth != NULL) {
844 				inp->inp_ipsec_remoteauth =
845 				    tdb->tdb_remote_auth;
846 				tdb->tdb_remote_auth->ref_count++;
847 			}
848 		} else { /* Just reset */
849 		        TAILQ_REMOVE(&inp->inp_tdb_in->tdb_inp_in, inp,
850 				     inp_tdb_in_next);
851 			inp->inp_tdb_in = NULL;
852 		}
853 	}
854         splx(s);
855 
856 	/* Error or otherwise drop-packet indication */
857 	if (error)
858 		goto drop;
859 #endif /* IPSEC */
860 
861 	/*
862 	 * Segment received on connection.
863 	 * Reset idle time and keep-alive timer.
864 	 */
865 	tp->t_idle = 0;
866 	if (tp->t_state != TCPS_SYN_RECEIVED)
867 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
868 
869 #ifdef TCP_SACK
870 	if (!tp->sack_disable)
871 		tcp_del_sackholes(tp, th); /* Delete stale SACK holes */
872 #endif /* TCP_SACK */
873 
874 	/*
875 	 * Process options if not in LISTEN state,
876 	 * else do it below (after getting remote address).
877 	 */
878 	if (optp && tp->t_state != TCPS_LISTEN)
879 		tcp_dooptions(tp, optp, optlen, th,
880 			&ts_present, &ts_val, &ts_ecr);
881 
882 #ifdef TCP_SACK
883 	if (!tp->sack_disable) {
884 		tp->rcv_laststart = th->th_seq; /* last rec'vd segment*/
885 		tp->rcv_lastend = th->th_seq + tlen;
886 	}
887 #endif /* TCP_SACK */
888 	/*
889 	 * Header prediction: check for the two common cases
890 	 * of a uni-directional data xfer.  If the packet has
891 	 * no control flags, is in-sequence, the window didn't
892 	 * change and we're not retransmitting, it's a
893 	 * candidate.  If the length is zero and the ack moved
894 	 * forward, we're the sender side of the xfer.  Just
895 	 * free the data acked & wake any higher level process
896 	 * that was blocked waiting for space.  If the length
897 	 * is non-zero and the ack didn't move, we're the
898 	 * receiver side.  If we're getting packets in-order
899 	 * (the reassembly queue is empty), add the data to
900 	 * the socket buffer and note that we need a delayed ack.
901 	 */
902 	if (tp->t_state == TCPS_ESTABLISHED &&
903 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
904 	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) &&
905 	    th->th_seq == tp->rcv_nxt &&
906 	    tiwin && tiwin == tp->snd_wnd &&
907 	    tp->snd_nxt == tp->snd_max) {
908 
909 		/*
910 		 * If last ACK falls within this segment's sequence numbers,
911 		 *  record the timestamp.
912 		 * Fix from Braden, see Stevens p. 870
913 		 */
914 		if (ts_present && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
915 			tp->ts_recent_age = tcp_now;
916 			tp->ts_recent = ts_val;
917 		}
918 
919 		if (tlen == 0) {
920 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
921 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
922 			    tp->snd_cwnd >= tp->snd_wnd &&
923 			    tp->t_dupacks == 0) {
924 				/*
925 				 * this is a pure ack for outstanding data.
926 				 */
927 				++tcpstat.tcps_predack;
928 				if (ts_present)
929 					tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
930 				else if (tp->t_rtt &&
931 					    SEQ_GT(th->th_ack, tp->t_rtseq))
932 					tcp_xmit_timer(tp, tp->t_rtt);
933 				acked = th->th_ack - tp->snd_una;
934 				tcpstat.tcps_rcvackpack++;
935 				tcpstat.tcps_rcvackbyte += acked;
936 				ND6_HINT(tp);
937 				sbdrop(&so->so_snd, acked);
938 				tp->snd_una = th->th_ack;
939 #if defined(TCP_SACK)
940 				/*
941 				 * We want snd_last to track snd_una so
942 				 * as to avoid sequence wraparound problems
943 				 * for very large transfers.
944 				 */
945 				tp->snd_last = tp->snd_una;
946 #endif /* TCP_SACK */
947 #if defined(TCP_SACK) && defined(TCP_FACK)
948 				tp->snd_fack = tp->snd_una;
949 				tp->retran_data = 0;
950 #endif /* TCP_FACK */
951 				m_freem(m);
952 
953 				/*
954 				 * If all outstanding data are acked, stop
955 				 * retransmit timer, otherwise restart timer
956 				 * using current (possibly backed-off) value.
957 				 * If process is waiting for space,
958 				 * wakeup/selwakeup/signal.  If data
959 				 * are ready to send, let tcp_output
960 				 * decide between more output or persist.
961 				 */
962 				if (tp->snd_una == tp->snd_max)
963 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
964 				else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
965 					TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
966 
967 				if (sb_notify(&so->so_snd))
968 					sowwakeup(so);
969 				if (so->so_snd.sb_cc)
970 					(void) tcp_output(tp);
971 				return;
972 			}
973 		} else if (th->th_ack == tp->snd_una &&
974 		    tp->segq.lh_first == NULL &&
975 		    tlen <= sbspace(&so->so_rcv)) {
976 			/*
977 			 * This is a pure, in-sequence data packet
978 			 * with nothing on the reassembly queue and
979 			 * we have enough buffer space to take it.
980 			 */
981 #ifdef TCP_SACK
982 			/* Clean receiver SACK report if present */
983 			if (!tp->sack_disable && tp->rcv_numsacks)
984 				tcp_clean_sackreport(tp);
985 #endif /* TCP_SACK */
986 			++tcpstat.tcps_preddat;
987 			tp->rcv_nxt += tlen;
988 			tcpstat.tcps_rcvpack++;
989 			tcpstat.tcps_rcvbyte += tlen;
990 			ND6_HINT(tp);
991 			/*
992 			 * Drop TCP, IP headers and TCP options then add data
993 			 * to socket buffer.
994 			 */
995 			if (th->th_flags & TH_PUSH)
996 				tp->t_flags |= TF_ACKNOW;
997 			else
998 				tp->t_flags |= TF_DELACK;
999 			m_adj(m, iphlen + off);
1000 			sbappend(&so->so_rcv, m);
1001 			sorwakeup(so);
1002 			return;
1003 		}
1004 	}
1005 
1006 	/*
1007 	 * Compute mbuf offset to TCP data segment.
1008 	 */
1009 	hdroptlen = iphlen + off;
1010 
1011 	/*
1012 	 * Calculate amount of space in receive window,
1013 	 * and then do TCP input processing.
1014 	 * Receive window is amount of space in rcv queue,
1015 	 * but not less than advertised window.
1016 	 */
1017 	{ int win;
1018 
1019 	win = sbspace(&so->so_rcv);
1020 	if (win < 0)
1021 		win = 0;
1022 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1023 	}
1024 
1025 	switch (tp->t_state) {
1026 
1027 	/*
1028 	 * If the state is LISTEN then ignore segment if it contains an RST.
1029 	 * If the segment contains an ACK then it is bad and send a RST.
1030 	 * If it does not contain a SYN then it is not interesting; drop it.
1031 	 * If it is from this socket, drop it, it must be forged.
1032 	 * Don't bother responding if the destination was a broadcast.
1033 	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1034 	 * tp->iss, and send a segment:
1035 	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1036 	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1037 	 * Fill in remote peer address fields if not previously specified.
1038 	 * Enter SYN_RECEIVED state, and process any other fields of this
1039 	 * segment in this state.
1040 	 */
1041 	case TCPS_LISTEN: {
1042 		struct mbuf *am;
1043 		register struct sockaddr_in *sin;
1044 #ifdef INET6
1045 		register struct sockaddr_in6 *sin6;
1046 #endif /* INET6 */
1047 
1048 		if (tiflags & TH_RST)
1049 			goto drop;
1050 		if (tiflags & TH_ACK)
1051 			goto dropwithreset;
1052 		if ((tiflags & TH_SYN) == 0)
1053 			goto drop;
1054 		if (th->th_dport == th->th_sport) {
1055 			switch (af) {
1056 #ifdef INET6
1057 			case AF_INET6:
1058 				if (IN6_ARE_ADDR_EQUAL(&ipv6->ip6_src,
1059 				    &ipv6->ip6_dst))
1060 					goto drop;
1061 				break;
1062 #endif /* INET6 */
1063 			case AF_INET:
1064 				if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1065 					goto drop;
1066 				break;
1067 			}
1068 		}
1069 
1070 		/*
1071 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1072 		 * in_broadcast() should never return true on a received
1073 		 * packet with M_BCAST not set.
1074 		 */
1075 		if (m->m_flags & (M_BCAST|M_MCAST))
1076 			goto drop;
1077 		switch (af) {
1078 #ifdef INET6
1079 		case AF_INET6:
1080 			/* XXX What about IPv6 Anycasting ?? :-(  rja */
1081 			if (IN6_IS_ADDR_MULTICAST(&ipv6->ip6_dst))
1082 				goto drop;
1083 			break;
1084 #endif /* INET6 */
1085 		case AF_INET:
1086 			if (IN_MULTICAST(ip->ip_dst.s_addr))
1087 				goto drop;
1088 			break;
1089 		}
1090 		am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
1091 		if (am == NULL)
1092 			goto drop;
1093 		switch (af) {
1094 #ifdef INET6
1095 		case AF_INET6:
1096 			/*
1097 			 * This is probably the place to set the tp->pf value.
1098 			 * (Don't forget to do it in the v4 code as well!)
1099 			 *
1100 			 * Also, remember to blank out things like flowlabel, or
1101 			 * set flowlabel for accepted sockets in v6.
1102 			 *
1103 			 * FURTHERMORE, this is PROBABLY the place where the
1104 			 * whole business of key munging is set up for passive
1105 			 * connections.
1106 			 */
1107 			am->m_len = sizeof(struct sockaddr_in6);
1108 			sin6 = mtod(am, struct sockaddr_in6 *);
1109 			sin6->sin6_family = AF_INET6;
1110 			sin6->sin6_len = sizeof(struct sockaddr_in6);
1111 			sin6->sin6_addr = ipv6->ip6_src;
1112 			sin6->sin6_port = th->th_sport;
1113 			sin6->sin6_flowinfo = htonl(0x0fffffff) &
1114 				inp->inp_ipv6.ip6_flow;
1115 			laddr6 = inp->inp_laddr6;
1116 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
1117 				inp->inp_laddr6 = ipv6->ip6_dst;
1118 			/* This is a good optimization. */
1119 			if (in6_pcbconnect(inp, am)) {
1120 				inp->inp_laddr6 = laddr6;
1121 				(void) m_free(am);
1122 				goto drop;
1123 			}
1124 			break;
1125 #endif
1126 		case AF_INET:
1127 			/* drop IPv4 packet to AF_INET6 socket */
1128 			if (inp->inp_flags & INP_IPV6) {
1129 				(void) m_free(am);
1130 				goto drop;
1131 			}
1132 			am->m_len = sizeof(struct sockaddr_in);
1133 			sin = mtod(am, struct sockaddr_in *);
1134 			sin->sin_family = AF_INET;
1135 			sin->sin_len = sizeof(*sin);
1136 			sin->sin_addr = ip->ip_src;
1137 			sin->sin_port = th->th_sport;
1138 			bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
1139 			laddr = inp->inp_laddr;
1140 			if (inp->inp_laddr.s_addr == INADDR_ANY)
1141 				inp->inp_laddr = ip->ip_dst;
1142 			if (in_pcbconnect(inp, am)) {
1143 				inp->inp_laddr = laddr;
1144 				(void) m_free(am);
1145 				goto drop;
1146 			}
1147 			(void) m_free(am);
1148 			break;
1149 		}
1150 		tp->t_template = tcp_template(tp);
1151 		if (tp->t_template == 0) {
1152 			tp = tcp_drop(tp, ENOBUFS);
1153 			dropsocket = 0;		/* socket is already gone */
1154 			goto drop;
1155 		}
1156 		if (optp)
1157 			tcp_dooptions(tp, optp, optlen, th,
1158 				&ts_present, &ts_val, &ts_ecr);
1159 #ifdef TCP_SACK
1160 		/*
1161 		 * If peer did not send a SACK_PERMITTED option (i.e., if
1162 		 * tcp_dooptions() did not set TF_SACK_PERMIT), set
1163                  * sack_disable to 1 if it is currently 0.
1164                  */
1165                 if (!tp->sack_disable)
1166                         if ((tp->t_flags & TF_SACK_PERMIT) == 0)
1167                                 tp->sack_disable = 1;
1168 #endif
1169 
1170 		if (iss)
1171 			tp->iss = iss;
1172 		else {
1173 #ifdef TCP_COMPAT_42
1174 			tcp_iss += TCP_ISSINCR/2;
1175 			tp->iss = tcp_iss;
1176 #else /* TCP_COMPAT_42 */
1177 			tp->iss = tcp_rndiss_next();
1178 #endif /* !TCP_COMPAT_42 */
1179 		}
1180 		tp->irs = th->th_seq;
1181 		tcp_sendseqinit(tp);
1182 #if defined (TCP_SACK)
1183 		tp->snd_last = tp->snd_una;
1184 #endif /* TCP_SACK */
1185 #if defined(TCP_SACK) && defined(TCP_FACK)
1186 		tp->snd_fack = tp->snd_una;
1187 		tp->retran_data = 0;
1188 		tp->snd_awnd = 0;
1189 #endif /* TCP_FACK */
1190 		tcp_rcvseqinit(tp);
1191 		tp->t_flags |= TF_ACKNOW;
1192 		tp->t_state = TCPS_SYN_RECEIVED;
1193 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcptv_keep_init);
1194 		dropsocket = 0;		/* committed to socket */
1195 		tcpstat.tcps_accepts++;
1196 		goto trimthenstep6;
1197 		}
1198 
1199 	/*
1200 	 * If the state is SYN_RECEIVED:
1201 	 * 	if seg contains SYN/ACK, send an RST.
1202 	 *	if seg contains an ACK, but not for our SYN/ACK, send an RST
1203   	 */
1204 
1205 	case TCPS_SYN_RECEIVED:
1206 		if (tiflags & TH_ACK) {
1207 			if (tiflags & TH_SYN) {
1208 				tcpstat.tcps_badsyn++;
1209 				goto dropwithreset;
1210 			}
1211 			if (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1212 			    SEQ_GT(th->th_ack, tp->snd_max))
1213 				goto dropwithreset;
1214 		}
1215 		break;
1216 
1217 	/*
1218 	 * If the state is SYN_SENT:
1219 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1220 	 *	if seg contains a RST, then drop the connection.
1221 	 *	if seg does not contain SYN, then drop it.
1222 	 * Otherwise this is an acceptable SYN segment
1223 	 *	initialize tp->rcv_nxt and tp->irs
1224 	 *	if seg contains ack then advance tp->snd_una
1225 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1226 	 *	arrange for segment to be acked (eventually)
1227 	 *	continue processing rest of data/controls, beginning with URG
1228 	 */
1229 	case TCPS_SYN_SENT:
1230 		if ((tiflags & TH_ACK) &&
1231 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1232 		     SEQ_GT(th->th_ack, tp->snd_max)))
1233 			goto dropwithreset;
1234 		if (tiflags & TH_RST) {
1235 			if (tiflags & TH_ACK)
1236 				tp = tcp_drop(tp, ECONNREFUSED);
1237 			goto drop;
1238 		}
1239 		if ((tiflags & TH_SYN) == 0)
1240 			goto drop;
1241 		if (tiflags & TH_ACK) {
1242 			tp->snd_una = th->th_ack;
1243 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1244 				tp->snd_nxt = tp->snd_una;
1245 		}
1246 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
1247 		tp->irs = th->th_seq;
1248 		tcp_rcvseqinit(tp);
1249 		tp->t_flags |= TF_ACKNOW;
1250 #ifdef TCP_SACK
1251                 /*
1252                  * If we've sent a SACK_PERMITTED option, and the peer
1253                  * also replied with one, then TF_SACK_PERMIT should have
1254                  * been set in tcp_dooptions().  If it was not, disable SACKs.
1255                  */
1256                 if (!tp->sack_disable)
1257                         if ((tp->t_flags & TF_SACK_PERMIT) == 0)
1258                                 tp->sack_disable = 1;
1259 #endif
1260 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
1261 			tcpstat.tcps_connects++;
1262 			soisconnected(so);
1263 			tp->t_state = TCPS_ESTABLISHED;
1264 			/* Do window scaling on this connection? */
1265 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1266 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1267 				tp->snd_scale = tp->requested_s_scale;
1268 				tp->rcv_scale = tp->request_r_scale;
1269 			}
1270 			(void) tcp_reass(tp, (struct tcphdr *)0,
1271 				(struct mbuf *)0, &tlen);
1272 			/*
1273 			 * if we didn't have to retransmit the SYN,
1274 			 * use its rtt as our initial srtt & rtt var.
1275 			 */
1276 			if (tp->t_rtt)
1277 				tcp_xmit_timer(tp, tp->t_rtt);
1278 			/*
1279 			 * Since new data was acked (the SYN), open the
1280 			 * congestion window by one MSS.  We do this
1281 			 * here, because we won't go through the normal
1282 			 * ACK processing below.  And since this is the
1283 			 * start of the connection, we know we are in
1284 			 * the exponential phase of slow-start.
1285 			 */
1286 			tp->snd_cwnd += tp->t_maxseg;
1287 		} else
1288 			tp->t_state = TCPS_SYN_RECEIVED;
1289 
1290 trimthenstep6:
1291 		/*
1292 		 * Advance th->th_seq to correspond to first data byte.
1293 		 * If data, trim to stay within window,
1294 		 * dropping FIN if necessary.
1295 		 */
1296 		th->th_seq++;
1297 		if (tlen > tp->rcv_wnd) {
1298 			todrop = tlen - tp->rcv_wnd;
1299 			m_adj(m, -todrop);
1300 			tlen = tp->rcv_wnd;
1301 			tiflags &= ~TH_FIN;
1302 			tcpstat.tcps_rcvpackafterwin++;
1303 			tcpstat.tcps_rcvbyteafterwin += todrop;
1304 		}
1305 		tp->snd_wl1 = th->th_seq - 1;
1306 		tp->rcv_up = th->th_seq;
1307 		goto step6;
1308 	}
1309 
1310 	/*
1311 	 * States other than LISTEN or SYN_SENT.
1312 	 * First check timestamp, if present.
1313 	 * Then check that at least some bytes of segment are within
1314 	 * receive window.  If segment begins before rcv_nxt,
1315 	 * drop leading data (and SYN); if nothing left, just ack.
1316 	 *
1317 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1318 	 * and it's less than ts_recent, drop it.
1319 	 */
1320 	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1321 	    TSTMP_LT(ts_val, tp->ts_recent)) {
1322 
1323 		/* Check to see if ts_recent is over 24 days old.  */
1324 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1325 			/*
1326 			 * Invalidate ts_recent.  If this segment updates
1327 			 * ts_recent, the age will be reset later and ts_recent
1328 			 * will get a valid value.  If it does not, setting
1329 			 * ts_recent to zero will at least satisfy the
1330 			 * requirement that zero be placed in the timestamp
1331 			 * echo reply when ts_recent isn't valid.  The
1332 			 * age isn't reset until we get a valid ts_recent
1333 			 * because we don't want out-of-order segments to be
1334 			 * dropped when ts_recent is old.
1335 			 */
1336 			tp->ts_recent = 0;
1337 		} else {
1338 			tcpstat.tcps_rcvduppack++;
1339 			tcpstat.tcps_rcvdupbyte += tlen;
1340 			tcpstat.tcps_pawsdrop++;
1341 			goto dropafterack;
1342 		}
1343 	}
1344 
1345 	todrop = tp->rcv_nxt - th->th_seq;
1346 	if (todrop > 0) {
1347 		if (tiflags & TH_SYN) {
1348 			tiflags &= ~TH_SYN;
1349 			th->th_seq++;
1350 			if (th->th_urp > 1)
1351 				th->th_urp--;
1352 			else
1353 				tiflags &= ~TH_URG;
1354 			todrop--;
1355 		}
1356 		if (todrop >= tlen ||
1357 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1358 			/*
1359 			 * Any valid FIN must be to the left of the
1360 			 * window.  At this point, FIN must be a
1361 			 * duplicate or out-of-sequence, so drop it.
1362 			 */
1363 			tiflags &= ~TH_FIN;
1364 			/*
1365 			 * Send ACK to resynchronize, and drop any data,
1366 			 * but keep on processing for RST or ACK.
1367 			 */
1368 			tp->t_flags |= TF_ACKNOW;
1369 			tcpstat.tcps_rcvdupbyte += todrop = tlen;
1370 			tcpstat.tcps_rcvduppack++;
1371 		} else {
1372 			tcpstat.tcps_rcvpartduppack++;
1373 			tcpstat.tcps_rcvpartdupbyte += todrop;
1374 		}
1375 		hdroptlen += todrop;	/* drop from head afterwards */
1376 		th->th_seq += todrop;
1377 		tlen -= todrop;
1378 		if (th->th_urp > todrop)
1379 			th->th_urp -= todrop;
1380 		else {
1381 			tiflags &= ~TH_URG;
1382 			th->th_urp = 0;
1383 		}
1384 	}
1385 
1386 	/*
1387 	 * If new data are received on a connection after the
1388 	 * user processes are gone, then RST the other end.
1389 	 */
1390 	if ((so->so_state & SS_NOFDREF) &&
1391 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1392 		tp = tcp_close(tp);
1393 		tcpstat.tcps_rcvafterclose++;
1394 		goto dropwithreset;
1395 	}
1396 
1397 	/*
1398 	 * If segment ends after window, drop trailing data
1399 	 * (and PUSH and FIN); if nothing left, just ACK.
1400 	 */
1401 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1402 	if (todrop > 0) {
1403 		tcpstat.tcps_rcvpackafterwin++;
1404 		if (todrop >= tlen) {
1405 			tcpstat.tcps_rcvbyteafterwin += tlen;
1406 			/*
1407 			 * If a new connection request is received
1408 			 * while in TIME_WAIT, drop the old connection
1409 			 * and start over if the sequence numbers
1410 			 * are above the previous ones.
1411 			 */
1412 			if (tiflags & TH_SYN &&
1413 			    tp->t_state == TCPS_TIME_WAIT &&
1414 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1415 				iss = tp->snd_nxt + TCP_ISSINCR;
1416 				tp = tcp_close(tp);
1417 				goto findpcb;
1418 			}
1419 			/*
1420 			 * If window is closed can only take segments at
1421 			 * window edge, and have to drop data and PUSH from
1422 			 * incoming segments.  Continue processing, but
1423 			 * remember to ack.  Otherwise, drop segment
1424 			 * and ack.
1425 			 */
1426 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1427 				tp->t_flags |= TF_ACKNOW;
1428 				tcpstat.tcps_rcvwinprobe++;
1429 			} else
1430 				goto dropafterack;
1431 		} else
1432 			tcpstat.tcps_rcvbyteafterwin += todrop;
1433 		m_adj(m, -todrop);
1434 		tlen -= todrop;
1435 		tiflags &= ~(TH_PUSH|TH_FIN);
1436 	}
1437 
1438 	/*
1439 	 * If last ACK falls within this segment's sequence numbers,
1440 	 * record its timestamp.
1441 	 * Fix from Braden, see Stevens p. 870
1442 	 */
1443 	if (ts_present && TSTMP_GEQ(ts_val, tp->ts_recent) &&
1444 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1445 		tp->ts_recent_age = tcp_now;
1446 		tp->ts_recent = ts_val;
1447 	}
1448 
1449 	/*
1450 	 * If the RST bit is set examine the state:
1451 	 *    SYN_RECEIVED STATE:
1452 	 *	If passive open, return to LISTEN state.
1453 	 *	If active open, inform user that connection was refused.
1454 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1455 	 *	Inform user that connection was reset, and close tcb.
1456 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
1457 	 *	Close the tcb.
1458 	 */
1459 	if (tiflags & TH_RST) {
1460 		if (th->th_seq != tp->last_ack_sent)
1461 			goto drop;
1462 
1463 		switch (tp->t_state) {
1464 		case TCPS_SYN_RECEIVED:
1465 			so->so_error = ECONNREFUSED;
1466 			goto close;
1467 
1468 		case TCPS_ESTABLISHED:
1469 		case TCPS_FIN_WAIT_1:
1470 		case TCPS_FIN_WAIT_2:
1471 		case TCPS_CLOSE_WAIT:
1472 			so->so_error = ECONNRESET;
1473 		close:
1474 			tp->t_state = TCPS_CLOSED;
1475 			tcpstat.tcps_drops++;
1476 			tp = tcp_close(tp);
1477 			goto drop;
1478 		case TCPS_CLOSING:
1479 		case TCPS_LAST_ACK:
1480 		case TCPS_TIME_WAIT:
1481 			tp = tcp_close(tp);
1482 			goto drop;
1483 		}
1484 	}
1485 
1486 	/*
1487 	 * If a SYN is in the window, then this is an
1488 	 * error and we send an RST and drop the connection.
1489 	 */
1490 	if (tiflags & TH_SYN) {
1491 		tp = tcp_drop(tp, ECONNRESET);
1492 		goto dropwithreset;
1493 	}
1494 
1495 	/*
1496 	 * If the ACK bit is off we drop the segment and return.
1497 	 */
1498 	if ((tiflags & TH_ACK) == 0) {
1499 		if (tp->t_flags & TF_ACKNOW)
1500 			goto dropafterack;
1501 		else
1502 			goto drop;
1503 	}
1504 
1505 	/*
1506 	 * Ack processing.
1507 	 */
1508 	switch (tp->t_state) {
1509 
1510 	/*
1511 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1512 	 * ESTABLISHED state and continue processing.
1513 	 * The ACK was checked above.
1514 	 */
1515 	case TCPS_SYN_RECEIVED:
1516 		tcpstat.tcps_connects++;
1517 		soisconnected(so);
1518 		tp->t_state = TCPS_ESTABLISHED;
1519 		/* Do window scaling? */
1520 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1521 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1522 			tp->snd_scale = tp->requested_s_scale;
1523 			tp->rcv_scale = tp->request_r_scale;
1524 		}
1525 		(void) tcp_reass(tp, (struct tcphdr *)0, (struct mbuf *)0,
1526 				 &tlen);
1527 		tp->snd_wl1 = th->th_seq - 1;
1528 		/* fall into ... */
1529 
1530 	/*
1531 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1532 	 * ACKs.  If the ack is in the range
1533 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1534 	 * then advance tp->snd_una to th->th_ack and drop
1535 	 * data from the retransmission queue.  If this ACK reflects
1536 	 * more up to date window information we update our window information.
1537 	 */
1538 	case TCPS_ESTABLISHED:
1539 	case TCPS_FIN_WAIT_1:
1540 	case TCPS_FIN_WAIT_2:
1541 	case TCPS_CLOSE_WAIT:
1542 	case TCPS_CLOSING:
1543 	case TCPS_LAST_ACK:
1544 	case TCPS_TIME_WAIT:
1545 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1546 			/*
1547 			 * Duplicate/old ACK processing.
1548 			 * Increments t_dupacks:
1549 			 *	Pure duplicate (same seq/ack/window, no data)
1550 			 * Doesn't affect t_dupacks:
1551 			 *	Data packets.
1552 			 *	Normal window updates (window opens)
1553 			 * Resets t_dupacks:
1554 			 *	New data ACKed.
1555 			 *	Window shrinks
1556 			 *	Old ACK
1557 			 */
1558 			if (tlen)
1559 				break;
1560 			/*
1561 			 * If we get an old ACK, there is probably packet
1562 			 * reordering going on.  Be conservative and reset
1563 			 * t_dupacks so that we are less agressive in
1564 			 * doing a fast retransmit.
1565 			 */
1566 			if (th->th_ack != tp->snd_una) {
1567 				tp->t_dupacks = 0;
1568 				break;
1569 			}
1570 			if (tiwin == tp->snd_wnd) {
1571 				tcpstat.tcps_rcvdupack++;
1572 				/*
1573 				 * If we have outstanding data (other than
1574 				 * a window probe), this is a completely
1575 				 * duplicate ack (ie, window info didn't
1576 				 * change), the ack is the biggest we've
1577 				 * seen and we've seen exactly our rexmt
1578 				 * threshhold of them, assume a packet
1579 				 * has been dropped and retransmit it.
1580 				 * Kludge snd_nxt & the congestion
1581 				 * window so we send only this one
1582 				 * packet.
1583 				 *
1584 				 * We know we're losing at the current
1585 				 * window size so do congestion avoidance
1586 				 * (set ssthresh to half the current window
1587 				 * and pull our congestion window back to
1588 				 * the new ssthresh).
1589 				 *
1590 				 * Dup acks mean that packets have left the
1591 				 * network (they're now cached at the receiver)
1592 				 * so bump cwnd by the amount in the receiver
1593 				 * to keep a constant cwnd packets in the
1594 				 * network.
1595 				 */
1596 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0)
1597 					tp->t_dupacks = 0;
1598 #if defined(TCP_SACK) && defined(TCP_FACK)
1599 				/*
1600 				 * In FACK, can enter fast rec. if the receiver
1601 				 * reports a reass. queue longer than 3 segs.
1602 				 */
1603 				else if (++tp->t_dupacks == tcprexmtthresh ||
1604 				    ((SEQ_GT(tp->snd_fack, tcprexmtthresh *
1605 				    tp->t_maxseg + tp->snd_una)) &&
1606 				    SEQ_GT(tp->snd_una, tp->snd_last))) {
1607 #else
1608 				else if (++tp->t_dupacks == tcprexmtthresh) {
1609 #endif /* TCP_FACK */
1610 					tcp_seq onxt = tp->snd_nxt;
1611 					u_long win =
1612 					    ulmin(tp->snd_wnd, tp->snd_cwnd) /
1613 						2 / tp->t_maxseg;
1614 
1615 #if defined(TCP_SACK)
1616 					if (SEQ_LT(th->th_ack, tp->snd_last)){
1617 					    	/*
1618 						 * False fast retx after
1619 						 * timeout.  Do not cut window.
1620 						 */
1621 						tp->t_dupacks = 0;
1622 						goto drop;
1623 					}
1624 #endif
1625 					if (win < 2)
1626 						win = 2;
1627 					tp->snd_ssthresh = win * tp->t_maxseg;
1628 #if defined(TCP_SACK)
1629 					tp->snd_last = tp->snd_max;
1630 #endif
1631 #ifdef TCP_SACK
1632                     			if (!tp->sack_disable) {
1633 						TCP_TIMER_DISARM(tp, TCPT_REXMT);
1634 						tp->t_rtt = 0;
1635 						tcpstat.tcps_sndrexmitfast++;
1636 #if defined(TCP_SACK) && defined(TCP_FACK)
1637 						tp->t_dupacks = tcprexmtthresh;
1638 						(void) tcp_output(tp);
1639 						/*
1640 						 * During FR, snd_cwnd is held
1641 						 * constant for FACK.
1642 						 */
1643 						tp->snd_cwnd = tp->snd_ssthresh;
1644 #else
1645 						/*
1646 						 * tcp_output() will send
1647 						 * oldest SACK-eligible rtx.
1648 						 */
1649 						(void) tcp_output(tp);
1650 						tp->snd_cwnd = tp->snd_ssthresh+
1651 					           tp->t_maxseg * tp->t_dupacks;
1652 #endif /* TCP_FACK */
1653 						goto drop;
1654 					}
1655 #endif /* TCP_SACK */
1656 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
1657 					tp->t_rtt = 0;
1658 					tp->snd_nxt = th->th_ack;
1659 					tp->snd_cwnd = tp->t_maxseg;
1660 					tcpstat.tcps_sndrexmitfast++;
1661 					(void) tcp_output(tp);
1662 
1663 					tp->snd_cwnd = tp->snd_ssthresh +
1664 					    tp->t_maxseg * tp->t_dupacks;
1665 					if (SEQ_GT(onxt, tp->snd_nxt))
1666 						tp->snd_nxt = onxt;
1667 					goto drop;
1668 				} else if (tp->t_dupacks > tcprexmtthresh) {
1669 #if defined(TCP_SACK) && defined(TCP_FACK)
1670 					/*
1671 					 * while (awnd < cwnd)
1672 					 *         sendsomething();
1673 					 */
1674 					if (!tp->sack_disable) {
1675 						if (tp->snd_awnd < tp->snd_cwnd)
1676 							tcp_output(tp);
1677 						goto drop;
1678 					}
1679 #endif /* TCP_FACK */
1680 					tp->snd_cwnd += tp->t_maxseg;
1681 					(void) tcp_output(tp);
1682 					goto drop;
1683 				}
1684 			} else if (tiwin < tp->snd_wnd) {
1685 				/*
1686 				 * The window was retracted!  Previous dup
1687 				 * ACKs may have been due to packets arriving
1688 				 * after the shrunken window, not a missing
1689 				 * packet, so play it safe and reset t_dupacks
1690 				 */
1691 				tp->t_dupacks = 0;
1692 			}
1693 			break;
1694 		}
1695 		/*
1696 		 * If the congestion window was inflated to account
1697 		 * for the other side's cached packets, retract it.
1698 		 */
1699 #if defined(TCP_SACK)
1700 		if (!tp->sack_disable) {
1701 			if (tp->t_dupacks >= tcprexmtthresh) {
1702 				/* Check for a partial ACK */
1703 				if (tcp_sack_partialack(tp, th)) {
1704 #if defined(TCP_SACK) && defined(TCP_FACK)
1705 					/* Force call to tcp_output */
1706 					if (tp->snd_awnd < tp->snd_cwnd)
1707 						needoutput = 1;
1708 #else
1709 					tp->snd_cwnd += tp->t_maxseg;
1710 					needoutput = 1;
1711 #endif /* TCP_FACK */
1712 				} else {
1713 					/* Out of fast recovery */
1714 					tp->snd_cwnd = tp->snd_ssthresh;
1715 					if (tcp_seq_subtract(tp->snd_max,
1716 					    th->th_ack) < tp->snd_ssthresh)
1717 						tp->snd_cwnd =
1718 						   tcp_seq_subtract(tp->snd_max,
1719 					           th->th_ack);
1720 					tp->t_dupacks = 0;
1721 #if defined(TCP_SACK) && defined(TCP_FACK)
1722 					if (SEQ_GT(th->th_ack, tp->snd_fack))
1723 						tp->snd_fack = th->th_ack;
1724 #endif /* TCP_FACK */
1725 				}
1726 			}
1727 		} else {
1728 			if (tp->t_dupacks >= tcprexmtthresh &&
1729 			    !tcp_newreno(tp, th)) {
1730 				/* Out of fast recovery */
1731 				tp->snd_cwnd = tp->snd_ssthresh;
1732 				if (tcp_seq_subtract(tp->snd_max, th->th_ack) <
1733 			  	    tp->snd_ssthresh)
1734 					tp->snd_cwnd =
1735 					    tcp_seq_subtract(tp->snd_max,
1736 					    th->th_ack);
1737 				tp->t_dupacks = 0;
1738 			}
1739 		}
1740 		if (tp->t_dupacks < tcprexmtthresh)
1741 			tp->t_dupacks = 0;
1742 #else /* else no TCP_SACK */
1743 		if (tp->t_dupacks >= tcprexmtthresh &&
1744 		    tp->snd_cwnd > tp->snd_ssthresh)
1745 			tp->snd_cwnd = tp->snd_ssthresh;
1746 		tp->t_dupacks = 0;
1747 #endif
1748 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1749 			tcpstat.tcps_rcvacktoomuch++;
1750 			goto dropafterack;
1751 		}
1752 		acked = th->th_ack - tp->snd_una;
1753 		tcpstat.tcps_rcvackpack++;
1754 		tcpstat.tcps_rcvackbyte += acked;
1755 
1756 		/*
1757 		 * If we have a timestamp reply, update smoothed
1758 		 * round trip time.  If no timestamp is present but
1759 		 * transmit timer is running and timed sequence
1760 		 * number was acked, update smoothed round trip time.
1761 		 * Since we now have an rtt measurement, cancel the
1762 		 * timer backoff (cf., Phil Karn's retransmit alg.).
1763 		 * Recompute the initial retransmit timer.
1764 		 */
1765 		if (ts_present)
1766 			tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
1767 		else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
1768 			tcp_xmit_timer(tp,tp->t_rtt);
1769 
1770 		/*
1771 		 * If all outstanding data is acked, stop retransmit
1772 		 * timer and remember to restart (more output or persist).
1773 		 * If there is more data to be acked, restart retransmit
1774 		 * timer, using current (possibly backed-off) value.
1775 		 */
1776 		if (th->th_ack == tp->snd_max) {
1777 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
1778 			needoutput = 1;
1779 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
1780 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1781 		/*
1782 		 * When new data is acked, open the congestion window.
1783 		 * If the window gives us less than ssthresh packets
1784 		 * in flight, open exponentially (maxseg per packet).
1785 		 * Otherwise open linearly: maxseg per window
1786 		 * (maxseg^2 / cwnd per packet).
1787 		 */
1788 		{
1789 		u_int cw = tp->snd_cwnd;
1790 		u_int incr = tp->t_maxseg;
1791 
1792 		if (cw > tp->snd_ssthresh)
1793 			incr = incr * incr / cw;
1794 #if defined (TCP_SACK)
1795 		if (tp->t_dupacks < tcprexmtthresh)
1796 #endif
1797 		tp->snd_cwnd = ulmin(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1798 		}
1799 		ND6_HINT(tp);
1800 		if (acked > so->so_snd.sb_cc) {
1801 			tp->snd_wnd -= so->so_snd.sb_cc;
1802 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1803 			ourfinisacked = 1;
1804 		} else {
1805 			sbdrop(&so->so_snd, acked);
1806 			tp->snd_wnd -= acked;
1807 			ourfinisacked = 0;
1808 		}
1809 		if (sb_notify(&so->so_snd))
1810 			sowwakeup(so);
1811 		tp->snd_una = th->th_ack;
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 		if (th->th_seq == tp->rcv_nxt && tp->segq.lh_first == NULL &&
1980 		    tp->t_state == TCPS_ESTABLISHED) {
1981 			if (th->th_flags & TH_PUSH)
1982 				tp->t_flags |= TF_ACKNOW;
1983 			else
1984 				tp->t_flags |= TF_DELACK;
1985 			tp->rcv_nxt += tlen;
1986 			tiflags = th->th_flags & TH_FIN;
1987 			tcpstat.tcps_rcvpack++;
1988 			tcpstat.tcps_rcvbyte += tlen;
1989 			ND6_HINT(tp);
1990 			m_adj(m, hdroptlen);
1991 			sbappend(&so->so_rcv, m);
1992 			sorwakeup(so);
1993 		} else {
1994 			m_adj(m, hdroptlen);
1995 			tiflags = tcp_reass(tp, th, m, &tlen);
1996 			tp->t_flags |= TF_ACKNOW;
1997 		}
1998 #ifdef TCP_SACK
1999 		if (!tp->sack_disable)
2000 			tcp_update_sack_list(tp);
2001 #endif
2002 
2003 		/*
2004 		 * variable len never referenced again in modern BSD,
2005 		 * so why bother computing it ??
2006 		 */
2007 #if 0
2008 		/*
2009 		 * Note the amount of data that peer has sent into
2010 		 * our window, in order to estimate the sender's
2011 		 * buffer size.
2012 		 */
2013 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2014 #endif /* 0 */
2015 	} else {
2016 		m_freem(m);
2017 		tiflags &= ~TH_FIN;
2018 	}
2019 
2020 	/*
2021 	 * If FIN is received ACK the FIN and let the user know
2022 	 * that the connection is closing.  Ignore a FIN received before
2023 	 * the connection is fully established.
2024 	 */
2025 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2026 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2027 			socantrcvmore(so);
2028 			tp->t_flags |= TF_ACKNOW;
2029 			tp->rcv_nxt++;
2030 		}
2031 		switch (tp->t_state) {
2032 
2033 		/*
2034 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2035 		 */
2036 		case TCPS_ESTABLISHED:
2037 			tp->t_state = TCPS_CLOSE_WAIT;
2038 			break;
2039 
2040 		/*
2041 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2042 		 * enter the CLOSING state.
2043 		 */
2044 		case TCPS_FIN_WAIT_1:
2045 			tp->t_state = TCPS_CLOSING;
2046 			break;
2047 
2048 		/*
2049 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2050 		 * starting the time-wait timer, turning off the other
2051 		 * standard timers.
2052 		 */
2053 		case TCPS_FIN_WAIT_2:
2054 			tp->t_state = TCPS_TIME_WAIT;
2055 			tcp_canceltimers(tp);
2056 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2057 			soisdisconnected(so);
2058 			break;
2059 
2060 		/*
2061 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2062 		 */
2063 		case TCPS_TIME_WAIT:
2064 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2065 			break;
2066 		}
2067 	}
2068 	if (so->so_options & SO_DEBUG) {
2069 		switch (tp->pf == PF_INET6) {
2070 #ifdef INET6
2071 		case PF_INET6:
2072 			tcp_trace(TA_INPUT, ostate, tp, (caddr_t) &tcp_saveti6,
2073 			    0, tlen);
2074 			break;
2075 #endif /* INET6 */
2076 		case PF_INET:
2077 			tcp_trace(TA_INPUT, ostate, tp, (caddr_t) &tcp_saveti,
2078 			    0, tlen);
2079 			break;
2080 		}
2081 	}
2082 
2083 	/*
2084 	 * Return any desired output.
2085 	 */
2086 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2087 		(void) tcp_output(tp);
2088 	}
2089 	return;
2090 
2091 dropafterack:
2092 	/*
2093 	 * Generate an ACK dropping incoming segment if it occupies
2094 	 * sequence space, where the ACK reflects our state.
2095 	 */
2096 	if (tiflags & TH_RST)
2097 		goto drop;
2098 	m_freem(m);
2099 	tp->t_flags |= TF_ACKNOW;
2100 	(void) tcp_output(tp);
2101 	return;
2102 
2103 dropwithreset_ratelim:
2104 	/*
2105 	 * We may want to rate-limit RSTs in certain situations,
2106 	 * particularly if we are sending an RST in response to
2107 	 * an attempt to connect to or otherwise communicate with
2108 	 * a port for which we have no socket.
2109 	 */
2110 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2111 	    tcp_rst_ppslim) == 0) {
2112 		/* XXX stat */
2113 		goto drop;
2114 	}
2115 	/* ...fall into dropwithreset... */
2116 
2117 dropwithreset:
2118 	/*
2119 	 * Generate a RST, dropping incoming segment.
2120 	 * Make ACK acceptable to originator of segment.
2121 	 * Don't bother to respond if destination was broadcast/multicast.
2122 	 */
2123 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2124 		goto drop;
2125 	switch (af) {
2126 #ifdef INET6
2127 	case AF_INET6:
2128 		/* For following calls to tcp_respond */
2129 		if (IN6_IS_ADDR_MULTICAST(&ipv6->ip6_dst))
2130 			goto drop;
2131 		break;
2132 #endif /* INET6 */
2133 	case AF_INET:
2134 		if (IN_MULTICAST(ip->ip_dst.s_addr))
2135 			goto drop;
2136 	}
2137 	if (tiflags & TH_ACK) {
2138 		tcp_respond(tp, mtod(m, caddr_t), m, (tcp_seq)0, th->th_ack,
2139 		    TH_RST);
2140 	} else {
2141 		if (tiflags & TH_SYN)
2142 			tlen++;
2143 		tcp_respond(tp, mtod(m, caddr_t), m, th->th_seq + tlen,
2144 		    (tcp_seq)0, TH_RST|TH_ACK);
2145 	}
2146 	/* destroy temporarily created socket */
2147 	if (dropsocket)
2148 		(void) soabort(so);
2149 	return;
2150 
2151 drop:
2152 	/*
2153 	 * Drop space held by incoming segment and return.
2154 	 */
2155 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
2156 		switch (tp->pf) {
2157 #ifdef INET6
2158 		case PF_INET6:
2159 			tcp_trace(TA_DROP, ostate, tp, (caddr_t) &tcp_saveti6,
2160 			    0, tlen);
2161 			break;
2162 #endif /* INET6 */
2163 		case PF_INET:
2164 			tcp_trace(TA_DROP, ostate, tp, (caddr_t) &tcp_saveti,
2165 			    0, tlen);
2166 			break;
2167 		}
2168 	}
2169 
2170 	m_freem(m);
2171 	/* destroy temporarily created socket */
2172 	if (dropsocket)
2173 		(void) soabort(so);
2174 	return;
2175 #ifndef TUBA_INCLUDE
2176 }
2177 
2178 void
2179 tcp_dooptions(tp, cp, cnt, th, ts_present, ts_val, ts_ecr)
2180 	struct tcpcb *tp;
2181 	u_char *cp;
2182 	int cnt;
2183 	struct tcphdr *th;
2184 	int *ts_present;
2185 	u_int32_t *ts_val, *ts_ecr;
2186 {
2187 	u_int16_t mss = 0;
2188 	int opt, optlen;
2189 
2190 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2191 		opt = cp[0];
2192 		if (opt == TCPOPT_EOL)
2193 			break;
2194 		if (opt == TCPOPT_NOP)
2195 			optlen = 1;
2196 		else {
2197 			if (cnt < 2)
2198 				break;
2199 			optlen = cp[1];
2200 			if (optlen < 2 || optlen > cnt)
2201 				break;
2202 		}
2203 		switch (opt) {
2204 
2205 		default:
2206 			continue;
2207 
2208 		case TCPOPT_MAXSEG:
2209 			if (optlen != TCPOLEN_MAXSEG)
2210 				continue;
2211 			if (!(th->th_flags & TH_SYN))
2212 				continue;
2213 			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
2214 			NTOHS(mss);
2215 			break;
2216 
2217 		case TCPOPT_WINDOW:
2218 			if (optlen != TCPOLEN_WINDOW)
2219 				continue;
2220 			if (!(th->th_flags & TH_SYN))
2221 				continue;
2222 			tp->t_flags |= TF_RCVD_SCALE;
2223 			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2224 			break;
2225 
2226 		case TCPOPT_TIMESTAMP:
2227 			if (optlen != TCPOLEN_TIMESTAMP)
2228 				continue;
2229 			*ts_present = 1;
2230 			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
2231 			NTOHL(*ts_val);
2232 			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
2233 			NTOHL(*ts_ecr);
2234 
2235 			/*
2236 			 * A timestamp received in a SYN makes
2237 			 * it ok to send timestamp requests and replies.
2238 			 */
2239 			if (th->th_flags & TH_SYN) {
2240 				tp->t_flags |= TF_RCVD_TSTMP;
2241 				tp->ts_recent = *ts_val;
2242 				tp->ts_recent_age = tcp_now;
2243 			}
2244 			break;
2245 
2246 #ifdef TCP_SACK
2247 		case TCPOPT_SACK_PERMITTED:
2248 			if (tp->sack_disable || optlen!=TCPOLEN_SACK_PERMITTED)
2249 				continue;
2250 			if (th->th_flags & TH_SYN)
2251 				/* MUST only be set on SYN */
2252 				tp->t_flags |= TF_SACK_PERMIT;
2253 			break;
2254 		case TCPOPT_SACK:
2255 			if (tcp_sack_option(tp, th, cp, optlen))
2256 				continue;
2257 			break;
2258 #endif
2259 		}
2260 	}
2261 	/* Update t_maxopd and t_maxseg after all options are processed */
2262 	if (th->th_flags & TH_SYN) {
2263 		(void) tcp_mss(tp, mss);	/* sets t_maxseg */
2264 
2265 		if (mss)
2266 			tcp_mss_update(tp);
2267 	}
2268 }
2269 
2270 #if defined(TCP_SACK)
2271 u_long
2272 tcp_seq_subtract(a, b)
2273 	u_long a, b;
2274 {
2275 	return ((long)(a - b));
2276 }
2277 #endif
2278 
2279 
2280 #ifdef TCP_SACK
2281 /*
2282  * This function is called upon receipt of new valid data (while not in header
2283  * prediction mode), and it updates the ordered list of sacks.
2284  */
2285 void
2286 tcp_update_sack_list(tp)
2287 	struct tcpcb *tp;
2288 {
2289 	/*
2290 	 * First reported block MUST be the most recent one.  Subsequent
2291 	 * blocks SHOULD be in the order in which they arrived at the
2292 	 * receiver.  These two conditions make the implementation fully
2293 	 * compliant with RFC 2018.
2294 	 */
2295 	int i, j = 0, count = 0, lastpos = -1;
2296 	struct sackblk sack, firstsack, temp[MAX_SACK_BLKS];
2297 
2298 	/* First clean up current list of sacks */
2299 	for (i = 0; i < tp->rcv_numsacks; i++) {
2300 		sack = tp->sackblks[i];
2301 		if (sack.start == 0 && sack.end == 0) {
2302 			count++; /* count = number of blocks to be discarded */
2303 			continue;
2304 		}
2305 		if (SEQ_LEQ(sack.end, tp->rcv_nxt)) {
2306 			tp->sackblks[i].start = tp->sackblks[i].end = 0;
2307 			count++;
2308 		} else {
2309 			temp[j].start = tp->sackblks[i].start;
2310 			temp[j++].end = tp->sackblks[i].end;
2311 		}
2312 	}
2313 	tp->rcv_numsacks -= count;
2314 	if (tp->rcv_numsacks == 0) { /* no sack blocks currently (fast path) */
2315 		tcp_clean_sackreport(tp);
2316 		if (SEQ_LT(tp->rcv_nxt, tp->rcv_laststart)) {
2317 			/* ==> need first sack block */
2318 			tp->sackblks[0].start = tp->rcv_laststart;
2319 			tp->sackblks[0].end = tp->rcv_lastend;
2320 			tp->rcv_numsacks = 1;
2321 		}
2322 		return;
2323 	}
2324 	/* Otherwise, sack blocks are already present. */
2325 	for (i = 0; i < tp->rcv_numsacks; i++)
2326 		tp->sackblks[i] = temp[i]; /* first copy back sack list */
2327 	if (SEQ_GEQ(tp->rcv_nxt, tp->rcv_lastend))
2328 		return;     /* sack list remains unchanged */
2329 	/*
2330 	 * From here, segment just received should be (part of) the 1st sack.
2331 	 * Go through list, possibly coalescing sack block entries.
2332 	 */
2333 	firstsack.start = tp->rcv_laststart;
2334 	firstsack.end = tp->rcv_lastend;
2335 	for (i = 0; i < tp->rcv_numsacks; i++) {
2336 		sack = tp->sackblks[i];
2337 		if (SEQ_LT(sack.end, firstsack.start) ||
2338 		    SEQ_GT(sack.start, firstsack.end))
2339 			continue; /* no overlap */
2340 		if (sack.start == firstsack.start && sack.end == firstsack.end){
2341 			/*
2342 			 * identical block; delete it here since we will
2343 			 * move it to the front of the list.
2344 			 */
2345 			tp->sackblks[i].start = tp->sackblks[i].end = 0;
2346 			lastpos = i;    /* last posn with a zero entry */
2347 			continue;
2348 		}
2349 		if (SEQ_LEQ(sack.start, firstsack.start))
2350 			firstsack.start = sack.start; /* merge blocks */
2351 		if (SEQ_GEQ(sack.end, firstsack.end))
2352 			firstsack.end = sack.end;     /* merge blocks */
2353 		tp->sackblks[i].start = tp->sackblks[i].end = 0;
2354 		lastpos = i;    /* last posn with a zero entry */
2355 	}
2356 	if (lastpos != -1) {    /* at least one merge */
2357 		for (i = 0, j = 1; i < tp->rcv_numsacks; i++) {
2358 			sack = tp->sackblks[i];
2359 			if (sack.start == 0 && sack.end == 0)
2360 				continue;
2361 			temp[j++] = sack;
2362 		}
2363 		tp->rcv_numsacks = j; /* including first blk (added later) */
2364 		for (i = 1; i < tp->rcv_numsacks; i++) /* now copy back */
2365 			tp->sackblks[i] = temp[i];
2366 	} else {        /* no merges -- shift sacks by 1 */
2367 		if (tp->rcv_numsacks < MAX_SACK_BLKS)
2368 			tp->rcv_numsacks++;
2369 		for (i = tp->rcv_numsacks-1; i > 0; i--)
2370 			tp->sackblks[i] = tp->sackblks[i-1];
2371 	}
2372 	tp->sackblks[0] = firstsack;
2373 	return;
2374 }
2375 
2376 /*
2377  * Process the TCP SACK option.  Returns 1 if tcp_dooptions() should continue,
2378  * and 0 otherwise, if the option was fine.  tp->snd_holes is an ordered list
2379  * of holes (oldest to newest, in terms of the sequence space).
2380  */
2381 int
2382 tcp_sack_option(struct tcpcb *tp, struct tcphdr *th, u_char *cp, int optlen)
2383 {
2384 	int tmp_olen;
2385 	u_char *tmp_cp;
2386 	struct sackhole *cur, *p, *temp;
2387 
2388 	if (tp->sack_disable)
2389 		return (1);
2390 
2391 	/* Note: TCPOLEN_SACK must be 2*sizeof(tcp_seq) */
2392 	if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2393 		return (1);
2394 	tmp_cp = cp + 2;
2395 	tmp_olen = optlen - 2;
2396 	if (tp->snd_numholes < 0)
2397 		tp->snd_numholes = 0;
2398 	if (tp->t_maxseg == 0)
2399 		panic("tcp_sack_option"); /* Should never happen */
2400 	while (tmp_olen > 0) {
2401 		struct sackblk sack;
2402 
2403 		bcopy(tmp_cp, (char *) &(sack.start), sizeof(tcp_seq));
2404 		NTOHL(sack.start);
2405 		bcopy(tmp_cp + sizeof(tcp_seq),
2406 		    (char *) &(sack.end), sizeof(tcp_seq));
2407 		NTOHL(sack.end);
2408 		tmp_olen -= TCPOLEN_SACK;
2409 		tmp_cp += TCPOLEN_SACK;
2410 		if (SEQ_LEQ(sack.end, sack.start))
2411 			continue; /* bad SACK fields */
2412 		if (SEQ_LEQ(sack.end, tp->snd_una))
2413 			continue; /* old block */
2414 #if defined(TCP_SACK) && defined(TCP_FACK)
2415 		/* Updates snd_fack.  */
2416 		if (SEQ_GT(sack.end, tp->snd_fack))
2417 			tp->snd_fack = sack.end;
2418 #endif /* TCP_FACK */
2419 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
2420 			if (SEQ_LT(sack.start, th->th_ack))
2421 				continue;
2422 		}
2423 		if (SEQ_GT(sack.end, tp->snd_max))
2424 			continue;
2425 		if (tp->snd_holes == NULL) { /* first hole */
2426 			tp->snd_holes = (struct sackhole *)
2427 			    pool_get(&sackhl_pool, PR_NOWAIT);
2428 			if (tp->snd_holes == NULL) {
2429 				/* ENOBUFS, so ignore SACKed block for now*/
2430 				continue;
2431 			}
2432 			cur = tp->snd_holes;
2433 			cur->start = th->th_ack;
2434 			cur->end = sack.start;
2435 			cur->rxmit = cur->start;
2436 			cur->next = NULL;
2437 			tp->snd_numholes = 1;
2438 			tp->rcv_lastsack = sack.end;
2439 			/*
2440 			 * dups is at least one.  If more data has been
2441 			 * SACKed, it can be greater than one.
2442 			 */
2443 			cur->dups = min(tcprexmtthresh,
2444 			    ((sack.end - cur->end)/tp->t_maxseg));
2445 			if (cur->dups < 1)
2446 				cur->dups = 1;
2447 			continue; /* with next sack block */
2448 		}
2449 		/* Go thru list of holes:  p = previous,  cur = current */
2450 		p = cur = tp->snd_holes;
2451 		while (cur) {
2452 			if (SEQ_LEQ(sack.end, cur->start))
2453 				/* SACKs data before the current hole */
2454 				break; /* no use going through more holes */
2455 			if (SEQ_GEQ(sack.start, cur->end)) {
2456 				/* SACKs data beyond the current hole */
2457 				cur->dups++;
2458 				if (((sack.end - cur->end)/tp->t_maxseg) >=
2459 				    tcprexmtthresh)
2460 					cur->dups = tcprexmtthresh;
2461 				p = cur;
2462 				cur = cur->next;
2463 				continue;
2464 			}
2465 			if (SEQ_LEQ(sack.start, cur->start)) {
2466 				/* Data acks at least the beginning of hole */
2467 #if defined(TCP_SACK) && defined(TCP_FACK)
2468 				if (SEQ_GT(sack.end, cur->rxmit))
2469 					tp->retran_data -=
2470 				    	    tcp_seq_subtract(cur->rxmit,
2471 					    cur->start);
2472 				else
2473 					tp->retran_data -=
2474 					    tcp_seq_subtract(sack.end,
2475 					    cur->start);
2476 #endif /* TCP_FACK */
2477 				if (SEQ_GEQ(sack.end, cur->end)) {
2478 					/* Acks entire hole, so delete hole */
2479 					if (p != cur) {
2480 						p->next = cur->next;
2481 						pool_put(&sackhl_pool, cur);
2482 						cur = p->next;
2483 					} else {
2484 						cur = cur->next;
2485 						pool_put(&sackhl_pool, p);
2486 						p = cur;
2487 						tp->snd_holes = p;
2488 					}
2489 					tp->snd_numholes--;
2490 					continue;
2491 				}
2492 				/* otherwise, move start of hole forward */
2493 				cur->start = sack.end;
2494 				cur->rxmit = max (cur->rxmit, cur->start);
2495 				p = cur;
2496 				cur = cur->next;
2497 				continue;
2498 			}
2499 			/* move end of hole backward */
2500 			if (SEQ_GEQ(sack.end, cur->end)) {
2501 #if defined(TCP_SACK) && defined(TCP_FACK)
2502 				if (SEQ_GT(cur->rxmit, sack.start))
2503 					tp->retran_data -=
2504 					    tcp_seq_subtract(cur->rxmit,
2505 					    sack.start);
2506 #endif /* TCP_FACK */
2507 				cur->end = sack.start;
2508 				cur->rxmit = min(cur->rxmit, cur->end);
2509 				cur->dups++;
2510 				if (((sack.end - cur->end)/tp->t_maxseg) >=
2511 				    tcprexmtthresh)
2512 					cur->dups = tcprexmtthresh;
2513 				p = cur;
2514 				cur = cur->next;
2515 				continue;
2516 			}
2517 			if (SEQ_LT(cur->start, sack.start) &&
2518 			    SEQ_GT(cur->end, sack.end)) {
2519 				/*
2520 				 * ACKs some data in middle of a hole; need to
2521 				 * split current hole
2522 				 */
2523 				temp = (struct sackhole *)
2524 				    pool_get(&sackhl_pool, PR_NOWAIT);
2525 				if (temp == NULL)
2526 					continue; /* ENOBUFS */
2527 #if defined(TCP_SACK) && defined(TCP_FACK)
2528 				if (SEQ_GT(cur->rxmit, sack.end))
2529 					tp->retran_data -=
2530 					    tcp_seq_subtract(sack.end,
2531 					    sack.start);
2532 				else if (SEQ_GT(cur->rxmit, sack.start))
2533 					tp->retran_data -=
2534 					    tcp_seq_subtract(cur->rxmit,
2535 					    sack.start);
2536 #endif /* TCP_FACK */
2537 				temp->next = cur->next;
2538 				temp->start = sack.end;
2539 				temp->end = cur->end;
2540 				temp->dups = cur->dups;
2541 				temp->rxmit = max(cur->rxmit, temp->start);
2542 				cur->end = sack.start;
2543 				cur->rxmit = min(cur->rxmit, cur->end);
2544 				cur->dups++;
2545 				if (((sack.end - cur->end)/tp->t_maxseg) >=
2546 					tcprexmtthresh)
2547 					cur->dups = tcprexmtthresh;
2548 				cur->next = temp;
2549 				p = temp;
2550 				cur = p->next;
2551 				tp->snd_numholes++;
2552 			}
2553 		}
2554 		/* At this point, p points to the last hole on the list */
2555 		if (SEQ_LT(tp->rcv_lastsack, sack.start)) {
2556 			/*
2557 			 * Need to append new hole at end.
2558 			 * Last hole is p (and it's not NULL).
2559 			 */
2560 			temp = (struct sackhole *)
2561 			    pool_get(&sackhl_pool, PR_NOWAIT);
2562 			if (temp == NULL)
2563 				continue; /* ENOBUFS */
2564 			temp->start = tp->rcv_lastsack;
2565 			temp->end = sack.start;
2566 			temp->dups = min(tcprexmtthresh,
2567 			    ((sack.end - sack.start)/tp->t_maxseg));
2568 			if (temp->dups < 1)
2569 				temp->dups = 1;
2570 			temp->rxmit = temp->start;
2571 			temp->next = 0;
2572 			p->next = temp;
2573 			tp->rcv_lastsack = sack.end;
2574 			tp->snd_numholes++;
2575 		}
2576 	}
2577 #if defined(TCP_SACK) && defined(TCP_FACK)
2578 	/*
2579 	 * Update retran_data and snd_awnd.  Go through the list of
2580 	 * holes.   Increment retran_data by (hole->rxmit - hole->start).
2581 	 */
2582 	tp->retran_data = 0;
2583 	cur = tp->snd_holes;
2584 	while (cur) {
2585 		tp->retran_data += cur->rxmit - cur->start;
2586 		cur = cur->next;
2587 	}
2588 	tp->snd_awnd = tcp_seq_subtract(tp->snd_nxt, tp->snd_fack) +
2589 	    tp->retran_data;
2590 #endif /* TCP_FACK */
2591 
2592 	return (0);
2593 }
2594 
2595 /*
2596  * Delete stale (i.e, cumulatively ack'd) holes.  Hole is deleted only if
2597  * it is completely acked; otherwise, tcp_sack_option(), called from
2598  * tcp_dooptions(), will fix up the hole.
2599  */
2600 void
2601 tcp_del_sackholes(tp, th)
2602 	struct tcpcb *tp;
2603 	struct tcphdr *th;
2604 {
2605 	if (!tp->sack_disable && tp->t_state != TCPS_LISTEN) {
2606 		/* max because this could be an older ack just arrived */
2607 		tcp_seq lastack = SEQ_GT(th->th_ack, tp->snd_una) ?
2608 			th->th_ack : tp->snd_una;
2609 		struct sackhole *cur = tp->snd_holes;
2610 		struct sackhole *prev;
2611 		while (cur)
2612 			if (SEQ_LEQ(cur->end, lastack)) {
2613 				prev = cur;
2614 				cur = cur->next;
2615 				pool_put(&sackhl_pool, prev);
2616 				tp->snd_numholes--;
2617 			} else if (SEQ_LT(cur->start, lastack)) {
2618 				cur->start = lastack;
2619 				if (SEQ_LT(cur->rxmit, cur->start))
2620 					cur->rxmit = cur->start;
2621 				break;
2622 			} else
2623 				break;
2624 		tp->snd_holes = cur;
2625 	}
2626 }
2627 
2628 /*
2629  * Delete all receiver-side SACK information.
2630  */
2631 void
2632 tcp_clean_sackreport(tp)
2633 	struct tcpcb *tp;
2634 {
2635 	int i;
2636 
2637 	tp->rcv_numsacks = 0;
2638 	for (i = 0; i < MAX_SACK_BLKS; i++)
2639 		tp->sackblks[i].start = tp->sackblks[i].end=0;
2640 
2641 }
2642 
2643 /*
2644  * Checks for partial ack.  If partial ack arrives, turn off retransmission
2645  * timer, deflate the window, do not clear tp->t_dupacks, and return 1.
2646  * If the ack advances at least to tp->snd_last, return 0.
2647  */
2648 int
2649 tcp_sack_partialack(tp, th)
2650 	struct tcpcb *tp;
2651 	struct tcphdr *th;
2652 {
2653 	if (SEQ_LT(th->th_ack, tp->snd_last)) {
2654 		/* Turn off retx. timer (will start again next segment) */
2655 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
2656 		tp->t_rtt = 0;
2657 #ifndef TCP_FACK
2658 		/*
2659 		 * Partial window deflation.  This statement relies on the
2660 		 * fact that tp->snd_una has not been updated yet.  In FACK
2661 		 * hold snd_cwnd constant during fast recovery.
2662 		 */
2663 		if (tp->snd_cwnd > (th->th_ack - tp->snd_una)) {
2664 			tp->snd_cwnd -= th->th_ack - tp->snd_una;
2665 			tp->snd_cwnd += tp->t_maxseg;
2666 		} else
2667 			tp->snd_cwnd = tp->t_maxseg;
2668 #endif
2669 		return (1);
2670 	}
2671 	return (0);
2672 }
2673 #endif /* TCP_SACK */
2674 
2675 /*
2676  * Pull out of band byte out of a segment so
2677  * it doesn't appear in the user's data queue.
2678  * It is still reflected in the segment length for
2679  * sequencing purposes.
2680  */
2681 void
2682 tcp_pulloutofband(so, urgent, m, off)
2683 	struct socket *so;
2684 	u_int urgent;
2685 	register struct mbuf *m;
2686 	int off;
2687 {
2688         int cnt = off + urgent - 1;
2689 
2690 	while (cnt >= 0) {
2691 		if (m->m_len > cnt) {
2692 			char *cp = mtod(m, caddr_t) + cnt;
2693 			struct tcpcb *tp = sototcpcb(so);
2694 
2695 			tp->t_iobc = *cp;
2696 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2697 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2698 			m->m_len--;
2699 			return;
2700 		}
2701 		cnt -= m->m_len;
2702 		m = m->m_next;
2703 		if (m == 0)
2704 			break;
2705 	}
2706 	panic("tcp_pulloutofband");
2707 }
2708 
2709 /*
2710  * Collect new round-trip time estimate
2711  * and update averages and current timeout.
2712  */
2713 void
2714 tcp_xmit_timer(tp, rtt)
2715 	register struct tcpcb *tp;
2716 	short rtt;
2717 {
2718 	register short delta;
2719 	short rttmin;
2720 
2721 	tcpstat.tcps_rttupdated++;
2722 	--rtt;
2723 	if (tp->t_srtt != 0) {
2724 		/*
2725 		 * srtt is stored as fixed point with 3 bits after the
2726 		 * binary point (i.e., scaled by 8).  The following magic
2727 		 * is equivalent to the smoothing algorithm in rfc793 with
2728 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2729 		 * point).  Adjust rtt to origin 0.
2730 		 */
2731 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2732 		if ((tp->t_srtt += delta) <= 0)
2733 			tp->t_srtt = 1;
2734 		/*
2735 		 * We accumulate a smoothed rtt variance (actually, a
2736 		 * smoothed mean difference), then set the retransmit
2737 		 * timer to smoothed rtt + 4 times the smoothed variance.
2738 		 * rttvar is stored as fixed point with 2 bits after the
2739 		 * binary point (scaled by 4).  The following is
2740 		 * equivalent to rfc793 smoothing with an alpha of .75
2741 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2742 		 * rfc793's wired-in beta.
2743 		 */
2744 		if (delta < 0)
2745 			delta = -delta;
2746 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2747 		if ((tp->t_rttvar += delta) <= 0)
2748 			tp->t_rttvar = 1;
2749 	} else {
2750 		/*
2751 		 * No rtt measurement yet - use the unsmoothed rtt.
2752 		 * Set the variance to half the rtt (so our first
2753 		 * retransmit happens at 3*rtt).
2754 		 */
2755 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
2756 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
2757 	}
2758 	tp->t_rtt = 0;
2759 	tp->t_rxtshift = 0;
2760 
2761 	/*
2762 	 * the retransmit should happen at rtt + 4 * rttvar.
2763 	 * Because of the way we do the smoothing, srtt and rttvar
2764 	 * will each average +1/2 tick of bias.  When we compute
2765 	 * the retransmit timer, we want 1/2 tick of rounding and
2766 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2767 	 * firing of the timer.  The bias will give us exactly the
2768 	 * 1.5 tick we need.  But, because the bias is
2769 	 * statistical, we have to test that we don't drop below
2770 	 * the minimum feasible timer (which is 2 ticks).
2771 	 */
2772 	if (tp->t_rttmin > rtt + 2)
2773 		rttmin = tp->t_rttmin;
2774 	else
2775 		rttmin = rtt + 2;
2776 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
2777 
2778 	/*
2779 	 * We received an ack for a packet that wasn't retransmitted;
2780 	 * it is probably safe to discard any error indications we've
2781 	 * received recently.  This isn't quite right, but close enough
2782 	 * for now (a route might have failed after we sent a segment,
2783 	 * and the return path might not be symmetrical).
2784 	 */
2785 	tp->t_softerror = 0;
2786 }
2787 
2788 /*
2789  * Determine a reasonable value for maxseg size.
2790  * If the route is known, check route for mtu.
2791  * If none, use an mss that can be handled on the outgoing
2792  * interface without forcing IP to fragment; if bigger than
2793  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2794  * to utilize large mbufs.  If no route is found, route has no mtu,
2795  * or the destination isn't local, use a default, hopefully conservative
2796  * size (usually 512 or the default IP max size, but no more than the mtu
2797  * of the interface), as we can't discover anything about intervening
2798  * gateways or networks.  We also initialize the congestion/slow start
2799  * window to be a single segment if the destination isn't local.
2800  * While looking at the routing entry, we also initialize other path-dependent
2801  * parameters from pre-set or cached values in the routing entry.
2802  *
2803  * Also take into account the space needed for options that we
2804  * send regularly.  Make maxseg shorter by that amount to assure
2805  * that we can send maxseg amount of data even when the options
2806  * are present.  Store the upper limit of the length of options plus
2807  * data in maxopd.
2808  *
2809  * NOTE: offer == -1 indicates that the maxseg size changed due to
2810  * Path MTU discovery.
2811  */
2812 int
2813 tcp_mss(tp, offer)
2814 	register struct tcpcb *tp;
2815 	int offer;
2816 {
2817 	struct rtentry *rt;
2818 	struct ifnet *ifp;
2819 	int mss, mssopt;
2820 	int iphlen;
2821 	int is_ipv6 = 0;
2822 	struct inpcb *inp;
2823 
2824 	inp = tp->t_inpcb;
2825 
2826 	mssopt = mss = tcp_mssdflt;
2827 
2828 	rt = in_pcbrtentry(inp);
2829 
2830 	if (rt == NULL)
2831 		goto out;
2832 
2833 	ifp = rt->rt_ifp;
2834 
2835 	switch (tp->pf) {
2836 #ifdef INET6
2837 	case AF_INET6:
2838 		iphlen = sizeof(struct ip6_hdr);
2839 		is_ipv6 = 1;
2840 		break;
2841 #endif
2842 	case AF_INET:
2843 		iphlen = sizeof(struct ip);
2844 		break;
2845 	default:
2846 		/* the family does not support path MTU discovery */
2847 		goto out;
2848 	}
2849 
2850 #ifdef RTV_MTU
2851 	/*
2852 	 * if there's an mtu associated with the route and we support
2853 	 * path MTU discovery for the underlying protocol family, use it.
2854 	 */
2855 	if (rt->rt_rmx.rmx_mtu) {
2856 		/*
2857 		 * One may wish to lower MSS to take into account options,
2858 		 * especially security-related options.
2859 		 */
2860 		mss = rt->rt_rmx.rmx_mtu - iphlen - sizeof(struct tcphdr);
2861 	} else
2862 #endif /* RTV_MTU */
2863 	if (!ifp)
2864 		/*
2865 		 * ifp may be null and rmx_mtu may be zero in certain
2866 		 * v6 cases (e.g., if ND wasn't able to resolve the
2867 		 * destination host.
2868 		 */
2869 		goto out;
2870 	else if (ifp->if_flags & IFF_LOOPBACK)
2871 		mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2872 	else if (!is_ipv6) {
2873 		if (ip_mtudisc)
2874 			mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2875 		else if (inp && in_localaddr(inp->inp_faddr))
2876 			mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2877 	}
2878 #ifdef INET6
2879 	else if (is_ipv6) {
2880 		if (inp && IN6_IS_ADDR_V4MAPPED(&inp->inp_faddr6)) {
2881 			/* mapped addr case */
2882 			struct in_addr d;
2883 			bcopy(&inp->inp_faddr6.s6_addr32[3], &d, sizeof(d));
2884 			if (ip_mtudisc || in_localaddr(d))
2885 				mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2886 		} else {
2887 			/*
2888 			 * for IPv6, path MTU discovery is always turned on,
2889 			 * or the node must use packet size <= 1280.
2890 			 */
2891 			mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2892 		}
2893 	}
2894 #endif /* INET6 */
2895 
2896 	/* Calculate the value that we offer in TCPOPT_MAXSEG */
2897 	if (offer != -1) {
2898 		mssopt = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2899 		mssopt = max(tcp_mssdflt, mssopt);
2900 	}
2901 
2902  out:
2903 	/*
2904 	 * The current mss, t_maxseg, is initialized to the default value.
2905 	 * If we compute a smaller value, reduce the current mss.
2906 	 * If we compute a larger value, return it for use in sending
2907 	 * a max seg size option, but don't store it for use
2908 	 * unless we received an offer at least that large from peer.
2909 	 * However, do not accept offers under 64 bytes.
2910 	 */
2911 	if (offer > 0)
2912 		tp->t_peermss = offer;
2913 	if (tp->t_peermss)
2914 		mss = min(mss, tp->t_peermss);
2915 	mss = max(mss, 64);		/* sanity - at least max opt. space */
2916 
2917 	/*
2918 	 * maxopd stores the maximum length of data AND options
2919 	 * in a segment; maxseg is the amount of data in a normal
2920 	 * segment.  We need to store this value (maxopd) apart
2921 	 * from maxseg, because now every segment carries options
2922 	 * and thus we normally have somewhat less data in segments.
2923 	 */
2924 	tp->t_maxopd = mss;
2925 
2926  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2927 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
2928 		mss -= TCPOLEN_TSTAMP_APPA;
2929 
2930 	if (offer == -1) {
2931 		/* mss changed due to Path MTU discovery */
2932 		if (mss < tp->t_maxseg) {
2933 			/*
2934 			 * Follow suggestion in RFC 2414 to reduce the
2935 			 * congestion window by the ratio of the old
2936 			 * segment size to the new segment size.
2937 			 */
2938 			tp->snd_cwnd = ulmax((tp->snd_cwnd / tp->t_maxseg) *
2939 					     mss, mss);
2940 		}
2941 	} else
2942 		tp->snd_cwnd = mss;
2943 
2944 	tp->t_maxseg = mss;
2945 
2946 	return (offer != -1 ? mssopt : mss);
2947 }
2948 
2949 /*
2950  * Set connection variables based on the effective MSS.
2951  * We are passed the TCPCB for the actual connection.  If we
2952  * are the server, we are called by the compressed state engine
2953  * when the 3-way handshake is complete.  If we are the client,
2954  * we are called when we receive the SYN,ACK from the server.
2955  *
2956  * NOTE: The t_maxseg value must be initialized in the TCPCB
2957  * before this routine is called!
2958  */
2959 void
2960 tcp_mss_update(tp)
2961 	struct tcpcb *tp;
2962 {
2963 	int mss, rtt;
2964 	u_long bufsize;
2965 	struct rtentry *rt;
2966 	struct socket *so;
2967 
2968 	so = tp->t_inpcb->inp_socket;
2969 	mss = tp->t_maxseg;
2970 
2971 	rt = in_pcbrtentry(tp->t_inpcb);
2972 
2973 	if (rt == NULL)
2974 		return;
2975 
2976 #ifdef RTV_MTU	/* if route characteristics exist ... */
2977 	/*
2978 	 * While we're here, check if there's an initial rtt
2979 	 * or rttvar.  Convert from the route-table units
2980 	 * to scaled multiples of the slow timeout timer.
2981 	 */
2982 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2983 		/*
2984 		 * XXX the lock bit for MTU indicates that the value
2985 		 * is also a minimum value; this is subject to time.
2986 		 */
2987 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2988 			TCPT_RANGESET(tp->t_rttmin,
2989 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
2990 			    TCPTV_MIN, TCPTV_REXMTMAX);
2991 		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2992 		if (rt->rt_rmx.rmx_rttvar)
2993 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2994 			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2995 		else
2996 			/* default variation is +- 1 rtt */
2997 			tp->t_rttvar =
2998 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2999 		TCPT_RANGESET((long) tp->t_rxtcur,
3000 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3001 		    tp->t_rttmin, TCPTV_REXMTMAX);
3002 	}
3003 #endif
3004 
3005 	/*
3006 	 * If there's a pipesize, change the socket buffer
3007 	 * to that size.  Make the socket buffers an integral
3008 	 * number of mss units; if the mss is larger than
3009 	 * the socket buffer, decrease the mss.
3010 	 */
3011 #ifdef RTV_SPIPE
3012 	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3013 #endif
3014 		bufsize = so->so_snd.sb_hiwat;
3015 	if (bufsize < mss) {
3016 		mss = bufsize;
3017 		/* Update t_maxseg and t_maxopd */
3018 		tcp_mss(tp, mss);
3019 	} else {
3020 		bufsize = roundup(bufsize, mss);
3021 		if (bufsize > sb_max)
3022 			bufsize = sb_max;
3023 		(void)sbreserve(&so->so_snd, bufsize);
3024 	}
3025 
3026 #ifdef RTV_RPIPE
3027 	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3028 #endif
3029 		bufsize = so->so_rcv.sb_hiwat;
3030 	if (bufsize > mss) {
3031 		bufsize = roundup(bufsize, mss);
3032 		if (bufsize > sb_max)
3033 			bufsize = sb_max;
3034 		(void)sbreserve(&so->so_rcv, bufsize);
3035 #ifdef RTV_RPIPE
3036 		if (rt->rt_rmx.rmx_recvpipe > 0)
3037 			tcp_rscale(tp, so->so_rcv.sb_hiwat);
3038 #endif
3039 	}
3040 
3041 #ifdef RTV_SSTHRESH
3042 	if (rt->rt_rmx.rmx_ssthresh) {
3043 		/*
3044 		 * There's some sort of gateway or interface
3045 		 * buffer limit on the path.  Use this to set
3046 		 * the slow start threshhold, but set the
3047 		 * threshold to no less than 2*mss.
3048 		 */
3049 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3050 	}
3051 #endif /* RTV_MTU */
3052 }
3053 #endif /* TUBA_INCLUDE */
3054 
3055 #if defined (TCP_SACK)
3056 /*
3057  * Checks for partial ack.  If partial ack arrives, force the retransmission
3058  * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
3059  * 1.  By setting snd_nxt to ti_ack, this forces retransmission timer to
3060  * be started again.  If the ack advances at least to tp->snd_last, return 0.
3061  */
3062 int
3063 tcp_newreno(tp, th)
3064 	struct tcpcb *tp;
3065 	struct tcphdr *th;
3066 {
3067 	if (SEQ_LT(th->th_ack, tp->snd_last)) {
3068 		/*
3069 		 * snd_una has not been updated and the socket send buffer
3070 		 * not yet drained of the acked data, so we have to leave
3071 		 * snd_una as it was to get the correct data offset in
3072 		 * tcp_output().
3073 		 */
3074 		tcp_seq onxt = tp->snd_nxt;
3075 		u_long  ocwnd = tp->snd_cwnd;
3076 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
3077 		tp->t_rtt = 0;
3078 		tp->snd_nxt = th->th_ack;
3079 		/*
3080 		 * Set snd_cwnd to one segment beyond acknowledged offset
3081 		 * (tp->snd_una not yet updated when this function is called)
3082 		 */
3083 		tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3084 		(void) tcp_output(tp);
3085 		tp->snd_cwnd = ocwnd;
3086 		if (SEQ_GT(onxt, tp->snd_nxt))
3087 			tp->snd_nxt = onxt;
3088 		/*
3089 		 * Partial window deflation.  Relies on fact that tp->snd_una
3090 		 * not updated yet.
3091 		 */
3092 		tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
3093 		return 1;
3094 	}
3095 	return 0;
3096 }
3097 #endif /* TCP_SACK */
3098