xref: /freebsd/sys/netinet/tcp_input.c (revision 282a3889ebf826db9839be296ff1dd903f6d6d6e)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
30  * $FreeBSD$
31  */
32 
33 #include "opt_ipfw.h"		/* for ipfw_fwd	*/
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_mac.h"
38 #include "opt_tcpdebug.h"
39 
40 #include <sys/param.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/proc.h>		/* for proc0 declaration */
45 #include <sys/protosw.h>
46 #include <sys/signalvar.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/systm.h>
52 
53 #include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
54 
55 #include <vm/uma.h>
56 
57 #include <net/if.h>
58 #include <net/route.h>
59 
60 #include <netinet/in.h>
61 #include <netinet/in_pcb.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
66 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
67 #include <netinet/ip_var.h>
68 #include <netinet/ip_options.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <netinet6/in6_pcb.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/nd6.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_fsm.h>
76 #include <netinet/tcp_seq.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #include <netinet6/tcp6_var.h>
80 #include <netinet/tcpip.h>
81 #ifdef TCPDEBUG
82 #include <netinet/tcp_debug.h>
83 #endif /* TCPDEBUG */
84 
85 #ifdef IPSEC
86 #include <netipsec/ipsec.h>
87 #include <netipsec/ipsec6.h>
88 #endif /*IPSEC*/
89 
90 #include <machine/in_cksum.h>
91 
92 #include <security/mac/mac_framework.h>
93 
94 static const int tcprexmtthresh = 3;
95 
96 struct	tcpstat tcpstat;
97 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
98     &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
99 
100 static int tcp_log_in_vain = 0;
101 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
102     &tcp_log_in_vain, 0, "Log all incoming TCP segments to closed ports");
103 
104 static int blackhole = 0;
105 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
106     &blackhole, 0, "Do not send RST on segments to closed ports");
107 
108 int tcp_delack_enabled = 1;
109 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
110     &tcp_delack_enabled, 0,
111     "Delay ACK to try and piggyback it onto a data packet");
112 
113 static int drop_synfin = 0;
114 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
115     &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
116 
117 static int tcp_do_rfc3042 = 1;
118 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
119     &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
120 
121 static int tcp_do_rfc3390 = 1;
122 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
123     &tcp_do_rfc3390, 0,
124     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
125 
126 static int tcp_insecure_rst = 0;
127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
128     &tcp_insecure_rst, 0,
129     "Follow the old (insecure) criteria for accepting RST packets");
130 
131 int	tcp_do_autorcvbuf = 1;
132 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
133     &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
134 
135 int	tcp_autorcvbuf_inc = 16*1024;
136 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
137     &tcp_autorcvbuf_inc, 0,
138     "Incrementor step size of automatic receive buffer");
139 
140 int	tcp_autorcvbuf_max = 256*1024;
141 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
142     &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
143 
144 struct inpcbhead tcb;
145 #define	tcb6	tcb  /* for KAME src sync over BSD*'s */
146 struct inpcbinfo tcbinfo;
147 
148 static void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
149 static void	 tcp_do_segment(struct mbuf *, struct tcphdr *,
150 		     struct socket *, struct tcpcb *, int, int);
151 static void	 tcp_dropwithreset(struct mbuf *, struct tcphdr *,
152 		     struct tcpcb *, int, int);
153 static void	 tcp_pulloutofband(struct socket *,
154 		     struct tcphdr *, struct mbuf *, int);
155 static void	 tcp_xmit_timer(struct tcpcb *, int);
156 static void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
157 
158 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
159 #ifdef INET6
160 #define ND6_HINT(tp) \
161 do { \
162 	if ((tp) && (tp)->t_inpcb && \
163 	    ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
164 		nd6_nud_hint(NULL, NULL, 0); \
165 } while (0)
166 #else
167 #define ND6_HINT(tp)
168 #endif
169 
170 /*
171  * Indicate whether this ack should be delayed.  We can delay the ack if
172  *	- there is no delayed ack timer in progress and
173  *	- our last ack wasn't a 0-sized window.  We never want to delay
174  *	  the ack that opens up a 0-sized window and
175  *		- delayed acks are enabled or
176  *		- this is a half-synchronized T/TCP connection.
177  */
178 #define DELAY_ACK(tp)							\
179 	((!tcp_timer_active(tp, TT_DELACK) &&				\
180 	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
181 	    (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
182 
183 
184 /*
185  * TCP input handling is split into multiple parts:
186  *   tcp6_input is a thin wrapper around tcp_input for the extended
187  *	ip6_protox[] call format in ip6_input
188  *   tcp_input handles primary segment validation, inpcb lookup and
189  *	SYN processing on listen sockets
190  *   tcp_do_segment processes the ACK and text of the segment for
191  *	establishing, established and closing connections
192  */
193 #ifdef INET6
194 int
195 tcp6_input(struct mbuf **mp, int *offp, int proto)
196 {
197 	struct mbuf *m = *mp;
198 	struct in6_ifaddr *ia6;
199 
200 	IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
201 
202 	/*
203 	 * draft-itojun-ipv6-tcp-to-anycast
204 	 * better place to put this in?
205 	 */
206 	ia6 = ip6_getdstifaddr(m);
207 	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
208 		struct ip6_hdr *ip6;
209 
210 		ip6 = mtod(m, struct ip6_hdr *);
211 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
212 			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
213 		return IPPROTO_DONE;
214 	}
215 
216 	tcp_input(m, *offp);
217 	return IPPROTO_DONE;
218 }
219 #endif
220 
221 void
222 tcp_input(struct mbuf *m, int off0)
223 {
224 	struct tcphdr *th;
225 	struct ip *ip = NULL;
226 	struct ipovly *ipov;
227 	struct inpcb *inp = NULL;
228 	struct tcpcb *tp = NULL;
229 	struct socket *so = NULL;
230 	u_char *optp = NULL;
231 	int optlen = 0;
232 	int len, tlen, off;
233 	int drop_hdrlen;
234 	int thflags;
235 	int rstreason = 0;	/* For badport_bandlim accounting purposes */
236 #ifdef IPFIREWALL_FORWARD
237 	struct m_tag *fwd_tag;
238 #endif
239 #ifdef INET6
240 	struct ip6_hdr *ip6 = NULL;
241 	int isipv6;
242 #else
243 	const void *ip6 = NULL;
244 	const int isipv6 = 0;
245 #endif
246 	struct tcpopt to;		/* options in this segment */
247 	char *s = NULL;			/* address and port logging */
248 
249 #ifdef TCPDEBUG
250 	/*
251 	 * The size of tcp_saveipgen must be the size of the max ip header,
252 	 * now IPv6.
253 	 */
254 	u_char tcp_saveipgen[IP6_HDR_LEN];
255 	struct tcphdr tcp_savetcp;
256 	short ostate = 0;
257 #endif
258 
259 #ifdef INET6
260 	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
261 #endif
262 
263 	to.to_flags = 0;
264 	tcpstat.tcps_rcvtotal++;
265 
266 	if (isipv6) {
267 #ifdef INET6
268 		/* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
269 		ip6 = mtod(m, struct ip6_hdr *);
270 		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
271 		if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
272 			tcpstat.tcps_rcvbadsum++;
273 			goto drop;
274 		}
275 		th = (struct tcphdr *)((caddr_t)ip6 + off0);
276 
277 		/*
278 		 * Be proactive about unspecified IPv6 address in source.
279 		 * As we use all-zero to indicate unbounded/unconnected pcb,
280 		 * unspecified IPv6 address can be used to confuse us.
281 		 *
282 		 * Note that packets with unspecified IPv6 destination is
283 		 * already dropped in ip6_input.
284 		 */
285 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
286 			/* XXX stat */
287 			goto drop;
288 		}
289 #else
290 		th = NULL;		/* XXX: Avoid compiler warning. */
291 #endif
292 	} else {
293 		/*
294 		 * Get IP and TCP header together in first mbuf.
295 		 * Note: IP leaves IP header in first mbuf.
296 		 */
297 		if (off0 > sizeof (struct ip)) {
298 			ip_stripoptions(m, (struct mbuf *)0);
299 			off0 = sizeof(struct ip);
300 		}
301 		if (m->m_len < sizeof (struct tcpiphdr)) {
302 			if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
303 			    == NULL) {
304 				tcpstat.tcps_rcvshort++;
305 				return;
306 			}
307 		}
308 		ip = mtod(m, struct ip *);
309 		ipov = (struct ipovly *)ip;
310 		th = (struct tcphdr *)((caddr_t)ip + off0);
311 		tlen = ip->ip_len;
312 
313 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
314 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
315 				th->th_sum = m->m_pkthdr.csum_data;
316 			else
317 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
318 						ip->ip_dst.s_addr,
319 						htonl(m->m_pkthdr.csum_data +
320 							ip->ip_len +
321 							IPPROTO_TCP));
322 			th->th_sum ^= 0xffff;
323 #ifdef TCPDEBUG
324 			ipov->ih_len = (u_short)tlen;
325 			ipov->ih_len = htons(ipov->ih_len);
326 #endif
327 		} else {
328 			/*
329 			 * Checksum extended TCP header and data.
330 			 */
331 			len = sizeof (struct ip) + tlen;
332 			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
333 			ipov->ih_len = (u_short)tlen;
334 			ipov->ih_len = htons(ipov->ih_len);
335 			th->th_sum = in_cksum(m, len);
336 		}
337 		if (th->th_sum) {
338 			tcpstat.tcps_rcvbadsum++;
339 			goto drop;
340 		}
341 		/* Re-initialization for later version check */
342 		ip->ip_v = IPVERSION;
343 	}
344 
345 	/*
346 	 * Check that TCP offset makes sense,
347 	 * pull out TCP options and adjust length.		XXX
348 	 */
349 	off = th->th_off << 2;
350 	if (off < sizeof (struct tcphdr) || off > tlen) {
351 		tcpstat.tcps_rcvbadoff++;
352 		goto drop;
353 	}
354 	tlen -= off;	/* tlen is used instead of ti->ti_len */
355 	if (off > sizeof (struct tcphdr)) {
356 		if (isipv6) {
357 #ifdef INET6
358 			IP6_EXTHDR_CHECK(m, off0, off, );
359 			ip6 = mtod(m, struct ip6_hdr *);
360 			th = (struct tcphdr *)((caddr_t)ip6 + off0);
361 #endif
362 		} else {
363 			if (m->m_len < sizeof(struct ip) + off) {
364 				if ((m = m_pullup(m, sizeof (struct ip) + off))
365 				    == NULL) {
366 					tcpstat.tcps_rcvshort++;
367 					return;
368 				}
369 				ip = mtod(m, struct ip *);
370 				ipov = (struct ipovly *)ip;
371 				th = (struct tcphdr *)((caddr_t)ip + off0);
372 			}
373 		}
374 		optlen = off - sizeof (struct tcphdr);
375 		optp = (u_char *)(th + 1);
376 	}
377 	thflags = th->th_flags;
378 
379 	/*
380 	 * Convert TCP protocol specific fields to host format.
381 	 */
382 	th->th_seq = ntohl(th->th_seq);
383 	th->th_ack = ntohl(th->th_ack);
384 	th->th_win = ntohs(th->th_win);
385 	th->th_urp = ntohs(th->th_urp);
386 
387 	/*
388 	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
389 	 */
390 	drop_hdrlen = off0 + off;
391 
392 	/*
393 	 * Locate pcb for segment.
394 	 */
395 	INP_INFO_WLOCK(&tcbinfo);
396 findpcb:
397 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
398 #ifdef IPFIREWALL_FORWARD
399 	/*
400 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
401 	 */
402 	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
403 
404 	if (fwd_tag != NULL && isipv6 == 0) {	/* IPv6 support is not yet */
405 		struct sockaddr_in *next_hop;
406 
407 		next_hop = (struct sockaddr_in *)(fwd_tag+1);
408 		/*
409 		 * Transparently forwarded. Pretend to be the destination.
410 		 * already got one like this?
411 		 */
412 		inp = in_pcblookup_hash(&tcbinfo,
413 					ip->ip_src, th->th_sport,
414 					ip->ip_dst, th->th_dport,
415 					0, m->m_pkthdr.rcvif);
416 		if (!inp) {
417 			/* It's new.  Try to find the ambushing socket. */
418 			inp = in_pcblookup_hash(&tcbinfo,
419 						ip->ip_src, th->th_sport,
420 						next_hop->sin_addr,
421 						next_hop->sin_port ?
422 						    ntohs(next_hop->sin_port) :
423 						    th->th_dport,
424 						INPLOOKUP_WILDCARD,
425 						m->m_pkthdr.rcvif);
426 		}
427 		/* Remove the tag from the packet.  We don't need it anymore. */
428 		m_tag_delete(m, fwd_tag);
429 	} else
430 #endif /* IPFIREWALL_FORWARD */
431 	{
432 		if (isipv6) {
433 #ifdef INET6
434 			inp = in6_pcblookup_hash(&tcbinfo,
435 						 &ip6->ip6_src, th->th_sport,
436 						 &ip6->ip6_dst, th->th_dport,
437 						 INPLOOKUP_WILDCARD,
438 						 m->m_pkthdr.rcvif);
439 #endif
440 		} else
441 			inp = in_pcblookup_hash(&tcbinfo,
442 						ip->ip_src, th->th_sport,
443 						ip->ip_dst, th->th_dport,
444 						INPLOOKUP_WILDCARD,
445 						m->m_pkthdr.rcvif);
446 	}
447 
448 #ifdef IPSEC
449 #ifdef INET6
450 	if (isipv6 && inp != NULL && ipsec6_in_reject(m, inp)) {
451 		ipsec6stat.in_polvio++;
452 		goto dropunlock;
453 	} else
454 #endif /* INET6 */
455 	if (inp != NULL && ipsec4_in_reject(m, inp)) {
456 		ipsec4stat.in_polvio++;
457 		goto dropunlock;
458 	}
459 #endif /* IPSEC */
460 
461 	/*
462 	 * If the INPCB does not exist then all data in the incoming
463 	 * segment is discarded and an appropriate RST is sent back.
464 	 */
465 	if (inp == NULL) {
466 		/*
467 		 * Log communication attempts to ports that are not
468 		 * in use.
469 		 */
470 		if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
471 		    tcp_log_in_vain == 2) {
472 			if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
473 				log(LOG_INFO, "%s; %s: Connection attempt "
474 				    "to closed port\n", s, __func__);
475 		}
476 		/*
477 		 * When blackholing do not respond with a RST but
478 		 * completely ignore the segment and drop it.
479 		 */
480 		if ((blackhole == 1 && (thflags & TH_SYN)) ||
481 		    blackhole == 2)
482 			goto dropunlock;
483 
484 		rstreason = BANDLIM_RST_CLOSEDPORT;
485 		goto dropwithreset;
486 	}
487 	INP_LOCK(inp);
488 
489 	/*
490 	 * Check the minimum TTL for socket.
491 	 */
492 	if (inp->inp_ip_minttl != 0) {
493 #ifdef INET6
494 		if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
495 			goto dropunlock;
496 		else
497 #endif
498 		if (inp->inp_ip_minttl > ip->ip_ttl)
499 			goto dropunlock;
500 	}
501 
502 	/*
503 	 * A previous connection in TIMEWAIT state is supposed to catch
504 	 * stray or duplicate segments arriving late.  If this segment
505 	 * was a legitimate new connection attempt the old INPCB gets
506 	 * removed and we can try again to find a listening socket.
507 	 */
508 	if (inp->inp_vflag & INP_TIMEWAIT) {
509 		if (thflags & TH_SYN)
510 			tcp_dooptions(&to, optp, optlen, TO_SYN);
511 		/*
512 		 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
513 		 */
514 		if (tcp_twcheck(inp, &to, th, m, tlen))
515 			goto findpcb;
516 		INP_INFO_WUNLOCK(&tcbinfo);
517 		return;
518 	}
519 	/*
520 	 * The TCPCB may no longer exist if the connection is winding
521 	 * down or it is in the CLOSED state.  Either way we drop the
522 	 * segment and send an appropriate response.
523 	 */
524 	tp = intotcpcb(inp);
525 	if (tp == NULL || tp->t_state == TCPS_CLOSED) {
526 		rstreason = BANDLIM_RST_CLOSEDPORT;
527 		goto dropwithreset;
528 	}
529 
530 #ifdef MAC
531 	INP_LOCK_ASSERT(inp);
532 	if (mac_check_inpcb_deliver(inp, m))
533 		goto dropunlock;
534 #endif
535 	so = inp->inp_socket;
536 	KASSERT(so != NULL, ("%s: so == NULL", __func__));
537 #ifdef TCPDEBUG
538 	if (so->so_options & SO_DEBUG) {
539 		ostate = tp->t_state;
540 		if (isipv6) {
541 #ifdef INET6
542 			bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
543 #endif
544 		} else
545 			bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
546 		tcp_savetcp = *th;
547 	}
548 #endif
549 	/*
550 	 * When the socket is accepting connections (the INPCB is in LISTEN
551 	 * state) we look into the SYN cache if this is a new connection
552 	 * attempt or the completion of a previous one.
553 	 */
554 	if (so->so_options & SO_ACCEPTCONN) {
555 		struct in_conninfo inc;
556 
557 		KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
558 		    "tp not listening", __func__));
559 
560 		bzero(&inc, sizeof(inc));
561 		inc.inc_isipv6 = isipv6;
562 #ifdef INET6
563 		if (isipv6) {
564 			inc.inc6_faddr = ip6->ip6_src;
565 			inc.inc6_laddr = ip6->ip6_dst;
566 		} else
567 #endif
568 		{
569 			inc.inc_faddr = ip->ip_src;
570 			inc.inc_laddr = ip->ip_dst;
571 		}
572 		inc.inc_fport = th->th_sport;
573 		inc.inc_lport = th->th_dport;
574 
575 		/*
576 		 * Check for an existing connection attempt in syncache if
577 		 * the flag is only ACK.  A successful lookup creates a new
578 		 * socket appended to the listen queue in SYN_RECEIVED state.
579 		 */
580 		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
581 			/*
582 			 * Parse the TCP options here because
583 			 * syncookies need access to the reflected
584 			 * timestamp.
585 			 */
586 			tcp_dooptions(&to, optp, optlen, 0);
587 			/*
588 			 * NB: syncache_expand() doesn't unlock
589 			 * inp and tcpinfo locks.
590 			 */
591 			if (!syncache_expand(&inc, &to, th, &so, m)) {
592 				/*
593 				 * No syncache entry or ACK was not
594 				 * for our SYN/ACK.  Send a RST.
595 				 * NB: syncache did its own logging
596 				 * of the failure cause.
597 				 */
598 				rstreason = BANDLIM_RST_OPENPORT;
599 				goto dropwithreset;
600 			}
601 			if (so == NULL) {
602 				/*
603 				 * We completed the 3-way handshake
604 				 * but could not allocate a socket
605 				 * either due to memory shortage,
606 				 * listen queue length limits or
607 				 * global socket limits.  Send RST
608 				 * or wait and have the remote end
609 				 * retransmit the ACK for another
610 				 * try.
611 				 */
612 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
613 					log(LOG_DEBUG, "%s; %s: Listen socket: "
614 					    "Socket allocation failed due to "
615 					    "limits or memory shortage, %s\n",
616 					    s, __func__, (tcp_sc_rst_sock_fail ?
617 					    "sending RST" : "try again"));
618 				if (tcp_sc_rst_sock_fail) {
619 					rstreason = BANDLIM_UNLIMITED;
620 					goto dropwithreset;
621 				} else
622 					goto dropunlock;
623 			}
624 			/*
625 			 * Socket is created in state SYN_RECEIVED.
626 			 * Unlock the listen socket, lock the newly
627 			 * created socket and update the tp variable.
628 			 */
629 			INP_UNLOCK(inp);	/* listen socket */
630 			inp = sotoinpcb(so);
631 			INP_LOCK(inp);		/* new connection */
632 			tp = intotcpcb(inp);
633 			KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
634 			    ("%s: ", __func__));
635 			/*
636 			 * Process the segment and the data it
637 			 * contains.  tcp_do_segment() consumes
638 			 * the mbuf chain and unlocks the inpcb.
639 			 */
640 			tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
641 			INP_INFO_UNLOCK_ASSERT(&tcbinfo);
642 			return;
643 		}
644 		/*
645 		 * Segment flag validation for new connection attempts:
646 		 *
647 		 * Our (SYN|ACK) response was rejected.
648 		 * Check with syncache and remove entry to prevent
649 		 * retransmits.
650 		 */
651 		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
652 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
653 				log(LOG_DEBUG, "%s; %s: Listen socket: "
654 				    "Our SYN|ACK was rejected, connection "
655 				    "attempt aborted by remote endpoint\n",
656 				    s, __func__);
657 			syncache_chkrst(&inc, th);
658 			goto dropunlock;
659 		}
660 		/*
661 		 * Spurious RST.  Ignore.
662 		 */
663 		if (thflags & TH_RST) {
664 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
665 				log(LOG_DEBUG, "%s; %s: Listen socket: "
666 				    "Spurious RST, segment rejected\n",
667 				    s, __func__);
668 			goto dropunlock;
669 		}
670 		/*
671 		 * We can't do anything without SYN.
672 		 */
673 		if ((thflags & TH_SYN) == 0) {
674 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
675 				log(LOG_DEBUG, "%s; %s: Listen socket: "
676 				    "SYN is missing, segment rejected\n",
677 				    s, __func__);
678 			tcpstat.tcps_badsyn++;
679 			goto dropunlock;
680 		}
681 		/*
682 		 * (SYN|ACK) is bogus on a listen socket.
683 		 */
684 		if (thflags & TH_ACK) {
685 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
686 				log(LOG_DEBUG, "%s; %s: Listen socket: "
687 				    "SYN|ACK invalid, segment rejected\n",
688 				    s, __func__);
689 			syncache_badack(&inc);	/* XXX: Not needed! */
690 			tcpstat.tcps_badsyn++;
691 			rstreason = BANDLIM_RST_OPENPORT;
692 			goto dropwithreset;
693 		}
694 		/*
695 		 * If the drop_synfin option is enabled, drop all
696 		 * segments with both the SYN and FIN bits set.
697 		 * This prevents e.g. nmap from identifying the
698 		 * TCP/IP stack.
699 		 * XXX: Poor reasoning.  nmap has other methods
700 		 * and is constantly refining its stack detection
701 		 * strategies.
702 		 * XXX: This is a violation of the TCP specification
703 		 * and was used by RFC1644.
704 		 */
705 		if ((thflags & TH_FIN) && drop_synfin) {
706 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
707 				log(LOG_DEBUG, "%s; %s: Listen socket: "
708 				    "SYN|FIN segment rejected (based on "
709 				    "sysctl setting)\n", s, __func__);
710 			tcpstat.tcps_badsyn++;
711                 	goto dropunlock;
712 		}
713 		/*
714 		 * Segment's flags are (SYN) or (SYN|FIN).
715 		 *
716 		 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
717 		 * as they do not affect the state of the TCP FSM.
718 		 * The data pointed to by TH_URG and th_urp is ignored.
719 		 */
720 		KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
721 		    ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
722 		KASSERT(thflags & (TH_SYN),
723 		    ("%s: Listen socket: TH_SYN not set", __func__));
724 #ifdef INET6
725 		/*
726 		 * If deprecated address is forbidden,
727 		 * we do not accept SYN to deprecated interface
728 		 * address to prevent any new inbound connection from
729 		 * getting established.
730 		 * When we do not accept SYN, we send a TCP RST,
731 		 * with deprecated source address (instead of dropping
732 		 * it).  We compromise it as it is much better for peer
733 		 * to send a RST, and RST will be the final packet
734 		 * for the exchange.
735 		 *
736 		 * If we do not forbid deprecated addresses, we accept
737 		 * the SYN packet.  RFC2462 does not suggest dropping
738 		 * SYN in this case.
739 		 * If we decipher RFC2462 5.5.4, it says like this:
740 		 * 1. use of deprecated addr with existing
741 		 *    communication is okay - "SHOULD continue to be
742 		 *    used"
743 		 * 2. use of it with new communication:
744 		 *   (2a) "SHOULD NOT be used if alternate address
745 		 *        with sufficient scope is available"
746 		 *   (2b) nothing mentioned otherwise.
747 		 * Here we fall into (2b) case as we have no choice in
748 		 * our source address selection - we must obey the peer.
749 		 *
750 		 * The wording in RFC2462 is confusing, and there are
751 		 * multiple description text for deprecated address
752 		 * handling - worse, they are not exactly the same.
753 		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
754 		 */
755 		if (isipv6 && !ip6_use_deprecated) {
756 			struct in6_ifaddr *ia6;
757 
758 			if ((ia6 = ip6_getdstifaddr(m)) &&
759 			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
760 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
761 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
762 					"Connection attempt to deprecated "
763 					"IPv6 address rejected\n",
764 					s, __func__);
765 				rstreason = BANDLIM_RST_OPENPORT;
766 				goto dropwithreset;
767 			}
768 		}
769 #endif
770 		/*
771 		 * Basic sanity checks on incoming SYN requests:
772 		 *   Don't respond if the destination is a link layer
773 		 *	broadcast according to RFC1122 4.2.3.10, p. 104.
774 		 *   If it is from this socket it must be forged.
775 		 *   Don't respond if the source or destination is a
776 		 *	global or subnet broad- or multicast address.
777 		 *   Note that it is quite possible to receive unicast
778 		 *	link-layer packets with a broadcast IP address. Use
779 		 *	in_broadcast() to find them.
780 		 */
781 		if (m->m_flags & (M_BCAST|M_MCAST)) {
782 			if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
783 			    log(LOG_DEBUG, "%s; %s: Listen socket: "
784 				"Connection attempt from broad- or multicast "
785 				"link layer address rejected\n", s, __func__);
786 			goto dropunlock;
787 		}
788 		if (isipv6) {
789 #ifdef INET6
790 			if (th->th_dport == th->th_sport &&
791 			    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
792 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
793 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
794 					"Connection attempt to/from self "
795 					"rejected\n", s, __func__);
796 				goto dropunlock;
797 			}
798 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
799 			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
800 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
801 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
802 					"Connection attempt from/to multicast "
803 					"address rejected\n", s, __func__);
804 				goto dropunlock;
805 			}
806 #endif
807 		} else {
808 			if (th->th_dport == th->th_sport &&
809 			    ip->ip_dst.s_addr == ip->ip_src.s_addr) {
810 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
811 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
812 					"Connection attempt from/to self "
813 					"rejected\n", s, __func__);
814 				goto dropunlock;
815 			}
816 			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
817 			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
818 			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
819 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
820 				if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
821 				    log(LOG_DEBUG, "%s; %s: Listen socket: "
822 					"Connection attempt from/to broad- "
823 					"or multicast address rejected\n",
824 					s, __func__);
825 				goto dropunlock;
826 			}
827 		}
828 		/*
829 		 * SYN appears to be valid.  Create compressed TCP state
830 		 * for syncache.
831 		 */
832 #ifdef TCPDEBUG
833 		if (so->so_options & SO_DEBUG)
834 			tcp_trace(TA_INPUT, ostate, tp,
835 			    (void *)tcp_saveipgen, &tcp_savetcp, 0);
836 #endif
837 		tcp_dooptions(&to, optp, optlen, TO_SYN);
838 		syncache_add(&inc, &to, th, inp, &so, m);
839 		/*
840 		 * Entry added to syncache and mbuf consumed.
841 		 * Everything already unlocked by syncache_add().
842 		 */
843 		INP_INFO_UNLOCK_ASSERT(&tcbinfo);
844 		return;
845 	}
846 
847 	/*
848 	 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
849 	 * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
850 	 * the inpcb, and unlocks pcbinfo.
851 	 */
852 	tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen);
853 	INP_INFO_UNLOCK_ASSERT(&tcbinfo);
854 	return;
855 
856 dropwithreset:
857 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
858 	tcp_dropwithreset(m, th, tp, tlen, rstreason);
859 	m = NULL;	/* mbuf chain got consumed. */
860 dropunlock:
861 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
862 	if (inp != NULL)
863 		INP_UNLOCK(inp);
864 	INP_INFO_WUNLOCK(&tcbinfo);
865 drop:
866 	INP_INFO_UNLOCK_ASSERT(&tcbinfo);
867 	if (s != NULL)
868 		free(s, M_TCPLOG);
869 	if (m != NULL)
870 		m_freem(m);
871 	return;
872 }
873 
874 static void
875 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
876     struct tcpcb *tp, int drop_hdrlen, int tlen)
877 {
878 	int thflags, acked, ourfinisacked, needoutput = 0;
879 	int headlocked = 1;
880 	int rstreason, todrop, win;
881 	u_long tiwin;
882 	struct tcpopt to;
883 
884 #ifdef TCPDEBUG
885 	/*
886 	 * The size of tcp_saveipgen must be the size of the max ip header,
887 	 * now IPv6.
888 	 */
889 	u_char tcp_saveipgen[IP6_HDR_LEN];
890 	struct tcphdr tcp_savetcp;
891 	short ostate = 0;
892 #endif
893 	thflags = th->th_flags;
894 
895 	INP_INFO_WLOCK_ASSERT(&tcbinfo);
896 	INP_LOCK_ASSERT(tp->t_inpcb);
897 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
898 	    __func__));
899 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
900 	    __func__));
901 
902 	/*
903 	 * Segment received on connection.
904 	 * Reset idle time and keep-alive timer.
905 	 * XXX: This should be done after segment
906 	 * validation to ignore broken/spoofed segs.
907 	 */
908 	tp->t_rcvtime = ticks;
909 	if (TCPS_HAVEESTABLISHED(tp->t_state))
910 		tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
911 
912 	/*
913 	 * Unscale the window into a 32-bit value.
914 	 * For the SYN_SENT state the scale is zero.
915 	 */
916 	tiwin = th->th_win << tp->snd_scale;
917 
918 	/*
919 	 * Parse options on any incoming segment.
920 	 */
921 	tcp_dooptions(&to, (u_char *)(th + 1),
922 	    (th->th_off << 2) - sizeof(struct tcphdr),
923 	    (thflags & TH_SYN) ? TO_SYN : 0);
924 
925 	/*
926 	 * If echoed timestamp is later than the current time,
927 	 * fall back to non RFC1323 RTT calculation.  Normalize
928 	 * timestamp if syncookies were used when this connection
929 	 * was established.
930 	 */
931 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
932 		to.to_tsecr -= tp->ts_offset;
933 		if (TSTMP_GT(to.to_tsecr, ticks))
934 			to.to_tsecr = 0;
935 	}
936 
937 	/*
938 	 * Process options only when we get SYN/ACK back. The SYN case
939 	 * for incoming connections is handled in tcp_syncache.
940 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
941 	 * or <SYN,ACK>) segment itself is never scaled.
942 	 * XXX this is traditional behavior, may need to be cleaned up.
943 	 */
944 	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
945 		if ((to.to_flags & TOF_SCALE) &&
946 		    (tp->t_flags & TF_REQ_SCALE)) {
947 			tp->t_flags |= TF_RCVD_SCALE;
948 			tp->snd_scale = to.to_wscale;
949 		}
950 		/*
951 		 * Initial send window.  It will be updated with
952 		 * the next incoming segment to the scaled value.
953 		 */
954 		tp->snd_wnd = th->th_win;
955 		if (to.to_flags & TOF_TS) {
956 			tp->t_flags |= TF_RCVD_TSTMP;
957 			tp->ts_recent = to.to_tsval;
958 			tp->ts_recent_age = ticks;
959 		}
960 		if (to.to_flags & TOF_MSS)
961 			tcp_mss(tp, to.to_mss);
962 		if ((tp->t_flags & TF_SACK_PERMIT) &&
963 		    (to.to_flags & TOF_SACKPERM) == 0)
964 			tp->t_flags &= ~TF_SACK_PERMIT;
965 	}
966 
967 	/*
968 	 * Header prediction: check for the two common cases
969 	 * of a uni-directional data xfer.  If the packet has
970 	 * no control flags, is in-sequence, the window didn't
971 	 * change and we're not retransmitting, it's a
972 	 * candidate.  If the length is zero and the ack moved
973 	 * forward, we're the sender side of the xfer.  Just
974 	 * free the data acked & wake any higher level process
975 	 * that was blocked waiting for space.  If the length
976 	 * is non-zero and the ack didn't move, we're the
977 	 * receiver side.  If we're getting packets in-order
978 	 * (the reassembly queue is empty), add the data to
979 	 * the socket buffer and note that we need a delayed ack.
980 	 * Make sure that the hidden state-flags are also off.
981 	 * Since we check for TCPS_ESTABLISHED first, it can only
982 	 * be TH_NEEDSYN.
983 	 */
984 	if (tp->t_state == TCPS_ESTABLISHED &&
985 	    th->th_seq == tp->rcv_nxt &&
986 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
987 	    tp->snd_nxt == tp->snd_max &&
988 	    tiwin && tiwin == tp->snd_wnd &&
989 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
990 	    LIST_EMPTY(&tp->t_segq) &&
991 	    ((to.to_flags & TOF_TS) == 0 ||
992 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
993 
994 		/*
995 		 * If last ACK falls within this segment's sequence numbers,
996 		 * record the timestamp.
997 		 * NOTE that the test is modified according to the latest
998 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
999 		 */
1000 		if ((to.to_flags & TOF_TS) != 0 &&
1001 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1002 			tp->ts_recent_age = ticks;
1003 			tp->ts_recent = to.to_tsval;
1004 		}
1005 
1006 		if (tlen == 0) {
1007 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1008 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1009 			    tp->snd_cwnd >= tp->snd_wnd &&
1010 			    ((!tcp_do_newreno &&
1011 			      !(tp->t_flags & TF_SACK_PERMIT) &&
1012 			      tp->t_dupacks < tcprexmtthresh) ||
1013 			     ((tcp_do_newreno ||
1014 			       (tp->t_flags & TF_SACK_PERMIT)) &&
1015 			      !IN_FASTRECOVERY(tp) &&
1016 			      (to.to_flags & TOF_SACK) == 0 &&
1017 			      TAILQ_EMPTY(&tp->snd_holes)))) {
1018 				KASSERT(headlocked,
1019 				    ("%s: headlocked", __func__));
1020 				INP_INFO_WUNLOCK(&tcbinfo);
1021 				headlocked = 0;
1022 				/*
1023 				 * This is a pure ack for outstanding data.
1024 				 */
1025 				++tcpstat.tcps_predack;
1026 				/*
1027 				 * "bad retransmit" recovery.
1028 				 */
1029 				if (tp->t_rxtshift == 1 &&
1030 				    ticks < tp->t_badrxtwin) {
1031 					++tcpstat.tcps_sndrexmitbad;
1032 					tp->snd_cwnd = tp->snd_cwnd_prev;
1033 					tp->snd_ssthresh =
1034 					    tp->snd_ssthresh_prev;
1035 					tp->snd_recover = tp->snd_recover_prev;
1036 					if (tp->t_flags & TF_WASFRECOVERY)
1037 					    ENTER_FASTRECOVERY(tp);
1038 					tp->snd_nxt = tp->snd_max;
1039 					tp->t_badrxtwin = 0;
1040 				}
1041 
1042 				/*
1043 				 * Recalculate the transmit timer / rtt.
1044 				 *
1045 				 * Some boxes send broken timestamp replies
1046 				 * during the SYN+ACK phase, ignore
1047 				 * timestamps of 0 or we could calculate a
1048 				 * huge RTT and blow up the retransmit timer.
1049 				 */
1050 				if ((to.to_flags & TOF_TS) != 0 &&
1051 				    to.to_tsecr) {
1052 					if (!tp->t_rttlow ||
1053 					    tp->t_rttlow > ticks - to.to_tsecr)
1054 						tp->t_rttlow = ticks - to.to_tsecr;
1055 					tcp_xmit_timer(tp,
1056 					    ticks - to.to_tsecr + 1);
1057 				} else if (tp->t_rtttime &&
1058 				    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1059 					if (!tp->t_rttlow ||
1060 					    tp->t_rttlow > ticks - tp->t_rtttime)
1061 						tp->t_rttlow = ticks - tp->t_rtttime;
1062 					tcp_xmit_timer(tp,
1063 							ticks - tp->t_rtttime);
1064 				}
1065 				tcp_xmit_bandwidth_limit(tp, th->th_ack);
1066 				acked = th->th_ack - tp->snd_una;
1067 				tcpstat.tcps_rcvackpack++;
1068 				tcpstat.tcps_rcvackbyte += acked;
1069 				sbdrop(&so->so_snd, acked);
1070 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1071 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1072 					tp->snd_recover = th->th_ack - 1;
1073 				tp->snd_una = th->th_ack;
1074 				/*
1075 				 * Pull snd_wl2 up to prevent seq wrap relative
1076 				 * to th_ack.
1077 				 */
1078 				tp->snd_wl2 = th->th_ack;
1079 				tp->t_dupacks = 0;
1080 				m_freem(m);
1081 				ND6_HINT(tp); /* Some progress has been made. */
1082 
1083 				/*
1084 				 * If all outstanding data are acked, stop
1085 				 * retransmit timer, otherwise restart timer
1086 				 * using current (possibly backed-off) value.
1087 				 * If process is waiting for space,
1088 				 * wakeup/selwakeup/signal.  If data
1089 				 * are ready to send, let tcp_output
1090 				 * decide between more output or persist.
1091 				 */
1092 #ifdef TCPDEBUG
1093 				if (so->so_options & SO_DEBUG)
1094 					tcp_trace(TA_INPUT, ostate, tp,
1095 					    (void *)tcp_saveipgen,
1096 					    &tcp_savetcp, 0);
1097 #endif
1098 				if (tp->snd_una == tp->snd_max)
1099 					tcp_timer_activate(tp, TT_REXMT, 0);
1100 				else if (!tcp_timer_active(tp, TT_PERSIST))
1101 					tcp_timer_activate(tp, TT_REXMT,
1102 						      tp->t_rxtcur);
1103 				/*
1104 				 * NB: sowwakeup_locked() does an
1105 				 * implicit unlock.
1106 				 */
1107 				sowwakeup(so);
1108 				if (so->so_snd.sb_cc)
1109 					(void) tcp_output(tp);
1110 				goto check_delack;
1111 			}
1112 		} else if (th->th_ack == tp->snd_una &&
1113 		    tlen <= sbspace(&so->so_rcv)) {
1114 			int newsize = 0;	/* automatic sockbuf scaling */
1115 
1116 			KASSERT(headlocked, ("%s: headlocked", __func__));
1117 			INP_INFO_WUNLOCK(&tcbinfo);
1118 			headlocked = 0;
1119 			/*
1120 			 * This is a pure, in-sequence data packet
1121 			 * with nothing on the reassembly queue and
1122 			 * we have enough buffer space to take it.
1123 			 */
1124 			/* Clean receiver SACK report if present */
1125 			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1126 				tcp_clean_sackreport(tp);
1127 			++tcpstat.tcps_preddat;
1128 			tp->rcv_nxt += tlen;
1129 			/*
1130 			 * Pull snd_wl1 up to prevent seq wrap relative to
1131 			 * th_seq.
1132 			 */
1133 			tp->snd_wl1 = th->th_seq;
1134 			/*
1135 			 * Pull rcv_up up to prevent seq wrap relative to
1136 			 * rcv_nxt.
1137 			 */
1138 			tp->rcv_up = tp->rcv_nxt;
1139 			tcpstat.tcps_rcvpack++;
1140 			tcpstat.tcps_rcvbyte += tlen;
1141 			ND6_HINT(tp);	/* Some progress has been made */
1142 #ifdef TCPDEBUG
1143 			if (so->so_options & SO_DEBUG)
1144 				tcp_trace(TA_INPUT, ostate, tp,
1145 				    (void *)tcp_saveipgen, &tcp_savetcp, 0);
1146 #endif
1147 		/*
1148 		 * Automatic sizing of receive socket buffer.  Often the send
1149 		 * buffer size is not optimally adjusted to the actual network
1150 		 * conditions at hand (delay bandwidth product).  Setting the
1151 		 * buffer size too small limits throughput on links with high
1152 		 * bandwidth and high delay (eg. trans-continental/oceanic links).
1153 		 *
1154 		 * On the receive side the socket buffer memory is only rarely
1155 		 * used to any significant extent.  This allows us to be much
1156 		 * more aggressive in scaling the receive socket buffer.  For
1157 		 * the case that the buffer space is actually used to a large
1158 		 * extent and we run out of kernel memory we can simply drop
1159 		 * the new segments; TCP on the sender will just retransmit it
1160 		 * later.  Setting the buffer size too big may only consume too
1161 		 * much kernel memory if the application doesn't read() from
1162 		 * the socket or packet loss or reordering makes use of the
1163 		 * reassembly queue.
1164 		 *
1165 		 * The criteria to step up the receive buffer one notch are:
1166 		 *  1. the number of bytes received during the time it takes
1167 		 *     one timestamp to be reflected back to us (the RTT);
1168 		 *  2. received bytes per RTT is within seven eighth of the
1169 		 *     current socket buffer size;
1170 		 *  3. receive buffer size has not hit maximal automatic size;
1171 		 *
1172 		 * This algorithm does one step per RTT at most and only if
1173 		 * we receive a bulk stream w/o packet losses or reorderings.
1174 		 * Shrinking the buffer during idle times is not necessary as
1175 		 * it doesn't consume any memory when idle.
1176 		 *
1177 		 * TODO: Only step up if the application is actually serving
1178 		 * the buffer to better manage the socket buffer resources.
1179 		 */
1180 			if (tcp_do_autorcvbuf &&
1181 			    to.to_tsecr &&
1182 			    (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1183 				if (to.to_tsecr > tp->rfbuf_ts &&
1184 				    to.to_tsecr - tp->rfbuf_ts < hz) {
1185 					if (tp->rfbuf_cnt >
1186 					    (so->so_rcv.sb_hiwat / 8 * 7) &&
1187 					    so->so_rcv.sb_hiwat <
1188 					    tcp_autorcvbuf_max) {
1189 						newsize =
1190 						    min(so->so_rcv.sb_hiwat +
1191 						    tcp_autorcvbuf_inc,
1192 						    tcp_autorcvbuf_max);
1193 					}
1194 					/* Start over with next RTT. */
1195 					tp->rfbuf_ts = 0;
1196 					tp->rfbuf_cnt = 0;
1197 				} else
1198 					tp->rfbuf_cnt += tlen;	/* add up */
1199 			}
1200 
1201 			/* Add data to socket buffer. */
1202 			SOCKBUF_LOCK(&so->so_rcv);
1203 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1204 				m_freem(m);
1205 			} else {
1206 				/*
1207 				 * Set new socket buffer size.
1208 				 * Give up when limit is reached.
1209 				 */
1210 				if (newsize)
1211 					if (!sbreserve_locked(&so->so_rcv,
1212 					    newsize, so, curthread))
1213 						so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1214 				m_adj(m, drop_hdrlen);	/* delayed header drop */
1215 				sbappendstream_locked(&so->so_rcv, m);
1216 			}
1217 			/* NB: sorwakeup_locked() does an implicit unlock. */
1218 			sorwakeup_locked(so);
1219 			if (DELAY_ACK(tp)) {
1220 				tp->t_flags |= TF_DELACK;
1221 			} else {
1222 				tp->t_flags |= TF_ACKNOW;
1223 				tcp_output(tp);
1224 			}
1225 			goto check_delack;
1226 		}
1227 	}
1228 
1229 	/*
1230 	 * Calculate amount of space in receive window,
1231 	 * and then do TCP input processing.
1232 	 * Receive window is amount of space in rcv queue,
1233 	 * but not less than advertised window.
1234 	 */
1235 	win = sbspace(&so->so_rcv);
1236 	if (win < 0)
1237 		win = 0;
1238 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1239 
1240 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
1241 	tp->rfbuf_ts = 0;
1242 	tp->rfbuf_cnt = 0;
1243 
1244 	switch (tp->t_state) {
1245 
1246 	/*
1247 	 * If the state is SYN_RECEIVED:
1248 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1249 	 */
1250 	case TCPS_SYN_RECEIVED:
1251 		if ((thflags & TH_ACK) &&
1252 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1253 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1254 				rstreason = BANDLIM_RST_OPENPORT;
1255 				goto dropwithreset;
1256 		}
1257 		break;
1258 
1259 	/*
1260 	 * If the state is SYN_SENT:
1261 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1262 	 *	if seg contains a RST, then drop the connection.
1263 	 *	if seg does not contain SYN, then drop it.
1264 	 * Otherwise this is an acceptable SYN segment
1265 	 *	initialize tp->rcv_nxt and tp->irs
1266 	 *	if seg contains ack then advance tp->snd_una
1267 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1268 	 *	arrange for segment to be acked (eventually)
1269 	 *	continue processing rest of data/controls, beginning with URG
1270 	 */
1271 	case TCPS_SYN_SENT:
1272 		if ((thflags & TH_ACK) &&
1273 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1274 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1275 			rstreason = BANDLIM_UNLIMITED;
1276 			goto dropwithreset;
1277 		}
1278 		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1279 			tp = tcp_drop(tp, ECONNREFUSED);
1280 		if (thflags & TH_RST)
1281 			goto drop;
1282 		if (!(thflags & TH_SYN))
1283 			goto drop;
1284 
1285 		tp->irs = th->th_seq;
1286 		tcp_rcvseqinit(tp);
1287 		if (thflags & TH_ACK) {
1288 			tcpstat.tcps_connects++;
1289 			soisconnected(so);
1290 #ifdef MAC
1291 			SOCK_LOCK(so);
1292 			mac_set_socket_peer_from_mbuf(m, so);
1293 			SOCK_UNLOCK(so);
1294 #endif
1295 			/* Do window scaling on this connection? */
1296 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1297 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1298 				tp->rcv_scale = tp->request_r_scale;
1299 			}
1300 			tp->rcv_adv += tp->rcv_wnd;
1301 			tp->snd_una++;		/* SYN is acked */
1302 			/*
1303 			 * If there's data, delay ACK; if there's also a FIN
1304 			 * ACKNOW will be turned on later.
1305 			 */
1306 			if (DELAY_ACK(tp) && tlen != 0)
1307 				tcp_timer_activate(tp, TT_DELACK,
1308 				    tcp_delacktime);
1309 			else
1310 				tp->t_flags |= TF_ACKNOW;
1311 			/*
1312 			 * Received <SYN,ACK> in SYN_SENT[*] state.
1313 			 * Transitions:
1314 			 *	SYN_SENT  --> ESTABLISHED
1315 			 *	SYN_SENT* --> FIN_WAIT_1
1316 			 */
1317 			tp->t_starttime = ticks;
1318 			if (tp->t_flags & TF_NEEDFIN) {
1319 				tp->t_state = TCPS_FIN_WAIT_1;
1320 				tp->t_flags &= ~TF_NEEDFIN;
1321 				thflags &= ~TH_SYN;
1322 			} else {
1323 				tp->t_state = TCPS_ESTABLISHED;
1324 				tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1325 			}
1326 		} else {
1327 			/*
1328 			 * Received initial SYN in SYN-SENT[*] state =>
1329 			 * simultaneous open.  If segment contains CC option
1330 			 * and there is a cached CC, apply TAO test.
1331 			 * If it succeeds, connection is * half-synchronized.
1332 			 * Otherwise, do 3-way handshake:
1333 			 *        SYN-SENT -> SYN-RECEIVED
1334 			 *        SYN-SENT* -> SYN-RECEIVED*
1335 			 * If there was no CC option, clear cached CC value.
1336 			 */
1337 			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1338 			tcp_timer_activate(tp, TT_REXMT, 0);
1339 			tp->t_state = TCPS_SYN_RECEIVED;
1340 		}
1341 
1342 		KASSERT(headlocked, ("%s: trimthenstep6: head not locked",
1343 		    __func__));
1344 		INP_LOCK_ASSERT(tp->t_inpcb);
1345 
1346 		/*
1347 		 * Advance th->th_seq to correspond to first data byte.
1348 		 * If data, trim to stay within window,
1349 		 * dropping FIN if necessary.
1350 		 */
1351 		th->th_seq++;
1352 		if (tlen > tp->rcv_wnd) {
1353 			todrop = tlen - tp->rcv_wnd;
1354 			m_adj(m, -todrop);
1355 			tlen = tp->rcv_wnd;
1356 			thflags &= ~TH_FIN;
1357 			tcpstat.tcps_rcvpackafterwin++;
1358 			tcpstat.tcps_rcvbyteafterwin += todrop;
1359 		}
1360 		tp->snd_wl1 = th->th_seq - 1;
1361 		tp->rcv_up = th->th_seq;
1362 		/*
1363 		 * Client side of transaction: already sent SYN and data.
1364 		 * If the remote host used T/TCP to validate the SYN,
1365 		 * our data will be ACK'd; if so, enter normal data segment
1366 		 * processing in the middle of step 5, ack processing.
1367 		 * Otherwise, goto step 6.
1368 		 */
1369 		if (thflags & TH_ACK)
1370 			goto process_ACK;
1371 
1372 		goto step6;
1373 
1374 	/*
1375 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1376 	 *      do normal processing.
1377 	 *
1378 	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
1379 	 */
1380 	case TCPS_LAST_ACK:
1381 	case TCPS_CLOSING:
1382 		break;  /* continue normal processing */
1383 	}
1384 
1385 	/*
1386 	 * States other than LISTEN or SYN_SENT.
1387 	 * First check the RST flag and sequence number since reset segments
1388 	 * are exempt from the timestamp and connection count tests.  This
1389 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1390 	 * below which allowed reset segments in half the sequence space
1391 	 * to fall though and be processed (which gives forged reset
1392 	 * segments with a random sequence number a 50 percent chance of
1393 	 * killing a connection).
1394 	 * Then check timestamp, if present.
1395 	 * Then check the connection count, if present.
1396 	 * Then check that at least some bytes of segment are within
1397 	 * receive window.  If segment begins before rcv_nxt,
1398 	 * drop leading data (and SYN); if nothing left, just ack.
1399 	 *
1400 	 *
1401 	 * If the RST bit is set, check the sequence number to see
1402 	 * if this is a valid reset segment.
1403 	 * RFC 793 page 37:
1404 	 *   In all states except SYN-SENT, all reset (RST) segments
1405 	 *   are validated by checking their SEQ-fields.  A reset is
1406 	 *   valid if its sequence number is in the window.
1407 	 * Note: this does not take into account delayed ACKs, so
1408 	 *   we should test against last_ack_sent instead of rcv_nxt.
1409 	 *   The sequence number in the reset segment is normally an
1410 	 *   echo of our outgoing acknowlegement numbers, but some hosts
1411 	 *   send a reset with the sequence number at the rightmost edge
1412 	 *   of our receive window, and we have to handle this case.
1413 	 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1414 	 *   that brute force RST attacks are possible.  To combat this,
1415 	 *   we use a much stricter check while in the ESTABLISHED state,
1416 	 *   only accepting RSTs where the sequence number is equal to
1417 	 *   last_ack_sent.  In all other states (the states in which a
1418 	 *   RST is more likely), the more permissive check is used.
1419 	 * If we have multiple segments in flight, the intial reset
1420 	 * segment sequence numbers will be to the left of last_ack_sent,
1421 	 * but they will eventually catch up.
1422 	 * In any case, it never made sense to trim reset segments to
1423 	 * fit the receive window since RFC 1122 says:
1424 	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1425 	 *
1426 	 *    A TCP SHOULD allow a received RST segment to include data.
1427 	 *
1428 	 *    DISCUSSION
1429 	 *         It has been suggested that a RST segment could contain
1430 	 *         ASCII text that encoded and explained the cause of the
1431 	 *         RST.  No standard has yet been established for such
1432 	 *         data.
1433 	 *
1434 	 * If the reset segment passes the sequence number test examine
1435 	 * the state:
1436 	 *    SYN_RECEIVED STATE:
1437 	 *	If passive open, return to LISTEN state.
1438 	 *	If active open, inform user that connection was refused.
1439 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1440 	 *	Inform user that connection was reset, and close tcb.
1441 	 *    CLOSING, LAST_ACK STATES:
1442 	 *	Close the tcb.
1443 	 *    TIME_WAIT STATE:
1444 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1445 	 *      RFC 1337.
1446 	 */
1447 	if (thflags & TH_RST) {
1448 		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1449 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1450 			switch (tp->t_state) {
1451 
1452 			case TCPS_SYN_RECEIVED:
1453 				so->so_error = ECONNREFUSED;
1454 				goto close;
1455 
1456 			case TCPS_ESTABLISHED:
1457 				if (tcp_insecure_rst == 0 &&
1458 				    !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1459 				    SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1460 				    !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1461 				    SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1462 					tcpstat.tcps_badrst++;
1463 					goto drop;
1464 				}
1465 			case TCPS_FIN_WAIT_1:
1466 			case TCPS_FIN_WAIT_2:
1467 			case TCPS_CLOSE_WAIT:
1468 				so->so_error = ECONNRESET;
1469 			close:
1470 				tp->t_state = TCPS_CLOSED;
1471 				tcpstat.tcps_drops++;
1472 				KASSERT(headlocked, ("%s: trimthenstep6: "
1473 				    "tcp_close: head not locked", __func__));
1474 				tp = tcp_close(tp);
1475 				break;
1476 
1477 			case TCPS_CLOSING:
1478 			case TCPS_LAST_ACK:
1479 				KASSERT(headlocked, ("%s: trimthenstep6: "
1480 				    "tcp_close.2: head not locked", __func__));
1481 				tp = tcp_close(tp);
1482 				break;
1483 			}
1484 		}
1485 		goto drop;
1486 	}
1487 
1488 	/*
1489 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1490 	 * and it's less than ts_recent, drop it.
1491 	 */
1492 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1493 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1494 
1495 		/* Check to see if ts_recent is over 24 days old.  */
1496 		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1497 			/*
1498 			 * Invalidate ts_recent.  If this segment updates
1499 			 * ts_recent, the age will be reset later and ts_recent
1500 			 * will get a valid value.  If it does not, setting
1501 			 * ts_recent to zero will at least satisfy the
1502 			 * requirement that zero be placed in the timestamp
1503 			 * echo reply when ts_recent isn't valid.  The
1504 			 * age isn't reset until we get a valid ts_recent
1505 			 * because we don't want out-of-order segments to be
1506 			 * dropped when ts_recent is old.
1507 			 */
1508 			tp->ts_recent = 0;
1509 		} else {
1510 			tcpstat.tcps_rcvduppack++;
1511 			tcpstat.tcps_rcvdupbyte += tlen;
1512 			tcpstat.tcps_pawsdrop++;
1513 			if (tlen)
1514 				goto dropafterack;
1515 			goto drop;
1516 		}
1517 	}
1518 
1519 	/*
1520 	 * In the SYN-RECEIVED state, validate that the packet belongs to
1521 	 * this connection before trimming the data to fit the receive
1522 	 * window.  Check the sequence number versus IRS since we know
1523 	 * the sequence numbers haven't wrapped.  This is a partial fix
1524 	 * for the "LAND" DoS attack.
1525 	 */
1526 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1527 		rstreason = BANDLIM_RST_OPENPORT;
1528 		goto dropwithreset;
1529 	}
1530 
1531 	todrop = tp->rcv_nxt - th->th_seq;
1532 	if (todrop > 0) {
1533 		if (thflags & TH_SYN) {
1534 			thflags &= ~TH_SYN;
1535 			th->th_seq++;
1536 			if (th->th_urp > 1)
1537 				th->th_urp--;
1538 			else
1539 				thflags &= ~TH_URG;
1540 			todrop--;
1541 		}
1542 		/*
1543 		 * Following if statement from Stevens, vol. 2, p. 960.
1544 		 */
1545 		if (todrop > tlen
1546 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1547 			/*
1548 			 * Any valid FIN must be to the left of the window.
1549 			 * At this point the FIN must be a duplicate or out
1550 			 * of sequence; drop it.
1551 			 */
1552 			thflags &= ~TH_FIN;
1553 
1554 			/*
1555 			 * Send an ACK to resynchronize and drop any data.
1556 			 * But keep on processing for RST or ACK.
1557 			 */
1558 			tp->t_flags |= TF_ACKNOW;
1559 			todrop = tlen;
1560 			tcpstat.tcps_rcvduppack++;
1561 			tcpstat.tcps_rcvdupbyte += todrop;
1562 		} else {
1563 			tcpstat.tcps_rcvpartduppack++;
1564 			tcpstat.tcps_rcvpartdupbyte += todrop;
1565 		}
1566 		drop_hdrlen += todrop;	/* drop from the top afterwards */
1567 		th->th_seq += todrop;
1568 		tlen -= todrop;
1569 		if (th->th_urp > todrop)
1570 			th->th_urp -= todrop;
1571 		else {
1572 			thflags &= ~TH_URG;
1573 			th->th_urp = 0;
1574 		}
1575 	}
1576 
1577 	/*
1578 	 * If new data are received on a connection after the
1579 	 * user processes are gone, then RST the other end.
1580 	 */
1581 	if ((so->so_state & SS_NOFDREF) &&
1582 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1583 		KASSERT(headlocked, ("%s: trimthenstep6: tcp_close.3: head "
1584 		    "not locked", __func__));
1585 		tp = tcp_close(tp);
1586 		tcpstat.tcps_rcvafterclose++;
1587 		rstreason = BANDLIM_UNLIMITED;
1588 		goto dropwithreset;
1589 	}
1590 
1591 	/*
1592 	 * If segment ends after window, drop trailing data
1593 	 * (and PUSH and FIN); if nothing left, just ACK.
1594 	 */
1595 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1596 	if (todrop > 0) {
1597 		tcpstat.tcps_rcvpackafterwin++;
1598 		if (todrop >= tlen) {
1599 			tcpstat.tcps_rcvbyteafterwin += tlen;
1600 			/*
1601 			 * If window is closed can only take segments at
1602 			 * window edge, and have to drop data and PUSH from
1603 			 * incoming segments.  Continue processing, but
1604 			 * remember to ack.  Otherwise, drop segment
1605 			 * and ack.
1606 			 */
1607 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1608 				tp->t_flags |= TF_ACKNOW;
1609 				tcpstat.tcps_rcvwinprobe++;
1610 			} else
1611 				goto dropafterack;
1612 		} else
1613 			tcpstat.tcps_rcvbyteafterwin += todrop;
1614 		m_adj(m, -todrop);
1615 		tlen -= todrop;
1616 		thflags &= ~(TH_PUSH|TH_FIN);
1617 	}
1618 
1619 	/*
1620 	 * If last ACK falls within this segment's sequence numbers,
1621 	 * record its timestamp.
1622 	 * NOTE:
1623 	 * 1) That the test incorporates suggestions from the latest
1624 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
1625 	 * 2) That updating only on newer timestamps interferes with
1626 	 *    our earlier PAWS tests, so this check should be solely
1627 	 *    predicated on the sequence space of this segment.
1628 	 * 3) That we modify the segment boundary check to be
1629 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
1630 	 *    instead of RFC1323's
1631 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
1632 	 *    This modified check allows us to overcome RFC1323's
1633 	 *    limitations as described in Stevens TCP/IP Illustrated
1634 	 *    Vol. 2 p.869. In such cases, we can still calculate the
1635 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
1636 	 */
1637 	if ((to.to_flags & TOF_TS) != 0 &&
1638 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1639 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1640 		((thflags & (TH_SYN|TH_FIN)) != 0))) {
1641 		tp->ts_recent_age = ticks;
1642 		tp->ts_recent = to.to_tsval;
1643 	}
1644 
1645 	/*
1646 	 * If a SYN is in the window, then this is an
1647 	 * error and we send an RST and drop the connection.
1648 	 */
1649 	if (thflags & TH_SYN) {
1650 		KASSERT(headlocked, ("%s: tcp_drop: trimthenstep6: "
1651 		    "head not locked", __func__));
1652 		tp = tcp_drop(tp, ECONNRESET);
1653 		rstreason = BANDLIM_UNLIMITED;
1654 		goto drop;
1655 	}
1656 
1657 	/*
1658 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1659 	 * flag is on (half-synchronized state), then queue data for
1660 	 * later processing; else drop segment and return.
1661 	 */
1662 	if ((thflags & TH_ACK) == 0) {
1663 		if (tp->t_state == TCPS_SYN_RECEIVED ||
1664 		    (tp->t_flags & TF_NEEDSYN))
1665 			goto step6;
1666 		else if (tp->t_flags & TF_ACKNOW)
1667 			goto dropafterack;
1668 		else
1669 			goto drop;
1670 	}
1671 
1672 	/*
1673 	 * Ack processing.
1674 	 */
1675 	switch (tp->t_state) {
1676 
1677 	/*
1678 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1679 	 * ESTABLISHED state and continue processing.
1680 	 * The ACK was checked above.
1681 	 */
1682 	case TCPS_SYN_RECEIVED:
1683 
1684 		tcpstat.tcps_connects++;
1685 		soisconnected(so);
1686 		/* Do window scaling? */
1687 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1688 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1689 			tp->rcv_scale = tp->request_r_scale;
1690 			tp->snd_wnd = tiwin;
1691 		}
1692 		/*
1693 		 * Make transitions:
1694 		 *      SYN-RECEIVED  -> ESTABLISHED
1695 		 *      SYN-RECEIVED* -> FIN-WAIT-1
1696 		 */
1697 		tp->t_starttime = ticks;
1698 		if (tp->t_flags & TF_NEEDFIN) {
1699 			tp->t_state = TCPS_FIN_WAIT_1;
1700 			tp->t_flags &= ~TF_NEEDFIN;
1701 		} else {
1702 			tp->t_state = TCPS_ESTABLISHED;
1703 			tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1704 		}
1705 		/*
1706 		 * If segment contains data or ACK, will call tcp_reass()
1707 		 * later; if not, do so now to pass queued data to user.
1708 		 */
1709 		if (tlen == 0 && (thflags & TH_FIN) == 0)
1710 			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1711 			    (struct mbuf *)0);
1712 		tp->snd_wl1 = th->th_seq - 1;
1713 		/* FALLTHROUGH */
1714 
1715 	/*
1716 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1717 	 * ACKs.  If the ack is in the range
1718 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1719 	 * then advance tp->snd_una to th->th_ack and drop
1720 	 * data from the retransmission queue.  If this ACK reflects
1721 	 * more up to date window information we update our window information.
1722 	 */
1723 	case TCPS_ESTABLISHED:
1724 	case TCPS_FIN_WAIT_1:
1725 	case TCPS_FIN_WAIT_2:
1726 	case TCPS_CLOSE_WAIT:
1727 	case TCPS_CLOSING:
1728 	case TCPS_LAST_ACK:
1729 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1730 			tcpstat.tcps_rcvacktoomuch++;
1731 			goto dropafterack;
1732 		}
1733 		if ((tp->t_flags & TF_SACK_PERMIT) &&
1734 		    ((to.to_flags & TOF_SACK) ||
1735 		     !TAILQ_EMPTY(&tp->snd_holes)))
1736 			tcp_sack_doack(tp, &to, th->th_ack);
1737 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1738 			if (tlen == 0 && tiwin == tp->snd_wnd) {
1739 				tcpstat.tcps_rcvdupack++;
1740 				/*
1741 				 * If we have outstanding data (other than
1742 				 * a window probe), this is a completely
1743 				 * duplicate ack (ie, window info didn't
1744 				 * change), the ack is the biggest we've
1745 				 * seen and we've seen exactly our rexmt
1746 				 * threshhold of them, assume a packet
1747 				 * has been dropped and retransmit it.
1748 				 * Kludge snd_nxt & the congestion
1749 				 * window so we send only this one
1750 				 * packet.
1751 				 *
1752 				 * We know we're losing at the current
1753 				 * window size so do congestion avoidance
1754 				 * (set ssthresh to half the current window
1755 				 * and pull our congestion window back to
1756 				 * the new ssthresh).
1757 				 *
1758 				 * Dup acks mean that packets have left the
1759 				 * network (they're now cached at the receiver)
1760 				 * so bump cwnd by the amount in the receiver
1761 				 * to keep a constant cwnd packets in the
1762 				 * network.
1763 				 */
1764 				if (!tcp_timer_active(tp, TT_REXMT) ||
1765 				    th->th_ack != tp->snd_una)
1766 					tp->t_dupacks = 0;
1767 				else if (++tp->t_dupacks > tcprexmtthresh ||
1768 				    ((tcp_do_newreno ||
1769 				      (tp->t_flags & TF_SACK_PERMIT)) &&
1770 				     IN_FASTRECOVERY(tp))) {
1771 					if ((tp->t_flags & TF_SACK_PERMIT) &&
1772 					    IN_FASTRECOVERY(tp)) {
1773 						int awnd;
1774 
1775 						/*
1776 						 * Compute the amount of data in flight first.
1777 						 * We can inject new data into the pipe iff
1778 						 * we have less than 1/2 the original window's
1779 						 * worth of data in flight.
1780 						 */
1781 						awnd = (tp->snd_nxt - tp->snd_fack) +
1782 							tp->sackhint.sack_bytes_rexmit;
1783 						if (awnd < tp->snd_ssthresh) {
1784 							tp->snd_cwnd += tp->t_maxseg;
1785 							if (tp->snd_cwnd > tp->snd_ssthresh)
1786 								tp->snd_cwnd = tp->snd_ssthresh;
1787 						}
1788 					} else
1789 						tp->snd_cwnd += tp->t_maxseg;
1790 					(void) tcp_output(tp);
1791 					goto drop;
1792 				} else if (tp->t_dupacks == tcprexmtthresh) {
1793 					tcp_seq onxt = tp->snd_nxt;
1794 					u_int win;
1795 
1796 					/*
1797 					 * If we're doing sack, check to
1798 					 * see if we're already in sack
1799 					 * recovery. If we're not doing sack,
1800 					 * check to see if we're in newreno
1801 					 * recovery.
1802 					 */
1803 					if (tp->t_flags & TF_SACK_PERMIT) {
1804 						if (IN_FASTRECOVERY(tp)) {
1805 							tp->t_dupacks = 0;
1806 							break;
1807 						}
1808 					} else if (tcp_do_newreno) {
1809 						if (SEQ_LEQ(th->th_ack,
1810 						    tp->snd_recover)) {
1811 							tp->t_dupacks = 0;
1812 							break;
1813 						}
1814 					}
1815 					win = min(tp->snd_wnd, tp->snd_cwnd) /
1816 					    2 / tp->t_maxseg;
1817 					if (win < 2)
1818 						win = 2;
1819 					tp->snd_ssthresh = win * tp->t_maxseg;
1820 					ENTER_FASTRECOVERY(tp);
1821 					tp->snd_recover = tp->snd_max;
1822 					tcp_timer_activate(tp, TT_REXMT, 0);
1823 					tp->t_rtttime = 0;
1824 					if (tp->t_flags & TF_SACK_PERMIT) {
1825 						tcpstat.tcps_sack_recovery_episode++;
1826 						tp->sack_newdata = tp->snd_nxt;
1827 						tp->snd_cwnd = tp->t_maxseg;
1828 						(void) tcp_output(tp);
1829 						goto drop;
1830 					}
1831 					tp->snd_nxt = th->th_ack;
1832 					tp->snd_cwnd = tp->t_maxseg;
1833 					(void) tcp_output(tp);
1834 					KASSERT(tp->snd_limited <= 2,
1835 					    ("%s: tp->snd_limited too big",
1836 					    __func__));
1837 					tp->snd_cwnd = tp->snd_ssthresh +
1838 					     tp->t_maxseg *
1839 					     (tp->t_dupacks - tp->snd_limited);
1840 					if (SEQ_GT(onxt, tp->snd_nxt))
1841 						tp->snd_nxt = onxt;
1842 					goto drop;
1843 				} else if (tcp_do_rfc3042) {
1844 					u_long oldcwnd = tp->snd_cwnd;
1845 					tcp_seq oldsndmax = tp->snd_max;
1846 					u_int sent;
1847 
1848 					KASSERT(tp->t_dupacks == 1 ||
1849 					    tp->t_dupacks == 2,
1850 					    ("%s: dupacks not 1 or 2",
1851 					    __func__));
1852 					if (tp->t_dupacks == 1)
1853 						tp->snd_limited = 0;
1854 					tp->snd_cwnd =
1855 					    (tp->snd_nxt - tp->snd_una) +
1856 					    (tp->t_dupacks - tp->snd_limited) *
1857 					    tp->t_maxseg;
1858 					(void) tcp_output(tp);
1859 					sent = tp->snd_max - oldsndmax;
1860 					if (sent > tp->t_maxseg) {
1861 						KASSERT((tp->t_dupacks == 2 &&
1862 						    tp->snd_limited == 0) ||
1863 						   (sent == tp->t_maxseg + 1 &&
1864 						    tp->t_flags & TF_SENTFIN),
1865 						    ("%s: sent too much",
1866 						    __func__));
1867 						tp->snd_limited = 2;
1868 					} else if (sent > 0)
1869 						++tp->snd_limited;
1870 					tp->snd_cwnd = oldcwnd;
1871 					goto drop;
1872 				}
1873 			} else
1874 				tp->t_dupacks = 0;
1875 			break;
1876 		}
1877 
1878 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
1879 		    ("%s: th_ack <= snd_una", __func__));
1880 
1881 		/*
1882 		 * If the congestion window was inflated to account
1883 		 * for the other side's cached packets, retract it.
1884 		 */
1885 		if (tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
1886 			if (IN_FASTRECOVERY(tp)) {
1887 				if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1888 					if (tp->t_flags & TF_SACK_PERMIT)
1889 						tcp_sack_partialack(tp, th);
1890 					else
1891 						tcp_newreno_partial_ack(tp, th);
1892 				} else {
1893 					/*
1894 					 * Out of fast recovery.
1895 					 * Window inflation should have left us
1896 					 * with approximately snd_ssthresh
1897 					 * outstanding data.
1898 					 * But in case we would be inclined to
1899 					 * send a burst, better to do it via
1900 					 * the slow start mechanism.
1901 					 */
1902 					if (SEQ_GT(th->th_ack +
1903 							tp->snd_ssthresh,
1904 						   tp->snd_max))
1905 						tp->snd_cwnd = tp->snd_max -
1906 								th->th_ack +
1907 								tp->t_maxseg;
1908 					else
1909 						tp->snd_cwnd = tp->snd_ssthresh;
1910 				}
1911 			}
1912 		} else {
1913 			if (tp->t_dupacks >= tcprexmtthresh &&
1914 			    tp->snd_cwnd > tp->snd_ssthresh)
1915 				tp->snd_cwnd = tp->snd_ssthresh;
1916 		}
1917 		tp->t_dupacks = 0;
1918 		/*
1919 		 * If we reach this point, ACK is not a duplicate,
1920 		 *     i.e., it ACKs something we sent.
1921 		 */
1922 		if (tp->t_flags & TF_NEEDSYN) {
1923 			/*
1924 			 * T/TCP: Connection was half-synchronized, and our
1925 			 * SYN has been ACK'd (so connection is now fully
1926 			 * synchronized).  Go to non-starred state,
1927 			 * increment snd_una for ACK of SYN, and check if
1928 			 * we can do window scaling.
1929 			 */
1930 			tp->t_flags &= ~TF_NEEDSYN;
1931 			tp->snd_una++;
1932 			/* Do window scaling? */
1933 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1934 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1935 				tp->rcv_scale = tp->request_r_scale;
1936 				/* Send window already scaled. */
1937 			}
1938 		}
1939 
1940 process_ACK:
1941 		KASSERT(headlocked, ("%s: process_ACK: head not locked",
1942 		    __func__));
1943 		INP_LOCK_ASSERT(tp->t_inpcb);
1944 
1945 		acked = th->th_ack - tp->snd_una;
1946 		tcpstat.tcps_rcvackpack++;
1947 		tcpstat.tcps_rcvackbyte += acked;
1948 
1949 		/*
1950 		 * If we just performed our first retransmit, and the ACK
1951 		 * arrives within our recovery window, then it was a mistake
1952 		 * to do the retransmit in the first place.  Recover our
1953 		 * original cwnd and ssthresh, and proceed to transmit where
1954 		 * we left off.
1955 		 */
1956 		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1957 			++tcpstat.tcps_sndrexmitbad;
1958 			tp->snd_cwnd = tp->snd_cwnd_prev;
1959 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
1960 			tp->snd_recover = tp->snd_recover_prev;
1961 			if (tp->t_flags & TF_WASFRECOVERY)
1962 				ENTER_FASTRECOVERY(tp);
1963 			tp->snd_nxt = tp->snd_max;
1964 			tp->t_badrxtwin = 0;	/* XXX probably not required */
1965 		}
1966 
1967 		/*
1968 		 * If we have a timestamp reply, update smoothed
1969 		 * round trip time.  If no timestamp is present but
1970 		 * transmit timer is running and timed sequence
1971 		 * number was acked, update smoothed round trip time.
1972 		 * Since we now have an rtt measurement, cancel the
1973 		 * timer backoff (cf., Phil Karn's retransmit alg.).
1974 		 * Recompute the initial retransmit timer.
1975 		 *
1976 		 * Some boxes send broken timestamp replies
1977 		 * during the SYN+ACK phase, ignore
1978 		 * timestamps of 0 or we could calculate a
1979 		 * huge RTT and blow up the retransmit timer.
1980 		 */
1981 		if ((to.to_flags & TOF_TS) != 0 &&
1982 		    to.to_tsecr) {
1983 			if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
1984 				tp->t_rttlow = ticks - to.to_tsecr;
1985 			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1986 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1987 			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
1988 				tp->t_rttlow = ticks - tp->t_rtttime;
1989 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1990 		}
1991 		tcp_xmit_bandwidth_limit(tp, th->th_ack);
1992 
1993 		/*
1994 		 * If all outstanding data is acked, stop retransmit
1995 		 * timer and remember to restart (more output or persist).
1996 		 * If there is more data to be acked, restart retransmit
1997 		 * timer, using current (possibly backed-off) value.
1998 		 */
1999 		if (th->th_ack == tp->snd_max) {
2000 			tcp_timer_activate(tp, TT_REXMT, 0);
2001 			needoutput = 1;
2002 		} else if (!tcp_timer_active(tp, TT_PERSIST))
2003 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2004 
2005 		/*
2006 		 * If no data (only SYN) was ACK'd,
2007 		 *    skip rest of ACK processing.
2008 		 */
2009 		if (acked == 0)
2010 			goto step6;
2011 
2012 		/*
2013 		 * When new data is acked, open the congestion window.
2014 		 * If the window gives us less than ssthresh packets
2015 		 * in flight, open exponentially (maxseg per packet).
2016 		 * Otherwise open linearly: maxseg per window
2017 		 * (maxseg^2 / cwnd per packet).
2018 		 */
2019 		if ((!tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2020 		    !IN_FASTRECOVERY(tp)) {
2021 			u_int cw = tp->snd_cwnd;
2022 			u_int incr = tp->t_maxseg;
2023 			if (cw > tp->snd_ssthresh)
2024 				incr = incr * incr / cw;
2025 			tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2026 		}
2027 		SOCKBUF_LOCK(&so->so_snd);
2028 		if (acked > so->so_snd.sb_cc) {
2029 			tp->snd_wnd -= so->so_snd.sb_cc;
2030 			sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2031 			ourfinisacked = 1;
2032 		} else {
2033 			sbdrop_locked(&so->so_snd, acked);
2034 			tp->snd_wnd -= acked;
2035 			ourfinisacked = 0;
2036 		}
2037 		sowwakeup_locked(so);
2038 		/* Detect una wraparound. */
2039 		if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2040 		    !IN_FASTRECOVERY(tp) &&
2041 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
2042 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2043 			tp->snd_recover = th->th_ack - 1;
2044 		if ((tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2045 		    IN_FASTRECOVERY(tp) &&
2046 		    SEQ_GEQ(th->th_ack, tp->snd_recover))
2047 			EXIT_FASTRECOVERY(tp);
2048 		tp->snd_una = th->th_ack;
2049 		if (tp->t_flags & TF_SACK_PERMIT) {
2050 			if (SEQ_GT(tp->snd_una, tp->snd_recover))
2051 				tp->snd_recover = tp->snd_una;
2052 		}
2053 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2054 			tp->snd_nxt = tp->snd_una;
2055 
2056 		switch (tp->t_state) {
2057 
2058 		/*
2059 		 * In FIN_WAIT_1 STATE in addition to the processing
2060 		 * for the ESTABLISHED state if our FIN is now acknowledged
2061 		 * then enter FIN_WAIT_2.
2062 		 */
2063 		case TCPS_FIN_WAIT_1:
2064 			if (ourfinisacked) {
2065 				/*
2066 				 * If we can't receive any more
2067 				 * data, then closing user can proceed.
2068 				 * Starting the timer is contrary to the
2069 				 * specification, but if we don't get a FIN
2070 				 * we'll hang forever.
2071 				 *
2072 				 * XXXjl:
2073 				 * we should release the tp also, and use a
2074 				 * compressed state.
2075 				 */
2076 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2077 					int timeout;
2078 
2079 					soisdisconnected(so);
2080 					timeout = (tcp_fast_finwait2_recycle) ?
2081 						tcp_finwait2_timeout : tcp_maxidle;
2082 					tcp_timer_activate(tp, TT_2MSL, timeout);
2083 				}
2084 				tp->t_state = TCPS_FIN_WAIT_2;
2085 			}
2086 			break;
2087 
2088 		/*
2089 		 * In CLOSING STATE in addition to the processing for
2090 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2091 		 * then enter the TIME-WAIT state, otherwise ignore
2092 		 * the segment.
2093 		 */
2094 		case TCPS_CLOSING:
2095 			if (ourfinisacked) {
2096 				KASSERT(headlocked, ("%s: process_ACK: "
2097 				    "head not locked", __func__));
2098 				tcp_twstart(tp);
2099 				INP_INFO_WUNLOCK(&tcbinfo);
2100 				headlocked = 0;
2101 				m_freem(m);
2102 				return;
2103 			}
2104 			break;
2105 
2106 		/*
2107 		 * In LAST_ACK, we may still be waiting for data to drain
2108 		 * and/or to be acked, as well as for the ack of our FIN.
2109 		 * If our FIN is now acknowledged, delete the TCB,
2110 		 * enter the closed state and return.
2111 		 */
2112 		case TCPS_LAST_ACK:
2113 			if (ourfinisacked) {
2114 				KASSERT(headlocked, ("%s: process_ACK: "
2115 				    "tcp_close: head not locked", __func__));
2116 				tp = tcp_close(tp);
2117 				goto drop;
2118 			}
2119 			break;
2120 		}
2121 	}
2122 
2123 step6:
2124 	KASSERT(headlocked, ("%s: step6: head not locked", __func__));
2125 	INP_LOCK_ASSERT(tp->t_inpcb);
2126 
2127 	/*
2128 	 * Update window information.
2129 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2130 	 */
2131 	if ((thflags & TH_ACK) &&
2132 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2133 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2134 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2135 		/* keep track of pure window updates */
2136 		if (tlen == 0 &&
2137 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2138 			tcpstat.tcps_rcvwinupd++;
2139 		tp->snd_wnd = tiwin;
2140 		tp->snd_wl1 = th->th_seq;
2141 		tp->snd_wl2 = th->th_ack;
2142 		if (tp->snd_wnd > tp->max_sndwnd)
2143 			tp->max_sndwnd = tp->snd_wnd;
2144 		needoutput = 1;
2145 	}
2146 
2147 	/*
2148 	 * Process segments with URG.
2149 	 */
2150 	if ((thflags & TH_URG) && th->th_urp &&
2151 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2152 		/*
2153 		 * This is a kludge, but if we receive and accept
2154 		 * random urgent pointers, we'll crash in
2155 		 * soreceive.  It's hard to imagine someone
2156 		 * actually wanting to send this much urgent data.
2157 		 */
2158 		SOCKBUF_LOCK(&so->so_rcv);
2159 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2160 			th->th_urp = 0;			/* XXX */
2161 			thflags &= ~TH_URG;		/* XXX */
2162 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
2163 			goto dodata;			/* XXX */
2164 		}
2165 		/*
2166 		 * If this segment advances the known urgent pointer,
2167 		 * then mark the data stream.  This should not happen
2168 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2169 		 * a FIN has been received from the remote side.
2170 		 * In these states we ignore the URG.
2171 		 *
2172 		 * According to RFC961 (Assigned Protocols),
2173 		 * the urgent pointer points to the last octet
2174 		 * of urgent data.  We continue, however,
2175 		 * to consider it to indicate the first octet
2176 		 * of data past the urgent section as the original
2177 		 * spec states (in one of two places).
2178 		 */
2179 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2180 			tp->rcv_up = th->th_seq + th->th_urp;
2181 			so->so_oobmark = so->so_rcv.sb_cc +
2182 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2183 			if (so->so_oobmark == 0)
2184 				so->so_rcv.sb_state |= SBS_RCVATMARK;
2185 			sohasoutofband(so);
2186 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2187 		}
2188 		SOCKBUF_UNLOCK(&so->so_rcv);
2189 		/*
2190 		 * Remove out of band data so doesn't get presented to user.
2191 		 * This can happen independent of advancing the URG pointer,
2192 		 * but if two URG's are pending at once, some out-of-band
2193 		 * data may creep in... ick.
2194 		 */
2195 		if (th->th_urp <= (u_long)tlen &&
2196 		    !(so->so_options & SO_OOBINLINE)) {
2197 			/* hdr drop is delayed */
2198 			tcp_pulloutofband(so, th, m, drop_hdrlen);
2199 		}
2200 	} else {
2201 		/*
2202 		 * If no out of band data is expected,
2203 		 * pull receive urgent pointer along
2204 		 * with the receive window.
2205 		 */
2206 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2207 			tp->rcv_up = tp->rcv_nxt;
2208 	}
2209 dodata:							/* XXX */
2210 	KASSERT(headlocked, ("%s: dodata: head not locked", __func__));
2211 	INP_LOCK_ASSERT(tp->t_inpcb);
2212 
2213 	/*
2214 	 * Process the segment text, merging it into the TCP sequencing queue,
2215 	 * and arranging for acknowledgment of receipt if necessary.
2216 	 * This process logically involves adjusting tp->rcv_wnd as data
2217 	 * is presented to the user (this happens in tcp_usrreq.c,
2218 	 * case PRU_RCVD).  If a FIN has already been received on this
2219 	 * connection then we just ignore the text.
2220 	 */
2221 	if ((tlen || (thflags & TH_FIN)) &&
2222 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2223 		tcp_seq save_start = th->th_seq;
2224 		m_adj(m, drop_hdrlen);	/* delayed header drop */
2225 		/*
2226 		 * Insert segment which includes th into TCP reassembly queue
2227 		 * with control block tp.  Set thflags to whether reassembly now
2228 		 * includes a segment with FIN.  This handles the common case
2229 		 * inline (segment is the next to be received on an established
2230 		 * connection, and the queue is empty), avoiding linkage into
2231 		 * and removal from the queue and repetition of various
2232 		 * conversions.
2233 		 * Set DELACK for segments received in order, but ack
2234 		 * immediately when segments are out of order (so
2235 		 * fast retransmit can work).
2236 		 */
2237 		if (th->th_seq == tp->rcv_nxt &&
2238 		    LIST_EMPTY(&tp->t_segq) &&
2239 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2240 			if (DELAY_ACK(tp))
2241 				tp->t_flags |= TF_DELACK;
2242 			else
2243 				tp->t_flags |= TF_ACKNOW;
2244 			tp->rcv_nxt += tlen;
2245 			thflags = th->th_flags & TH_FIN;
2246 			tcpstat.tcps_rcvpack++;
2247 			tcpstat.tcps_rcvbyte += tlen;
2248 			ND6_HINT(tp);
2249 			SOCKBUF_LOCK(&so->so_rcv);
2250 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2251 				m_freem(m);
2252 			else
2253 				sbappendstream_locked(&so->so_rcv, m);
2254 			/* NB: sorwakeup_locked() does an implicit unlock. */
2255 			sorwakeup_locked(so);
2256 		} else {
2257 			/*
2258 			 * XXX: Due to the header drop above "th" is
2259 			 * theoretically invalid by now.  Fortunately
2260 			 * m_adj() doesn't actually frees any mbufs
2261 			 * when trimming from the head.
2262 			 */
2263 			thflags = tcp_reass(tp, th, &tlen, m);
2264 			tp->t_flags |= TF_ACKNOW;
2265 		}
2266 		if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2267 			tcp_update_sack_list(tp, save_start, save_start + tlen);
2268 #if 0
2269 		/*
2270 		 * Note the amount of data that peer has sent into
2271 		 * our window, in order to estimate the sender's
2272 		 * buffer size.
2273 		 * XXX: Unused.
2274 		 */
2275 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2276 #endif
2277 	} else {
2278 		m_freem(m);
2279 		thflags &= ~TH_FIN;
2280 	}
2281 
2282 	/*
2283 	 * If FIN is received ACK the FIN and let the user know
2284 	 * that the connection is closing.
2285 	 */
2286 	if (thflags & TH_FIN) {
2287 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2288 			socantrcvmore(so);
2289 			/*
2290 			 * If connection is half-synchronized
2291 			 * (ie NEEDSYN flag on) then delay ACK,
2292 			 * so it may be piggybacked when SYN is sent.
2293 			 * Otherwise, since we received a FIN then no
2294 			 * more input can be expected, send ACK now.
2295 			 */
2296 			if (tp->t_flags & TF_NEEDSYN)
2297 				tp->t_flags |= TF_DELACK;
2298 			else
2299 				tp->t_flags |= TF_ACKNOW;
2300 			tp->rcv_nxt++;
2301 		}
2302 		switch (tp->t_state) {
2303 
2304 		/*
2305 		 * In SYN_RECEIVED and ESTABLISHED STATES
2306 		 * enter the CLOSE_WAIT state.
2307 		 */
2308 		case TCPS_SYN_RECEIVED:
2309 			tp->t_starttime = ticks;
2310 			/*FALLTHROUGH*/
2311 		case TCPS_ESTABLISHED:
2312 			tp->t_state = TCPS_CLOSE_WAIT;
2313 			break;
2314 
2315 		/*
2316 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2317 		 * enter the CLOSING state.
2318 		 */
2319 		case TCPS_FIN_WAIT_1:
2320 			tp->t_state = TCPS_CLOSING;
2321 			break;
2322 
2323 		/*
2324 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2325 		 * starting the time-wait timer, turning off the other
2326 		 * standard timers.
2327 		 */
2328 		case TCPS_FIN_WAIT_2:
2329 			KASSERT(headlocked == 1, ("%s: dodata: "
2330 			    "TCP_FIN_WAIT_2: head not locked", __func__));
2331 			tcp_twstart(tp);
2332 			INP_INFO_WUNLOCK(&tcbinfo);
2333 			return;
2334 		}
2335 	}
2336 	INP_INFO_WUNLOCK(&tcbinfo);
2337 	headlocked = 0;
2338 #ifdef TCPDEBUG
2339 	if (so->so_options & SO_DEBUG)
2340 		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2341 			  &tcp_savetcp, 0);
2342 #endif
2343 
2344 	/*
2345 	 * Return any desired output.
2346 	 */
2347 	if (needoutput || (tp->t_flags & TF_ACKNOW))
2348 		(void) tcp_output(tp);
2349 
2350 check_delack:
2351 	KASSERT(headlocked == 0, ("%s: check_delack: head locked",
2352 	    __func__));
2353 	INP_INFO_UNLOCK_ASSERT(&tcbinfo);
2354 	INP_LOCK_ASSERT(tp->t_inpcb);
2355 	if (tp->t_flags & TF_DELACK) {
2356 		tp->t_flags &= ~TF_DELACK;
2357 		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2358 	}
2359 	INP_UNLOCK(tp->t_inpcb);
2360 	return;
2361 
2362 dropafterack:
2363 	KASSERT(headlocked, ("%s: dropafterack: head not locked", __func__));
2364 	/*
2365 	 * Generate an ACK dropping incoming segment if it occupies
2366 	 * sequence space, where the ACK reflects our state.
2367 	 *
2368 	 * We can now skip the test for the RST flag since all
2369 	 * paths to this code happen after packets containing
2370 	 * RST have been dropped.
2371 	 *
2372 	 * In the SYN-RECEIVED state, don't send an ACK unless the
2373 	 * segment we received passes the SYN-RECEIVED ACK test.
2374 	 * If it fails send a RST.  This breaks the loop in the
2375 	 * "LAND" DoS attack, and also prevents an ACK storm
2376 	 * between two listening ports that have been sent forged
2377 	 * SYN segments, each with the source address of the other.
2378 	 */
2379 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2380 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2381 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2382 		rstreason = BANDLIM_RST_OPENPORT;
2383 		goto dropwithreset;
2384 	}
2385 #ifdef TCPDEBUG
2386 	if (so->so_options & SO_DEBUG)
2387 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2388 			  &tcp_savetcp, 0);
2389 #endif
2390 	KASSERT(headlocked, ("%s: headlocked should be 1", __func__));
2391 	INP_INFO_WUNLOCK(&tcbinfo);
2392 	tp->t_flags |= TF_ACKNOW;
2393 	(void) tcp_output(tp);
2394 	INP_UNLOCK(tp->t_inpcb);
2395 	m_freem(m);
2396 	return;
2397 
2398 dropwithreset:
2399 	KASSERT(headlocked, ("%s: dropwithreset: head not locked", __func__));
2400 
2401 	tcp_dropwithreset(m, th, tp, tlen, rstreason);
2402 
2403 	if (tp != NULL)
2404 		INP_UNLOCK(tp->t_inpcb);
2405 	if (headlocked)
2406 		INP_INFO_WUNLOCK(&tcbinfo);
2407 	return;
2408 
2409 drop:
2410 	/*
2411 	 * Drop space held by incoming segment and return.
2412 	 */
2413 #ifdef TCPDEBUG
2414 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2415 		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2416 			  &tcp_savetcp, 0);
2417 #endif
2418 	if (tp != NULL)
2419 		INP_UNLOCK(tp->t_inpcb);
2420 	if (headlocked)
2421 		INP_INFO_WUNLOCK(&tcbinfo);
2422 	m_freem(m);
2423 	return;
2424 }
2425 
2426 /*
2427  * Issue RST and make ACK acceptable to originator of segment.
2428  * The mbuf must still include the original packet header.
2429  * tp may be NULL.
2430  */
2431 static void
2432 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2433     int tlen, int rstreason)
2434 {
2435 	struct ip *ip;
2436 #ifdef INET6
2437 	struct ip6_hdr *ip6;
2438 #endif
2439 	/* Don't bother if destination was broadcast/multicast. */
2440 	if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2441 		goto drop;
2442 #ifdef INET6
2443 	if (mtod(m, struct ip *)->ip_v == 6) {
2444 		ip6 = mtod(m, struct ip6_hdr *);
2445 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2446 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2447 			goto drop;
2448 		/* IPv6 anycast check is done at tcp6_input() */
2449 	} else
2450 #endif
2451 	{
2452 		ip = mtod(m, struct ip *);
2453 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2454 		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2455 		    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2456 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2457 			goto drop;
2458 	}
2459 
2460 	/* Perform bandwidth limiting. */
2461 	if (badport_bandlim(rstreason) < 0)
2462 		goto drop;
2463 
2464 	/* tcp_respond consumes the mbuf chain. */
2465 	if (th->th_flags & TH_ACK) {
2466 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2467 		    th->th_ack, TH_RST);
2468 	} else {
2469 		if (th->th_flags & TH_SYN)
2470 			tlen++;
2471 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2472 		    (tcp_seq)0, TH_RST|TH_ACK);
2473 	}
2474 	return;
2475 drop:
2476 	m_freem(m);
2477 	return;
2478 }
2479 
2480 /*
2481  * Parse TCP options and place in tcpopt.
2482  */
2483 static void
2484 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2485 {
2486 	int opt, optlen;
2487 
2488 	to->to_flags = 0;
2489 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2490 		opt = cp[0];
2491 		if (opt == TCPOPT_EOL)
2492 			break;
2493 		if (opt == TCPOPT_NOP)
2494 			optlen = 1;
2495 		else {
2496 			if (cnt < 2)
2497 				break;
2498 			optlen = cp[1];
2499 			if (optlen < 2 || optlen > cnt)
2500 				break;
2501 		}
2502 		switch (opt) {
2503 		case TCPOPT_MAXSEG:
2504 			if (optlen != TCPOLEN_MAXSEG)
2505 				continue;
2506 			if (!(flags & TO_SYN))
2507 				continue;
2508 			to->to_flags |= TOF_MSS;
2509 			bcopy((char *)cp + 2,
2510 			    (char *)&to->to_mss, sizeof(to->to_mss));
2511 			to->to_mss = ntohs(to->to_mss);
2512 			break;
2513 		case TCPOPT_WINDOW:
2514 			if (optlen != TCPOLEN_WINDOW)
2515 				continue;
2516 			if (!(flags & TO_SYN))
2517 				continue;
2518 			to->to_flags |= TOF_SCALE;
2519 			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2520 			break;
2521 		case TCPOPT_TIMESTAMP:
2522 			if (optlen != TCPOLEN_TIMESTAMP)
2523 				continue;
2524 			to->to_flags |= TOF_TS;
2525 			bcopy((char *)cp + 2,
2526 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2527 			to->to_tsval = ntohl(to->to_tsval);
2528 			bcopy((char *)cp + 6,
2529 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2530 			to->to_tsecr = ntohl(to->to_tsecr);
2531 			break;
2532 #ifdef TCP_SIGNATURE
2533 		/*
2534 		 * XXX In order to reply to a host which has set the
2535 		 * TCP_SIGNATURE option in its initial SYN, we have to
2536 		 * record the fact that the option was observed here
2537 		 * for the syncache code to perform the correct response.
2538 		 */
2539 		case TCPOPT_SIGNATURE:
2540 			if (optlen != TCPOLEN_SIGNATURE)
2541 				continue;
2542 			to->to_flags |= TOF_SIGNATURE;
2543 			to->to_signature = cp + 2;
2544 			break;
2545 #endif
2546 		case TCPOPT_SACK_PERMITTED:
2547 			if (optlen != TCPOLEN_SACK_PERMITTED)
2548 				continue;
2549 			if (!(flags & TO_SYN))
2550 				continue;
2551 			if (!tcp_do_sack)
2552 				continue;
2553 			to->to_flags |= TOF_SACKPERM;
2554 			break;
2555 		case TCPOPT_SACK:
2556 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2557 				continue;
2558 			if (flags & TO_SYN)
2559 				continue;
2560 			to->to_flags |= TOF_SACK;
2561 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2562 			to->to_sacks = cp + 2;
2563 			tcpstat.tcps_sack_rcv_blocks++;
2564 			break;
2565 		default:
2566 			continue;
2567 		}
2568 	}
2569 }
2570 
2571 /*
2572  * Pull out of band byte out of a segment so
2573  * it doesn't appear in the user's data queue.
2574  * It is still reflected in the segment length for
2575  * sequencing purposes.
2576  */
2577 static void
2578 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2579     int off)
2580 {
2581 	int cnt = off + th->th_urp - 1;
2582 
2583 	while (cnt >= 0) {
2584 		if (m->m_len > cnt) {
2585 			char *cp = mtod(m, caddr_t) + cnt;
2586 			struct tcpcb *tp = sototcpcb(so);
2587 
2588 			tp->t_iobc = *cp;
2589 			tp->t_oobflags |= TCPOOB_HAVEDATA;
2590 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2591 			m->m_len--;
2592 			if (m->m_flags & M_PKTHDR)
2593 				m->m_pkthdr.len--;
2594 			return;
2595 		}
2596 		cnt -= m->m_len;
2597 		m = m->m_next;
2598 		if (m == NULL)
2599 			break;
2600 	}
2601 	panic("tcp_pulloutofband");
2602 }
2603 
2604 /*
2605  * Collect new round-trip time estimate
2606  * and update averages and current timeout.
2607  */
2608 static void
2609 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2610 {
2611 	int delta;
2612 
2613 	INP_LOCK_ASSERT(tp->t_inpcb);
2614 
2615 	tcpstat.tcps_rttupdated++;
2616 	tp->t_rttupdated++;
2617 	if (tp->t_srtt != 0) {
2618 		/*
2619 		 * srtt is stored as fixed point with 5 bits after the
2620 		 * binary point (i.e., scaled by 8).  The following magic
2621 		 * is equivalent to the smoothing algorithm in rfc793 with
2622 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2623 		 * point).  Adjust rtt to origin 0.
2624 		 */
2625 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2626 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2627 
2628 		if ((tp->t_srtt += delta) <= 0)
2629 			tp->t_srtt = 1;
2630 
2631 		/*
2632 		 * We accumulate a smoothed rtt variance (actually, a
2633 		 * smoothed mean difference), then set the retransmit
2634 		 * timer to smoothed rtt + 4 times the smoothed variance.
2635 		 * rttvar is stored as fixed point with 4 bits after the
2636 		 * binary point (scaled by 16).  The following is
2637 		 * equivalent to rfc793 smoothing with an alpha of .75
2638 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2639 		 * rfc793's wired-in beta.
2640 		 */
2641 		if (delta < 0)
2642 			delta = -delta;
2643 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2644 		if ((tp->t_rttvar += delta) <= 0)
2645 			tp->t_rttvar = 1;
2646 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2647 		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2648 	} else {
2649 		/*
2650 		 * No rtt measurement yet - use the unsmoothed rtt.
2651 		 * Set the variance to half the rtt (so our first
2652 		 * retransmit happens at 3*rtt).
2653 		 */
2654 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2655 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2656 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2657 	}
2658 	tp->t_rtttime = 0;
2659 	tp->t_rxtshift = 0;
2660 
2661 	/*
2662 	 * the retransmit should happen at rtt + 4 * rttvar.
2663 	 * Because of the way we do the smoothing, srtt and rttvar
2664 	 * will each average +1/2 tick of bias.  When we compute
2665 	 * the retransmit timer, we want 1/2 tick of rounding and
2666 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2667 	 * firing of the timer.  The bias will give us exactly the
2668 	 * 1.5 tick we need.  But, because the bias is
2669 	 * statistical, we have to test that we don't drop below
2670 	 * the minimum feasible timer (which is 2 ticks).
2671 	 */
2672 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2673 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2674 
2675 	/*
2676 	 * We received an ack for a packet that wasn't retransmitted;
2677 	 * it is probably safe to discard any error indications we've
2678 	 * received recently.  This isn't quite right, but close enough
2679 	 * for now (a route might have failed after we sent a segment,
2680 	 * and the return path might not be symmetrical).
2681 	 */
2682 	tp->t_softerror = 0;
2683 }
2684 
2685 /*
2686  * Determine a reasonable value for maxseg size.
2687  * If the route is known, check route for mtu.
2688  * If none, use an mss that can be handled on the outgoing
2689  * interface without forcing IP to fragment; if bigger than
2690  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2691  * to utilize large mbufs.  If no route is found, route has no mtu,
2692  * or the destination isn't local, use a default, hopefully conservative
2693  * size (usually 512 or the default IP max size, but no more than the mtu
2694  * of the interface), as we can't discover anything about intervening
2695  * gateways or networks.  We also initialize the congestion/slow start
2696  * window to be a single segment if the destination isn't local.
2697  * While looking at the routing entry, we also initialize other path-dependent
2698  * parameters from pre-set or cached values in the routing entry.
2699  *
2700  * Also take into account the space needed for options that we
2701  * send regularly.  Make maxseg shorter by that amount to assure
2702  * that we can send maxseg amount of data even when the options
2703  * are present.  Store the upper limit of the length of options plus
2704  * data in maxopd.
2705  *
2706  * In case of T/TCP, we call this routine during implicit connection
2707  * setup as well (offer = -1), to initialize maxseg from the cached
2708  * MSS of our peer.
2709  *
2710  * NOTE that this routine is only called when we process an incoming
2711  * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2712  */
2713 void
2714 tcp_mss(struct tcpcb *tp, int offer)
2715 {
2716 	int rtt, mss;
2717 	u_long bufsize;
2718 	u_long maxmtu;
2719 	struct inpcb *inp = tp->t_inpcb;
2720 	struct socket *so;
2721 	struct hc_metrics_lite metrics;
2722 	int origoffer = offer;
2723 	int mtuflags = 0;
2724 #ifdef INET6
2725 	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2726 	size_t min_protoh = isipv6 ?
2727 			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2728 			    sizeof (struct tcpiphdr);
2729 #else
2730 	const size_t min_protoh = sizeof(struct tcpiphdr);
2731 #endif
2732 
2733 	/* Initialize. */
2734 #ifdef INET6
2735 	if (isipv6) {
2736 		maxmtu = tcp_maxmtu6(&inp->inp_inc, &mtuflags);
2737 		tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2738 	} else
2739 #endif
2740 	{
2741 		maxmtu = tcp_maxmtu(&inp->inp_inc, &mtuflags);
2742 		tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2743 	}
2744 	so = inp->inp_socket;
2745 
2746 	/*
2747 	 * No route to sender, stay with default mss and return.
2748 	 */
2749 	if (maxmtu == 0)
2750 		return;
2751 
2752 	/* What have we got? */
2753 	switch (offer) {
2754 		case 0:
2755 			/*
2756 			 * Offer == 0 means that there was no MSS on the SYN
2757 			 * segment, in this case we use tcp_mssdflt.
2758 			 */
2759 			offer =
2760 #ifdef INET6
2761 				isipv6 ? tcp_v6mssdflt :
2762 #endif
2763 				tcp_mssdflt;
2764 			break;
2765 
2766 		case -1:
2767 			/*
2768 			 * Offer == -1 means that we didn't receive SYN yet.
2769 			 */
2770 			/* FALLTHROUGH */
2771 
2772 		default:
2773 			/*
2774 			 * Prevent DoS attack with too small MSS. Round up
2775 			 * to at least minmss.
2776 			 */
2777 			offer = max(offer, tcp_minmss);
2778 			/*
2779 			 * Sanity check: make sure that maxopd will be large
2780 			 * enough to allow some data on segments even if the
2781 			 * all the option space is used (40bytes).  Otherwise
2782 			 * funny things may happen in tcp_output.
2783 			 */
2784 			offer = max(offer, 64);
2785 	}
2786 
2787 	/*
2788 	 * rmx information is now retrieved from tcp_hostcache.
2789 	 */
2790 	tcp_hc_get(&inp->inp_inc, &metrics);
2791 
2792 	/*
2793 	 * If there's a discovered mtu int tcp hostcache, use it
2794 	 * else, use the link mtu.
2795 	 */
2796 	if (metrics.rmx_mtu)
2797 		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2798 	else {
2799 #ifdef INET6
2800 		if (isipv6) {
2801 			mss = maxmtu - min_protoh;
2802 			if (!path_mtu_discovery &&
2803 			    !in6_localaddr(&inp->in6p_faddr))
2804 				mss = min(mss, tcp_v6mssdflt);
2805 		} else
2806 #endif
2807 		{
2808 			mss = maxmtu - min_protoh;
2809 			if (!path_mtu_discovery &&
2810 			    !in_localaddr(inp->inp_faddr))
2811 				mss = min(mss, tcp_mssdflt);
2812 		}
2813 	}
2814 	mss = min(mss, offer);
2815 
2816 	/*
2817 	 * maxopd stores the maximum length of data AND options
2818 	 * in a segment; maxseg is the amount of data in a normal
2819 	 * segment.  We need to store this value (maxopd) apart
2820 	 * from maxseg, because now every segment carries options
2821 	 * and thus we normally have somewhat less data in segments.
2822 	 */
2823 	tp->t_maxopd = mss;
2824 
2825 	/*
2826 	 * origoffer==-1 indicates that no segments were received yet.
2827 	 * In this case we just guess.
2828 	 */
2829 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2830 	    (origoffer == -1 ||
2831 	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2832 		mss -= TCPOLEN_TSTAMP_APPA;
2833 	tp->t_maxseg = mss;
2834 
2835 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
2836 		if (mss > MCLBYTES)
2837 			mss &= ~(MCLBYTES-1);
2838 #else
2839 		if (mss > MCLBYTES)
2840 			mss = mss / MCLBYTES * MCLBYTES;
2841 #endif
2842 	tp->t_maxseg = mss;
2843 
2844 	/*
2845 	 * If there's a pipesize, change the socket buffer to that size,
2846 	 * don't change if sb_hiwat is different than default (then it
2847 	 * has been changed on purpose with setsockopt).
2848 	 * Make the socket buffers an integral number of mss units;
2849 	 * if the mss is larger than the socket buffer, decrease the mss.
2850 	 */
2851 	SOCKBUF_LOCK(&so->so_snd);
2852 	if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2853 		bufsize = metrics.rmx_sendpipe;
2854 	else
2855 		bufsize = so->so_snd.sb_hiwat;
2856 	if (bufsize < mss)
2857 		mss = bufsize;
2858 	else {
2859 		bufsize = roundup(bufsize, mss);
2860 		if (bufsize > sb_max)
2861 			bufsize = sb_max;
2862 		if (bufsize > so->so_snd.sb_hiwat)
2863 			(void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2864 	}
2865 	SOCKBUF_UNLOCK(&so->so_snd);
2866 	tp->t_maxseg = mss;
2867 
2868 	SOCKBUF_LOCK(&so->so_rcv);
2869 	if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2870 		bufsize = metrics.rmx_recvpipe;
2871 	else
2872 		bufsize = so->so_rcv.sb_hiwat;
2873 	if (bufsize > mss) {
2874 		bufsize = roundup(bufsize, mss);
2875 		if (bufsize > sb_max)
2876 			bufsize = sb_max;
2877 		if (bufsize > so->so_rcv.sb_hiwat)
2878 			(void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
2879 	}
2880 	SOCKBUF_UNLOCK(&so->so_rcv);
2881 	/*
2882 	 * While we're here, check the others too.
2883 	 */
2884 	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
2885 		tp->t_srtt = rtt;
2886 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2887 		tcpstat.tcps_usedrtt++;
2888 		if (metrics.rmx_rttvar) {
2889 			tp->t_rttvar = metrics.rmx_rttvar;
2890 			tcpstat.tcps_usedrttvar++;
2891 		} else {
2892 			/* default variation is +- 1 rtt */
2893 			tp->t_rttvar =
2894 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2895 		}
2896 		TCPT_RANGESET(tp->t_rxtcur,
2897 			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2898 			      tp->t_rttmin, TCPTV_REXMTMAX);
2899 	}
2900 	if (metrics.rmx_ssthresh) {
2901 		/*
2902 		 * There's some sort of gateway or interface
2903 		 * buffer limit on the path.  Use this to set
2904 		 * the slow start threshhold, but set the
2905 		 * threshold to no less than 2*mss.
2906 		 */
2907 		tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
2908 		tcpstat.tcps_usedssthresh++;
2909 	}
2910 	if (metrics.rmx_bandwidth)
2911 		tp->snd_bandwidth = metrics.rmx_bandwidth;
2912 
2913 	/*
2914 	 * Set the slow-start flight size depending on whether this
2915 	 * is a local network or not.
2916 	 *
2917 	 * Extend this so we cache the cwnd too and retrieve it here.
2918 	 * Make cwnd even bigger than RFC3390 suggests but only if we
2919 	 * have previous experience with the remote host. Be careful
2920 	 * not make cwnd bigger than remote receive window or our own
2921 	 * send socket buffer. Maybe put some additional upper bound
2922 	 * on the retrieved cwnd. Should do incremental updates to
2923 	 * hostcache when cwnd collapses so next connection doesn't
2924 	 * overloads the path again.
2925 	 *
2926 	 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
2927 	 * We currently check only in syncache_socket for that.
2928 	 */
2929 #define TCP_METRICS_CWND
2930 #ifdef TCP_METRICS_CWND
2931 	if (metrics.rmx_cwnd)
2932 		tp->snd_cwnd = max(mss,
2933 				min(metrics.rmx_cwnd / 2,
2934 				 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
2935 	else
2936 #endif
2937 	if (tcp_do_rfc3390)
2938 		tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2939 #ifdef INET6
2940 	else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2941 		 (!isipv6 && in_localaddr(inp->inp_faddr)))
2942 #else
2943 	else if (in_localaddr(inp->inp_faddr))
2944 #endif
2945 		tp->snd_cwnd = mss * ss_fltsz_local;
2946 	else
2947 		tp->snd_cwnd = mss * ss_fltsz;
2948 
2949 	/* Check the interface for TSO capabilities. */
2950 	if (mtuflags & CSUM_TSO)
2951 		tp->t_flags |= TF_TSO;
2952 }
2953 
2954 /*
2955  * Determine the MSS option to send on an outgoing SYN.
2956  */
2957 int
2958 tcp_mssopt(struct in_conninfo *inc)
2959 {
2960 	int mss = 0;
2961 	u_long maxmtu = 0;
2962 	u_long thcmtu = 0;
2963 	size_t min_protoh;
2964 #ifdef INET6
2965 	int isipv6 = inc->inc_isipv6 ? 1 : 0;
2966 #endif
2967 
2968 	KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
2969 
2970 #ifdef INET6
2971 	if (isipv6) {
2972 		mss = tcp_v6mssdflt;
2973 		maxmtu = tcp_maxmtu6(inc, NULL);
2974 		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
2975 		min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
2976 	} else
2977 #endif
2978 	{
2979 		mss = tcp_mssdflt;
2980 		maxmtu = tcp_maxmtu(inc, NULL);
2981 		thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
2982 		min_protoh = sizeof(struct tcpiphdr);
2983 	}
2984 	if (maxmtu && thcmtu)
2985 		mss = min(maxmtu, thcmtu) - min_protoh;
2986 	else if (maxmtu || thcmtu)
2987 		mss = max(maxmtu, thcmtu) - min_protoh;
2988 
2989 	return (mss);
2990 }
2991 
2992 
2993 /*
2994  * On a partial ack arrives, force the retransmission of the
2995  * next unacknowledged segment.  Do not clear tp->t_dupacks.
2996  * By setting snd_nxt to ti_ack, this forces retransmission timer to
2997  * be started again.
2998  */
2999 static void
3000 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3001 {
3002 	tcp_seq onxt = tp->snd_nxt;
3003 	u_long  ocwnd = tp->snd_cwnd;
3004 
3005 	tcp_timer_activate(tp, TT_REXMT, 0);
3006 	tp->t_rtttime = 0;
3007 	tp->snd_nxt = th->th_ack;
3008 	/*
3009 	 * Set snd_cwnd to one segment beyond acknowledged offset.
3010 	 * (tp->snd_una has not yet been updated when this function is called.)
3011 	 */
3012 	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3013 	tp->t_flags |= TF_ACKNOW;
3014 	(void) tcp_output(tp);
3015 	tp->snd_cwnd = ocwnd;
3016 	if (SEQ_GT(onxt, tp->snd_nxt))
3017 		tp->snd_nxt = onxt;
3018 	/*
3019 	 * Partial window deflation.  Relies on fact that tp->snd_una
3020 	 * not updated yet.
3021 	 */
3022 	if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3023 		tp->snd_cwnd -= th->th_ack - tp->snd_una;
3024 	else
3025 		tp->snd_cwnd = 0;
3026 	tp->snd_cwnd += tp->t_maxseg;
3027 }
3028