xref: /openbsd-src/sys/netinet/tcp_input.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: tcp_input.c,v 1.100 2001/07/07 22:22:04 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 	MALLOC(tiqe, struct ipqent *, sizeof(struct ipqent), M_IPQ, M_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 				FREE(tiqe, M_IPQ);
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 		FREE(q, M_IPQ);
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 		FREE(q, M_IPQ);
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 		tp->t_timer[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 					tp->t_timer[TCPT_REXMT] = 0;
964 				else if (tp->t_timer[TCPT_PERSIST] == 0)
965 					tp->t_timer[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 		tp->t_timer[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 		tp->t_timer[TCPT_REXMT] = 0;
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 (tp->t_timer[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 						tp->t_timer[TCPT_REXMT] = 0;
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 					tp->t_timer[TCPT_REXMT] = 0;
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 			tp->t_timer[TCPT_REXMT] = 0;
1778 			needoutput = 1;
1779 		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1780 			tp->t_timer[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 		register u_int cw = tp->snd_cwnd;
1790 		register 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 					tp->t_timer[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 				tp->t_timer[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 			tp->t_timer[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 			tp->t_timer[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 			tp->t_timer[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(tp, th, cp, optlen)
2383 	struct tcpcb *tp;
2384 	struct tcphdr *th;
2385 	u_char *cp;
2386 	int    optlen;
2387 {
2388 	int tmp_olen;
2389 	u_char *tmp_cp;
2390 	struct sackhole *cur, *p, *temp;
2391 
2392 	if (tp->sack_disable)
2393 		return 1;
2394 
2395 	/* Note: TCPOLEN_SACK must be 2*sizeof(tcp_seq) */
2396 	if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2397 		return 1;
2398 	tmp_cp = cp + 2;
2399 	tmp_olen = optlen - 2;
2400 	if (tp->snd_numholes < 0)
2401 		tp->snd_numholes = 0;
2402 	if (tp->t_maxseg == 0)
2403 		panic("tcp_sack_option"); /* Should never happen */
2404 	while (tmp_olen > 0) {
2405 		struct sackblk sack;
2406 
2407 		bcopy((char *) tmp_cp, (char *) &(sack.start), sizeof(tcp_seq));
2408 		NTOHL(sack.start);
2409 		bcopy((char *) tmp_cp + sizeof(tcp_seq),
2410 		    (char *) &(sack.end), sizeof(tcp_seq));
2411 		NTOHL(sack.end);
2412 		tmp_olen -= TCPOLEN_SACK;
2413 		tmp_cp += TCPOLEN_SACK;
2414 		if (SEQ_LEQ(sack.end, sack.start))
2415 			continue; /* bad SACK fields */
2416 		if (SEQ_LEQ(sack.end, tp->snd_una))
2417 			continue; /* old block */
2418 #if defined(TCP_SACK) && defined(TCP_FACK)
2419 		/* Updates snd_fack.  */
2420 		if (SEQ_GEQ(sack.end, tp->snd_fack))
2421 			tp->snd_fack = sack.end;
2422 #endif /* TCP_FACK */
2423 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
2424 			if (SEQ_LT(sack.start, th->th_ack))
2425 				continue;
2426 		} else {
2427 			if (SEQ_LT(sack.start, tp->snd_una))
2428 				continue;
2429 		}
2430 		if (SEQ_GT(sack.end, tp->snd_max))
2431 			continue;
2432 		if (tp->snd_holes == 0) { /* first hole */
2433 			tp->snd_holes = (struct sackhole *)
2434 			    malloc(sizeof(struct sackhole), M_PCB, M_NOWAIT);
2435 			if (tp->snd_holes == NULL) {
2436 				/* ENOBUFS, so ignore SACKed block for now*/
2437 				continue;
2438 			}
2439 			cur = tp->snd_holes;
2440 			cur->start = th->th_ack;
2441 			cur->end = sack.start;
2442 			cur->rxmit = cur->start;
2443 			cur->next = 0;
2444 			tp->snd_numholes = 1;
2445 			tp->rcv_lastsack = sack.end;
2446 			/*
2447 			 * dups is at least one.  If more data has been
2448 			 * SACKed, it can be greater than one.
2449 			 */
2450 			cur->dups = min(tcprexmtthresh,
2451 			    ((sack.end - cur->end)/tp->t_maxseg));
2452 			if (cur->dups < 1)
2453 				cur->dups = 1;
2454 			continue; /* with next sack block */
2455 		}
2456 		/* Go thru list of holes:  p = previous,  cur = current */
2457 		p = cur = tp->snd_holes;
2458 		while (cur) {
2459 			if (SEQ_LEQ(sack.end, cur->start))
2460 				/* SACKs data before the current hole */
2461 				break; /* no use going through more holes */
2462 			if (SEQ_GEQ(sack.start, cur->end)) {
2463 				/* SACKs data beyond the current hole */
2464 				cur->dups++;
2465 				if ( ((sack.end - cur->end)/tp->t_maxseg) >=
2466 					tcprexmtthresh)
2467 					cur->dups = tcprexmtthresh;
2468 				p = cur;
2469 				cur = cur->next;
2470 				continue;
2471 			}
2472 			if (SEQ_LEQ(sack.start, cur->start)) {
2473 				/* Data acks at least the beginning of hole */
2474 #if defined(TCP_SACK) && defined(TCP_FACK)
2475 				if (SEQ_GT(sack.end, cur->rxmit))
2476 					tp->retran_data -=
2477 				    	    tcp_seq_subtract(cur->rxmit,
2478 					    cur->start);
2479 				else
2480 					tp->retran_data -=
2481 					    tcp_seq_subtract(sack.end,
2482 					    cur->start);
2483 #endif /* TCP_FACK */
2484 				if (SEQ_GEQ(sack.end,cur->end)){
2485 					/* Acks entire hole, so delete hole */
2486 					if (p != cur) {
2487 						p->next = cur->next;
2488 						free(cur, M_PCB);
2489 						cur = p->next;
2490 					} else {
2491 						cur=cur->next;
2492 						free(p, M_PCB);
2493 						p = cur;
2494 						tp->snd_holes = p;
2495 					}
2496 					tp->snd_numholes--;
2497 					continue;
2498 				}
2499 				/* otherwise, move start of hole forward */
2500 				cur->start = sack.end;
2501 				cur->rxmit = max (cur->rxmit, cur->start);
2502 				p = cur;
2503 				cur = cur->next;
2504 				continue;
2505 			}
2506 			/* move end of hole backward */
2507 			if (SEQ_GEQ(sack.end, cur->end)) {
2508 #if defined(TCP_SACK) && defined(TCP_FACK)
2509 				if (SEQ_GT(cur->rxmit, sack.start))
2510 					tp->retran_data -=
2511 					    tcp_seq_subtract(cur->rxmit,
2512 					    sack.start);
2513 #endif /* TCP_FACK */
2514 				cur->end = sack.start;
2515 				cur->rxmit = min (cur->rxmit, cur->end);
2516 				cur->dups++;
2517 				if ( ((sack.end - cur->end)/tp->t_maxseg) >=
2518 					tcprexmtthresh)
2519 					cur->dups = tcprexmtthresh;
2520 				p = cur;
2521 				cur = cur->next;
2522 				continue;
2523 			}
2524 			if (SEQ_LT(cur->start, sack.start) &&
2525 			    SEQ_GT(cur->end, sack.end)) {
2526 				/*
2527 				 * ACKs some data in middle of a hole; need to
2528 				 * split current hole
2529 				 */
2530 				temp = (struct sackhole *)malloc(sizeof(*temp),
2531 				    M_PCB,M_NOWAIT);
2532 				if (temp == NULL)
2533 					continue; /* ENOBUFS */
2534 #if defined(TCP_SACK) && defined(TCP_FACK)
2535 				if (SEQ_GT(cur->rxmit, sack.end))
2536 					tp->retran_data -=
2537 					    tcp_seq_subtract(sack.end,
2538 					    sack.start);
2539 				else if (SEQ_GT(cur->rxmit, sack.start))
2540 					tp->retran_data -=
2541 					    tcp_seq_subtract(cur->rxmit,
2542 					    sack.start);
2543 #endif /* TCP_FACK */
2544 				temp->next = cur->next;
2545 				temp->start = sack.end;
2546 				temp->end = cur->end;
2547 				temp->dups = cur->dups;
2548 				temp->rxmit = max (cur->rxmit, temp->start);
2549 				cur->end = sack.start;
2550 				cur->rxmit = min (cur->rxmit, cur->end);
2551 				cur->dups++;
2552 				if ( ((sack.end - cur->end)/tp->t_maxseg) >=
2553 					tcprexmtthresh)
2554 					cur->dups = tcprexmtthresh;
2555 				cur->next = temp;
2556 				p = temp;
2557 				cur = p->next;
2558 				tp->snd_numholes++;
2559 			}
2560 		}
2561 		/* At this point, p points to the last hole on the list */
2562 		if (SEQ_LT(tp->rcv_lastsack, sack.start)) {
2563 			/*
2564 			 * Need to append new hole at end.
2565 			 * Last hole is p (and it's not NULL).
2566 			 */
2567 			temp = (struct sackhole *) malloc(sizeof(*temp),
2568 			    M_PCB, M_NOWAIT);
2569 			if (temp == NULL)
2570 				continue; /* ENOBUFS */
2571 			temp->start = tp->rcv_lastsack;
2572 			temp->end = sack.start;
2573 			temp->dups = min(tcprexmtthresh,
2574 			    ((sack.end - sack.start)/tp->t_maxseg));
2575 			if (temp->dups < 1)
2576 				temp->dups = 1;
2577 			temp->rxmit = temp->start;
2578 			temp->next = 0;
2579 			p->next = temp;
2580 			tp->rcv_lastsack = sack.end;
2581 			tp->snd_numholes++;
2582 		}
2583 	}
2584 #if defined(TCP_SACK) && defined(TCP_FACK)
2585 	/*
2586 	 * Update retran_data and snd_awnd.  Go through the list of
2587 	 * holes.   Increment retran_data by (hole->rxmit - hole->start).
2588 	 */
2589 	tp->retran_data = 0;
2590 	cur = tp->snd_holes;
2591 	while (cur) {
2592 		tp->retran_data += cur->rxmit - cur->start;
2593 		cur = cur->next;
2594 	}
2595 	tp->snd_awnd = tcp_seq_subtract(tp->snd_nxt, tp->snd_fack) +
2596 	    tp->retran_data;
2597 #endif /* TCP_FACK */
2598 
2599 	return 0;
2600 }
2601 
2602 /*
2603  * Delete stale (i.e, cumulatively ack'd) holes.  Hole is deleted only if
2604  * it is completely acked; otherwise, tcp_sack_option(), called from
2605  * tcp_dooptions(), will fix up the hole.
2606  */
2607 void
2608 tcp_del_sackholes(tp, th)
2609 	struct tcpcb *tp;
2610 	struct tcphdr *th;
2611 {
2612 	if (!tp->sack_disable && tp->t_state != TCPS_LISTEN) {
2613 		/* max because this could be an older ack just arrived */
2614 		tcp_seq lastack = SEQ_GT(th->th_ack, tp->snd_una) ?
2615 			th->th_ack : tp->snd_una;
2616 		struct sackhole *cur = tp->snd_holes;
2617 		struct sackhole *prev = cur;
2618 		while (cur)
2619 			if (SEQ_LEQ(cur->end, lastack)) {
2620 				cur = cur->next;
2621 				free(prev, M_PCB);
2622 				prev = cur;
2623 				tp->snd_numholes--;
2624 			} else if (SEQ_LT(cur->start, lastack)) {
2625 				cur->start = lastack;
2626 				if (SEQ_LT(cur->rxmit, cur->start))
2627 					cur->rxmit = cur->start;
2628 				break;
2629 			} else
2630 				break;
2631 		tp->snd_holes = cur;
2632 	}
2633 }
2634 
2635 /*
2636  * Delete all receiver-side SACK information.
2637  */
2638 void
2639 tcp_clean_sackreport(tp)
2640 	struct tcpcb *tp;
2641 {
2642 	int i;
2643 
2644 	tp->rcv_numsacks = 0;
2645 	for (i = 0; i < MAX_SACK_BLKS; i++)
2646 		tp->sackblks[i].start = tp->sackblks[i].end=0;
2647 
2648 }
2649 
2650 /*
2651  * Checks for partial ack.  If partial ack arrives, turn off retransmission
2652  * timer, deflate the window, do not clear tp->t_dupacks, and return 1.
2653  * If the ack advances at least to tp->snd_last, return 0.
2654  */
2655 int
2656 tcp_sack_partialack(tp, th)
2657 	struct tcpcb *tp;
2658 	struct tcphdr *th;
2659 {
2660 	if (SEQ_LT(th->th_ack, tp->snd_last)) {
2661 		/* Turn off retx. timer (will start again next segment) */
2662 		tp->t_timer[TCPT_REXMT] = 0;
2663 		tp->t_rtt = 0;
2664 #ifndef TCP_FACK
2665 		/*
2666 		 * Partial window deflation.  This statement relies on the
2667 		 * fact that tp->snd_una has not been updated yet.  In FACK
2668 		 * hold snd_cwnd constant during fast recovery.
2669 		 */
2670 		if (tp->snd_cwnd > (th->th_ack - tp->snd_una)) {
2671 			tp->snd_cwnd -= th->th_ack - tp->snd_una;
2672 			tp->snd_cwnd += tp->t_maxseg;
2673 		} else
2674 			tp->snd_cwnd = tp->t_maxseg;
2675 #endif
2676 		return 1;
2677 	}
2678 	return 0;
2679 }
2680 #endif /* TCP_SACK */
2681 
2682 /*
2683  * Pull out of band byte out of a segment so
2684  * it doesn't appear in the user's data queue.
2685  * It is still reflected in the segment length for
2686  * sequencing purposes.
2687  */
2688 void
2689 tcp_pulloutofband(so, urgent, m, off)
2690 	struct socket *so;
2691 	u_int urgent;
2692 	register struct mbuf *m;
2693 	int off;
2694 {
2695         int cnt = off + urgent - 1;
2696 
2697 	while (cnt >= 0) {
2698 		if (m->m_len > cnt) {
2699 			char *cp = mtod(m, caddr_t) + cnt;
2700 			struct tcpcb *tp = sototcpcb(so);
2701 
2702 			tp->t_iobc = *cp;
2703 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2704 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2705 			m->m_len--;
2706 			return;
2707 		}
2708 		cnt -= m->m_len;
2709 		m = m->m_next;
2710 		if (m == 0)
2711 			break;
2712 	}
2713 	panic("tcp_pulloutofband");
2714 }
2715 
2716 /*
2717  * Collect new round-trip time estimate
2718  * and update averages and current timeout.
2719  */
2720 void
2721 tcp_xmit_timer(tp, rtt)
2722 	register struct tcpcb *tp;
2723 	short rtt;
2724 {
2725 	register short delta;
2726 	short rttmin;
2727 
2728 	tcpstat.tcps_rttupdated++;
2729 	--rtt;
2730 	if (tp->t_srtt != 0) {
2731 		/*
2732 		 * srtt is stored as fixed point with 3 bits after the
2733 		 * binary point (i.e., scaled by 8).  The following magic
2734 		 * is equivalent to the smoothing algorithm in rfc793 with
2735 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2736 		 * point).  Adjust rtt to origin 0.
2737 		 */
2738 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2739 		if ((tp->t_srtt += delta) <= 0)
2740 			tp->t_srtt = 1;
2741 		/*
2742 		 * We accumulate a smoothed rtt variance (actually, a
2743 		 * smoothed mean difference), then set the retransmit
2744 		 * timer to smoothed rtt + 4 times the smoothed variance.
2745 		 * rttvar is stored as fixed point with 2 bits after the
2746 		 * binary point (scaled by 4).  The following is
2747 		 * equivalent to rfc793 smoothing with an alpha of .75
2748 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2749 		 * rfc793's wired-in beta.
2750 		 */
2751 		if (delta < 0)
2752 			delta = -delta;
2753 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2754 		if ((tp->t_rttvar += delta) <= 0)
2755 			tp->t_rttvar = 1;
2756 	} else {
2757 		/*
2758 		 * No rtt measurement yet - use the unsmoothed rtt.
2759 		 * Set the variance to half the rtt (so our first
2760 		 * retransmit happens at 3*rtt).
2761 		 */
2762 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
2763 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
2764 	}
2765 	tp->t_rtt = 0;
2766 	tp->t_rxtshift = 0;
2767 
2768 	/*
2769 	 * the retransmit should happen at rtt + 4 * rttvar.
2770 	 * Because of the way we do the smoothing, srtt and rttvar
2771 	 * will each average +1/2 tick of bias.  When we compute
2772 	 * the retransmit timer, we want 1/2 tick of rounding and
2773 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2774 	 * firing of the timer.  The bias will give us exactly the
2775 	 * 1.5 tick we need.  But, because the bias is
2776 	 * statistical, we have to test that we don't drop below
2777 	 * the minimum feasible timer (which is 2 ticks).
2778 	 */
2779 	if (tp->t_rttmin > rtt + 2)
2780 		rttmin = tp->t_rttmin;
2781 	else
2782 		rttmin = rtt + 2;
2783 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
2784 
2785 	/*
2786 	 * We received an ack for a packet that wasn't retransmitted;
2787 	 * it is probably safe to discard any error indications we've
2788 	 * received recently.  This isn't quite right, but close enough
2789 	 * for now (a route might have failed after we sent a segment,
2790 	 * and the return path might not be symmetrical).
2791 	 */
2792 	tp->t_softerror = 0;
2793 }
2794 
2795 /*
2796  * Determine a reasonable value for maxseg size.
2797  * If the route is known, check route for mtu.
2798  * If none, use an mss that can be handled on the outgoing
2799  * interface without forcing IP to fragment; if bigger than
2800  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2801  * to utilize large mbufs.  If no route is found, route has no mtu,
2802  * or the destination isn't local, use a default, hopefully conservative
2803  * size (usually 512 or the default IP max size, but no more than the mtu
2804  * of the interface), as we can't discover anything about intervening
2805  * gateways or networks.  We also initialize the congestion/slow start
2806  * window to be a single segment if the destination isn't local.
2807  * While looking at the routing entry, we also initialize other path-dependent
2808  * parameters from pre-set or cached values in the routing entry.
2809  *
2810  * Also take into account the space needed for options that we
2811  * send regularly.  Make maxseg shorter by that amount to assure
2812  * that we can send maxseg amount of data even when the options
2813  * are present.  Store the upper limit of the length of options plus
2814  * data in maxopd.
2815  *
2816  * NOTE: offer == -1 indicates that the maxseg size changed due to
2817  * Path MTU discovery.
2818  */
2819 int
2820 tcp_mss(tp, offer)
2821 	register struct tcpcb *tp;
2822 	int offer;
2823 {
2824 	struct rtentry *rt;
2825 	struct ifnet *ifp;
2826 	int mss, mssopt;
2827 	int iphlen;
2828 	int is_ipv6 = 0;
2829 	struct inpcb *inp;
2830 
2831 	inp = tp->t_inpcb;
2832 
2833 	mssopt = mss = tcp_mssdflt;
2834 
2835 	rt = in_pcbrtentry(inp);
2836 
2837 	if (rt == NULL)
2838 		goto out;
2839 
2840 	ifp = rt->rt_ifp;
2841 
2842 	switch (tp->pf) {
2843 #ifdef INET6
2844 	case AF_INET6:
2845 		iphlen = sizeof(struct ip6_hdr);
2846 		is_ipv6 = 1;
2847 		break;
2848 #endif
2849 	case AF_INET:
2850 		iphlen = sizeof(struct ip);
2851 		break;
2852 	default:
2853 		/* the family does not support path MTU discovery */
2854 		goto out;
2855 	}
2856 
2857 #ifdef RTV_MTU
2858 	/*
2859 	 * if there's an mtu associated with the route and we support
2860 	 * path MTU discovery for the underlying protocol family, use it.
2861 	 */
2862 	if (rt->rt_rmx.rmx_mtu) {
2863 		/*
2864 		 * One may wish to lower MSS to take into account options,
2865 		 * especially security-related options.
2866 		 */
2867 		mss = rt->rt_rmx.rmx_mtu - iphlen - sizeof(struct tcphdr);
2868 	} else
2869 #endif /* RTV_MTU */
2870 	if (!ifp)
2871 		/*
2872 		 * ifp may be null and rmx_mtu may be zero in certain
2873 		 * v6 cases (e.g., if ND wasn't able to resolve the
2874 		 * destination host.
2875 		 */
2876 		goto out;
2877 	else if (ifp->if_flags & IFF_LOOPBACK)
2878 		mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2879 	else if (!is_ipv6) {
2880 		if (ip_mtudisc)
2881 			mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2882 		else if (inp && in_localaddr(inp->inp_faddr))
2883 			mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2884 	}
2885 #ifdef INET6
2886 	else if (is_ipv6) {
2887 		if (inp && IN6_IS_ADDR_V4MAPPED(&inp->inp_faddr6)) {
2888 			/* mapped addr case */
2889 			struct in_addr d;
2890 			bcopy(&inp->inp_faddr6.s6_addr32[3], &d, sizeof(d));
2891 			if (ip_mtudisc || in_localaddr(d))
2892 				mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2893 		} else {
2894 			/*
2895 			 * for IPv6, path MTU discovery is always turned on,
2896 			 * or the node must use packet size <= 1280.
2897 			 */
2898 			mss = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2899 		}
2900 	}
2901 #endif /* INET6 */
2902 
2903 	/* Calculate the value that we offer in TCPOPT_MAXSEG */
2904 	if (offer != -1) {
2905 		mssopt = ifp->if_mtu - iphlen - sizeof(struct tcphdr);
2906 		mssopt = max(tcp_mssdflt, mssopt);
2907 	}
2908 
2909  out:
2910 	/*
2911 	 * The current mss, t_maxseg, is initialized to the default value.
2912 	 * If we compute a smaller value, reduce the current mss.
2913 	 * If we compute a larger value, return it for use in sending
2914 	 * a max seg size option, but don't store it for use
2915 	 * unless we received an offer at least that large from peer.
2916 	 * However, do not accept offers under 64 bytes.
2917 	 */
2918 	if (offer > 0)
2919 		tp->t_peermss = offer;
2920 	if (tp->t_peermss)
2921 		mss = min(mss, tp->t_peermss);
2922 	mss = max(mss, 64);		/* sanity - at least max opt. space */
2923 
2924 	/*
2925 	 * maxopd stores the maximum length of data AND options
2926 	 * in a segment; maxseg is the amount of data in a normal
2927 	 * segment.  We need to store this value (maxopd) apart
2928 	 * from maxseg, because now every segment carries options
2929 	 * and thus we normally have somewhat less data in segments.
2930 	 */
2931 	tp->t_maxopd = mss;
2932 
2933  	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2934 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
2935 		mss -= TCPOLEN_TSTAMP_APPA;
2936 
2937 	if (offer == -1) {
2938 		/* mss changed due to Path MTU discovery */
2939 		if (mss < tp->t_maxseg) {
2940 			/*
2941 			 * Follow suggestion in RFC 2414 to reduce the
2942 			 * congestion window by the ratio of the old
2943 			 * segment size to the new segment size.
2944 			 */
2945 			tp->snd_cwnd = ulmax((tp->snd_cwnd / tp->t_maxseg) *
2946 					     mss, mss);
2947 		}
2948 	} else
2949 		tp->snd_cwnd = mss;
2950 
2951 	tp->t_maxseg = mss;
2952 
2953 	return (offer != -1 ? mssopt : mss);
2954 }
2955 
2956 /*
2957  * Set connection variables based on the effective MSS.
2958  * We are passed the TCPCB for the actual connection.  If we
2959  * are the server, we are called by the compressed state engine
2960  * when the 3-way handshake is complete.  If we are the client,
2961  * we are called when we receive the SYN,ACK from the server.
2962  *
2963  * NOTE: The t_maxseg value must be initialized in the TCPCB
2964  * before this routine is called!
2965  */
2966 void
2967 tcp_mss_update(tp)
2968 	struct tcpcb *tp;
2969 {
2970 	int mss, rtt;
2971 	u_long bufsize;
2972 	struct rtentry *rt;
2973 	struct socket *so;
2974 
2975 	so = tp->t_inpcb->inp_socket;
2976 	mss = tp->t_maxseg;
2977 
2978 	rt = in_pcbrtentry(tp->t_inpcb);
2979 
2980 	if (rt == NULL)
2981 		return;
2982 
2983 #ifdef RTV_MTU	/* if route characteristics exist ... */
2984 	/*
2985 	 * While we're here, check if there's an initial rtt
2986 	 * or rttvar.  Convert from the route-table units
2987 	 * to scaled multiples of the slow timeout timer.
2988 	 */
2989 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2990 		/*
2991 		 * XXX the lock bit for MTU indicates that the value
2992 		 * is also a minimum value; this is subject to time.
2993 		 */
2994 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2995 			TCPT_RANGESET(tp->t_rttmin,
2996 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
2997 			    TCPTV_MIN, TCPTV_REXMTMAX);
2998 		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2999 		if (rt->rt_rmx.rmx_rttvar)
3000 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
3001 			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
3002 		else
3003 			/* default variation is +- 1 rtt */
3004 			tp->t_rttvar =
3005 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3006 		TCPT_RANGESET((long) tp->t_rxtcur,
3007 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3008 		    tp->t_rttmin, TCPTV_REXMTMAX);
3009 	}
3010 #endif
3011 
3012 	/*
3013 	 * If there's a pipesize, change the socket buffer
3014 	 * to that size.  Make the socket buffers an integral
3015 	 * number of mss units; if the mss is larger than
3016 	 * the socket buffer, decrease the mss.
3017 	 */
3018 #ifdef RTV_SPIPE
3019 	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3020 #endif
3021 		bufsize = so->so_snd.sb_hiwat;
3022 	if (bufsize < mss) {
3023 		mss = bufsize;
3024 		/* Update t_maxseg and t_maxopd */
3025 		tcp_mss(tp, mss);
3026 	} else {
3027 		bufsize = roundup(bufsize, mss);
3028 		if (bufsize > sb_max)
3029 			bufsize = sb_max;
3030 		(void)sbreserve(&so->so_snd, bufsize);
3031 	}
3032 
3033 #ifdef RTV_RPIPE
3034 	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3035 #endif
3036 		bufsize = so->so_rcv.sb_hiwat;
3037 	if (bufsize > mss) {
3038 		bufsize = roundup(bufsize, mss);
3039 		if (bufsize > sb_max)
3040 			bufsize = sb_max;
3041 		(void)sbreserve(&so->so_rcv, bufsize);
3042 #ifdef RTV_RPIPE
3043 		if (rt->rt_rmx.rmx_recvpipe > 0)
3044 			tcp_rscale(tp, so->so_rcv.sb_hiwat);
3045 #endif
3046 	}
3047 
3048 #ifdef RTV_SSTHRESH
3049 	if (rt->rt_rmx.rmx_ssthresh) {
3050 		/*
3051 		 * There's some sort of gateway or interface
3052 		 * buffer limit on the path.  Use this to set
3053 		 * the slow start threshhold, but set the
3054 		 * threshold to no less than 2*mss.
3055 		 */
3056 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3057 	}
3058 #endif /* RTV_MTU */
3059 }
3060 #endif /* TUBA_INCLUDE */
3061 
3062 #if defined (TCP_SACK)
3063 /*
3064  * Checks for partial ack.  If partial ack arrives, force the retransmission
3065  * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
3066  * 1.  By setting snd_nxt to ti_ack, this forces retransmission timer to
3067  * be started again.  If the ack advances at least to tp->snd_last, return 0.
3068  */
3069 int
3070 tcp_newreno(tp, th)
3071 	struct tcpcb *tp;
3072 	struct tcphdr *th;
3073 {
3074 	if (SEQ_LT(th->th_ack, tp->snd_last)) {
3075 		/*
3076 		 * snd_una has not been updated and the socket send buffer
3077 		 * not yet drained of the acked data, so we have to leave
3078 		 * snd_una as it was to get the correct data offset in
3079 		 * tcp_output().
3080 		 */
3081 		tcp_seq onxt = tp->snd_nxt;
3082 		u_long  ocwnd = tp->snd_cwnd;
3083 		tp->t_timer[TCPT_REXMT] = 0;
3084 		tp->t_rtt = 0;
3085 		tp->snd_nxt = th->th_ack;
3086 		/*
3087 		 * Set snd_cwnd to one segment beyond acknowledged offset
3088 		 * (tp->snd_una not yet updated when this function is called)
3089 		 */
3090 		tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3091 		(void) tcp_output(tp);
3092 		tp->snd_cwnd = ocwnd;
3093 		if (SEQ_GT(onxt, tp->snd_nxt))
3094 			tp->snd_nxt = onxt;
3095 		/*
3096 		 * Partial window deflation.  Relies on fact that tp->snd_una
3097 		 * not updated yet.
3098 		 */
3099 		tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
3100 		return 1;
3101 	}
3102 	return 0;
3103 }
3104 #endif /* TCP_SACK */
3105