tcp_input.c revision 102131
1126274Sdes/*
2126274Sdes * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3126274Sdes *	The Regents of the University of California.  All rights reserved.
4126274Sdes *
5126274Sdes * Redistribution and use in source and binary forms, with or without
6126274Sdes * modification, are permitted provided that the following conditions
7126274Sdes * are met:
8126274Sdes * 1. Redistributions of source code must retain the above copyright
9126274Sdes *    notice, this list of conditions and the following disclaimer.
10126274Sdes * 2. Redistributions in binary form must reproduce the above copyright
11126274Sdes *    notice, this list of conditions and the following disclaimer in the
12126274Sdes *    documentation and/or other materials provided with the distribution.
13126274Sdes * 3. All advertising materials mentioning features or use of this software
14126274Sdes *    must display the following acknowledgement:
15126274Sdes *	This product includes software developed by the University of
16126274Sdes *	California, Berkeley and its contributors.
17126274Sdes * 4. Neither the name of the University nor the names of its contributors
18126274Sdes *    may be used to endorse or promote products derived from this software
19126274Sdes *    without specific prior written permission.
20126274Sdes *
21126274Sdes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22126274Sdes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23126274Sdes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24126274Sdes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25126274Sdes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26126274Sdes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27126274Sdes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28126274Sdes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29162852Sdes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30162852Sdes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31181111Sdes * SUCH DAMAGE.
32126274Sdes *
33162852Sdes *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
34162852Sdes * $FreeBSD: head/sys/netinet/tcp_input.c 102131 2002-08-19 19:47:13Z jmallett $
35126274Sdes */
36126274Sdes
37126274Sdes#include "opt_ipfw.h"		/* for ipfw_fwd		*/
38126274Sdes#include "opt_inet6.h"
39146998Sdes#include "opt_ipsec.h"
40146998Sdes#include "opt_mac.h"
41146998Sdes#include "opt_tcpdebug.h"
42126274Sdes#include "opt_tcp_input.h"
43126274Sdes
44126274Sdes#include <sys/param.h>
45126274Sdes#include <sys/kernel.h>
46126274Sdes#include <sys/mac.h>
47126274Sdes#include <sys/malloc.h>
48126274Sdes#include <sys/mbuf.h>
49126274Sdes#include <sys/proc.h>		/* for proc0 declaration */
50126274Sdes#include <sys/protosw.h>
51126274Sdes#include <sys/signalvar.h>
52126274Sdes#include <sys/socket.h>
53126274Sdes#include <sys/socketvar.h>
54126274Sdes#include <sys/sysctl.h>
55126274Sdes#include <sys/syslog.h>
56126274Sdes#include <sys/systm.h>
57126274Sdes
58126274Sdes#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
59126274Sdes
60126274Sdes#include <net/if.h>
61126274Sdes#include <net/route.h>
62126274Sdes
63126274Sdes#include <netinet/in.h>
64126274Sdes#include <netinet/in_pcb.h>
65126274Sdes#include <netinet/in_systm.h>
66126274Sdes#include <netinet/in_var.h>
67126274Sdes#include <netinet/ip.h>
68126274Sdes#include <netinet/ip_icmp.h>	/* for ICMP_BANDLIM		*/
69126274Sdes#include <netinet/icmp_var.h>	/* for ICMP_BANDLIM		*/
70126274Sdes#include <netinet/ip_var.h>
71126274Sdes#include <netinet/ip6.h>
72126274Sdes#include <netinet/icmp6.h>
73126274Sdes#include <netinet6/in6_pcb.h>
74126274Sdes#include <netinet6/ip6_var.h>
75126274Sdes#include <netinet6/nd6.h>
76126274Sdes#include <netinet/tcp.h>
77126274Sdes#include <netinet/tcp_fsm.h>
78126274Sdes#include <netinet/tcp_seq.h>
79126274Sdes#include <netinet/tcp_timer.h>
80126274Sdes#include <netinet/tcp_var.h>
81126274Sdes#include <netinet6/tcp6_var.h>
82126274Sdes#include <netinet/tcpip.h>
83126274Sdes#ifdef TCPDEBUG
84126274Sdes#include <netinet/tcp_debug.h>
85126274Sdes#endif /* TCPDEBUG */
86126274Sdes
87126274Sdes#ifdef IPSEC
88126274Sdes#include <netinet6/ipsec.h>
89126274Sdes#include <netinet6/ipsec6.h>
90126274Sdes#include <netkey/key.h>
91126274Sdes#endif /*IPSEC*/
92126274Sdes
93126274Sdes#include <machine/in_cksum.h>
94126274Sdes
95126274SdesMALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
96126274Sdes
97126274Sdesstatic const int tcprexmtthresh = 3;
98126274Sdestcp_cc	tcp_ccgen;
99126274Sdes
100126274Sdesstruct	tcpstat tcpstat;
101126274SdesSYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
102126274Sdes    &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
103126274Sdes
104126274Sdesstatic int log_in_vain = 0;
105126274SdesSYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
106126274Sdes    &log_in_vain, 0, "Log all incoming TCP connections");
107126274Sdes
108149749Sdesstatic int blackhole = 0;
109126274SdesSYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
110126274Sdes	&blackhole, 0, "Do not send RST when dropping refused connections");
111126274Sdes
112126274Sdesint tcp_delack_enabled = 1;
113126274SdesSYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
114126274Sdes    &tcp_delack_enabled, 0,
115126274Sdes    "Delay ACK to try and piggyback it onto a data packet");
116126274Sdes
117126274Sdes#ifdef TCP_DROP_SYNFIN
118126274Sdesstatic int drop_synfin = 0;
119126274SdesSYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
120126274Sdes    &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
121126274Sdes#endif
122126274Sdes
123126274Sdesstruct inpcbhead tcb;
124126274Sdes#define	tcb6	tcb  /* for KAME src sync over BSD*'s */
125126274Sdesstruct inpcbinfo tcbinfo;
126126274Sdesstruct mtx	*tcbinfo_mtx;
127126274Sdes
128126274Sdesstatic void	 tcp_dooptions(struct tcpopt *, u_char *, int, int);
129126274Sdesstatic void	 tcp_pulloutofband(struct socket *,
130126274Sdes		     struct tcphdr *, struct mbuf *, int);
131126274Sdesstatic int	 tcp_reass(struct tcpcb *, struct tcphdr *, int *,
132126274Sdes		     struct mbuf *);
133126274Sdesstatic void	 tcp_xmit_timer(struct tcpcb *, int);
134126274Sdesstatic void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
135126274Sdes
136126274Sdes/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
137126274Sdes#ifdef INET6
138126274Sdes#define ND6_HINT(tp) \
139126274Sdesdo { \
140126274Sdes	if ((tp) && (tp)->t_inpcb && \
141126274Sdes	    ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
142126274Sdes	    (tp)->t_inpcb->in6p_route.ro_rt) \
143		nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
144} while (0)
145#else
146#define ND6_HINT(tp)
147#endif
148
149/*
150 * Indicate whether this ack should be delayed.  We can delay the ack if
151 *	- delayed acks are enabled and
152 *	- there is no delayed ack timer in progress and
153 *	- our last ack wasn't a 0-sized window.  We never want to delay
154 *	  the ack that opens up a 0-sized window.
155 */
156#define DELAY_ACK(tp) \
157	(tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
158	(tp->t_flags & TF_RXWIN0SENT) == 0)
159
160static int
161tcp_reass(tp, th, tlenp, m)
162	register struct tcpcb *tp;
163	register struct tcphdr *th;
164	int *tlenp;
165	struct mbuf *m;
166{
167	struct tseg_qent *q;
168	struct tseg_qent *p = NULL;
169	struct tseg_qent *nq;
170	struct tseg_qent *te;
171	struct socket *so = tp->t_inpcb->inp_socket;
172	int flags;
173
174	/*
175	 * Call with th==0 after become established to
176	 * force pre-ESTABLISHED data up to user socket.
177	 */
178	if (th == 0)
179		goto present;
180
181	/* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
182	MALLOC(te, struct tseg_qent *, sizeof (struct tseg_qent), M_TSEGQ,
183	       M_NOWAIT);
184	if (te == NULL) {
185		tcpstat.tcps_rcvmemdrop++;
186		m_freem(m);
187		return (0);
188	}
189
190	/*
191	 * Find a segment which begins after this one does.
192	 */
193	LIST_FOREACH(q, &tp->t_segq, tqe_q) {
194		if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
195			break;
196		p = q;
197	}
198
199	/*
200	 * If there is a preceding segment, it may provide some of
201	 * our data already.  If so, drop the data from the incoming
202	 * segment.  If it provides all of our data, drop us.
203	 */
204	if (p != NULL) {
205		register int i;
206		/* conversion to int (in i) handles seq wraparound */
207		i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
208		if (i > 0) {
209			if (i >= *tlenp) {
210				tcpstat.tcps_rcvduppack++;
211				tcpstat.tcps_rcvdupbyte += *tlenp;
212				m_freem(m);
213				FREE(te, M_TSEGQ);
214				/*
215				 * Try to present any queued data
216				 * at the left window edge to the user.
217				 * This is needed after the 3-WHS
218				 * completes.
219				 */
220				goto present;	/* ??? */
221			}
222			m_adj(m, i);
223			*tlenp -= i;
224			th->th_seq += i;
225		}
226	}
227	tcpstat.tcps_rcvoopack++;
228	tcpstat.tcps_rcvoobyte += *tlenp;
229
230	/*
231	 * While we overlap succeeding segments trim them or,
232	 * if they are completely covered, dequeue them.
233	 */
234	while (q) {
235		register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
236		if (i <= 0)
237			break;
238		if (i < q->tqe_len) {
239			q->tqe_th->th_seq += i;
240			q->tqe_len -= i;
241			m_adj(q->tqe_m, i);
242			break;
243		}
244
245		nq = LIST_NEXT(q, tqe_q);
246		LIST_REMOVE(q, tqe_q);
247		m_freem(q->tqe_m);
248		FREE(q, M_TSEGQ);
249		q = nq;
250	}
251
252	/* Insert the new segment queue entry into place. */
253	te->tqe_m = m;
254	te->tqe_th = th;
255	te->tqe_len = *tlenp;
256
257	if (p == NULL) {
258		LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
259	} else {
260		LIST_INSERT_AFTER(p, te, tqe_q);
261	}
262
263present:
264	/*
265	 * Present data to user, advancing rcv_nxt through
266	 * completed sequence space.
267	 */
268	if (!TCPS_HAVEESTABLISHED(tp->t_state))
269		return (0);
270	q = LIST_FIRST(&tp->t_segq);
271	if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
272		return (0);
273	do {
274		tp->rcv_nxt += q->tqe_len;
275		flags = q->tqe_th->th_flags & TH_FIN;
276		nq = LIST_NEXT(q, tqe_q);
277		LIST_REMOVE(q, tqe_q);
278		if (so->so_state & SS_CANTRCVMORE)
279			m_freem(q->tqe_m);
280		else
281			sbappend(&so->so_rcv, q->tqe_m);
282		FREE(q, M_TSEGQ);
283		q = nq;
284	} while (q && q->tqe_th->th_seq == tp->rcv_nxt);
285	ND6_HINT(tp);
286	sorwakeup(so);
287	return (flags);
288}
289
290/*
291 * TCP input routine, follows pages 65-76 of the
292 * protocol specification dated September, 1981 very closely.
293 */
294#ifdef INET6
295int
296tcp6_input(mp, offp, proto)
297	struct mbuf **mp;
298	int *offp, proto;
299{
300	register struct mbuf *m = *mp;
301	struct in6_ifaddr *ia6;
302
303	IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
304
305	/*
306	 * draft-itojun-ipv6-tcp-to-anycast
307	 * better place to put this in?
308	 */
309	ia6 = ip6_getdstifaddr(m);
310	if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
311		struct ip6_hdr *ip6;
312
313		ip6 = mtod(m, struct ip6_hdr *);
314		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
315			    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
316		return IPPROTO_DONE;
317	}
318
319	tcp_input(m, *offp);
320	return IPPROTO_DONE;
321}
322#endif
323
324void
325tcp_input(m, off0)
326	register struct mbuf *m;
327	int off0;
328{
329	register struct tcphdr *th;
330	register struct ip *ip = NULL;
331	register struct ipovly *ipov;
332	register struct inpcb *inp = NULL;
333	u_char *optp = NULL;
334	int optlen = 0;
335	int len, tlen, off;
336	int drop_hdrlen;
337	register struct tcpcb *tp = 0;
338	register int thflags;
339	struct socket *so = 0;
340	int todrop, acked, ourfinisacked, needoutput = 0;
341	u_long tiwin;
342	struct tcpopt to;		/* options in this segment */
343	struct rmxp_tao *taop;		/* pointer to our TAO cache entry */
344	struct rmxp_tao	tao_noncached;	/* in case there's no cached entry */
345	int headlocked = 0;
346	struct sockaddr_in *next_hop = NULL;
347	int rstreason; /* For badport_bandlim accounting purposes */
348
349	struct ip6_hdr *ip6 = NULL;
350#ifdef INET6
351	int isipv6;
352#else
353	const int isipv6 = 0;
354#endif
355
356#ifdef TCPDEBUG
357	/*
358	 * The size of tcp_saveipgen must be the size of the max ip header,
359	 * now IPv6.
360	 */
361	u_char tcp_saveipgen[40];
362	struct tcphdr tcp_savetcp;
363	short ostate = 0;
364#endif
365
366#ifdef MAC
367	int error;
368#endif
369
370	/* Grab info from MT_TAG mbufs prepended to the chain. */
371	for (;m && m->m_type == MT_TAG; m = m->m_next) {
372		if (m->m_tag_id == PACKET_TAG_IPFORWARD)
373			next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
374	}
375#ifdef INET6
376	isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
377#endif
378	bzero((char *)&to, sizeof(to));
379
380	tcpstat.tcps_rcvtotal++;
381
382	if (isipv6) {
383		/* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
384		ip6 = mtod(m, struct ip6_hdr *);
385		tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
386		if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
387			tcpstat.tcps_rcvbadsum++;
388			goto drop;
389		}
390		th = (struct tcphdr *)((caddr_t)ip6 + off0);
391
392		/*
393		 * Be proactive about unspecified IPv6 address in source.
394		 * As we use all-zero to indicate unbounded/unconnected pcb,
395		 * unspecified IPv6 address can be used to confuse us.
396		 *
397		 * Note that packets with unspecified IPv6 destination is
398		 * already dropped in ip6_input.
399		 */
400		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
401			/* XXX stat */
402			goto drop;
403		}
404	} else {
405		/*
406		 * Get IP and TCP header together in first mbuf.
407		 * Note: IP leaves IP header in first mbuf.
408		 */
409		if (off0 > sizeof (struct ip)) {
410			ip_stripoptions(m, (struct mbuf *)0);
411			off0 = sizeof(struct ip);
412		}
413		if (m->m_len < sizeof (struct tcpiphdr)) {
414			if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
415				tcpstat.tcps_rcvshort++;
416				return;
417			}
418		}
419		ip = mtod(m, struct ip *);
420		ipov = (struct ipovly *)ip;
421		th = (struct tcphdr *)((caddr_t)ip + off0);
422		tlen = ip->ip_len;
423
424		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
425			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
426				th->th_sum = m->m_pkthdr.csum_data;
427			else
428				th->th_sum = in_pseudo(ip->ip_src.s_addr,
429						ip->ip_dst.s_addr,
430						htonl(m->m_pkthdr.csum_data +
431							ip->ip_len +
432							IPPROTO_TCP));
433			th->th_sum ^= 0xffff;
434		} else {
435			/*
436			 * Checksum extended TCP header and data.
437			 */
438			len = sizeof (struct ip) + tlen;
439			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
440			ipov->ih_len = (u_short)tlen;
441			ipov->ih_len = htons(ipov->ih_len);
442			th->th_sum = in_cksum(m, len);
443		}
444		if (th->th_sum) {
445			tcpstat.tcps_rcvbadsum++;
446			goto drop;
447		}
448#ifdef INET6
449		/* Re-initialization for later version check */
450		ip->ip_v = IPVERSION;
451#endif
452	}
453
454	/*
455	 * Check that TCP offset makes sense,
456	 * pull out TCP options and adjust length.		XXX
457	 */
458	off = th->th_off << 2;
459	if (off < sizeof (struct tcphdr) || off > tlen) {
460		tcpstat.tcps_rcvbadoff++;
461		goto drop;
462	}
463	tlen -= off;	/* tlen is used instead of ti->ti_len */
464	if (off > sizeof (struct tcphdr)) {
465		if (isipv6) {
466			IP6_EXTHDR_CHECK(m, off0, off, );
467			ip6 = mtod(m, struct ip6_hdr *);
468			th = (struct tcphdr *)((caddr_t)ip6 + off0);
469		} else {
470			if (m->m_len < sizeof(struct ip) + off) {
471				if ((m = m_pullup(m, sizeof (struct ip) + off))
472						== 0) {
473					tcpstat.tcps_rcvshort++;
474					return;
475				}
476				ip = mtod(m, struct ip *);
477				ipov = (struct ipovly *)ip;
478				th = (struct tcphdr *)((caddr_t)ip + off0);
479			}
480		}
481		optlen = off - sizeof (struct tcphdr);
482		optp = (u_char *)(th + 1);
483	}
484	thflags = th->th_flags;
485
486#ifdef TCP_DROP_SYNFIN
487	/*
488	 * If the drop_synfin option is enabled, drop all packets with
489	 * both the SYN and FIN bits set. This prevents e.g. nmap from
490	 * identifying the TCP/IP stack.
491	 *
492	 * This is a violation of the TCP specification.
493	 */
494	if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
495		goto drop;
496#endif
497
498	/*
499	 * Convert TCP protocol specific fields to host format.
500	 */
501	th->th_seq = ntohl(th->th_seq);
502	th->th_ack = ntohl(th->th_ack);
503	th->th_win = ntohs(th->th_win);
504	th->th_urp = ntohs(th->th_urp);
505
506	/*
507	 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
508	 * until after ip6_savecontrol() is called and before other functions
509	 * which don't want those proto headers.
510	 * Because ip6_savecontrol() is going to parse the mbuf to
511	 * search for data to be passed up to user-land, it wants mbuf
512	 * parameters to be unchanged.
513	 * XXX: the call of ip6_savecontrol() has been obsoleted based on
514	 * latest version of the advanced API (20020110).
515	 */
516	drop_hdrlen = off0 + off;
517
518	/*
519	 * Locate pcb for segment.
520	 */
521	 INP_INFO_WLOCK(&tcbinfo);
522	 headlocked = 1;
523findpcb:
524	/* IPFIREWALL_FORWARD section */
525	if (next_hop != NULL && isipv6 == 0) {	/* IPv6 support is not yet */
526		/*
527		 * Transparently forwarded. Pretend to be the destination.
528		 * already got one like this?
529		 */
530		inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
531					ip->ip_dst, th->th_dport,
532					0, m->m_pkthdr.rcvif);
533		if (!inp) {
534			/* It's new.  Try find the ambushing socket. */
535			inp = in_pcblookup_hash(&tcbinfo,
536						ip->ip_src, th->th_sport,
537						next_hop->sin_addr,
538						next_hop->sin_port ?
539						    ntohs(next_hop->sin_port) :
540						    th->th_dport,
541						1, m->m_pkthdr.rcvif);
542		}
543	} else {
544		if (isipv6)
545			inp = in6_pcblookup_hash(&tcbinfo,
546						 &ip6->ip6_src, th->th_sport,
547						 &ip6->ip6_dst, th->th_dport,
548						 1, m->m_pkthdr.rcvif);
549		else
550			inp = in_pcblookup_hash(&tcbinfo,
551						ip->ip_src, th->th_sport,
552						ip->ip_dst, th->th_dport,
553						1, m->m_pkthdr.rcvif);
554      }
555
556#ifdef IPSEC
557	if (isipv6) {
558		if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
559			ipsec6stat.in_polvio++;
560			goto drop;
561		}
562	} else {
563		if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
564			ipsecstat.in_polvio++;
565			goto drop;
566		}
567	}
568#endif
569
570	/*
571	 * If the state is CLOSED (i.e., TCB does not exist) then
572	 * all data in the incoming segment is discarded.
573	 * If the TCB exists but is in CLOSED state, it is embryonic,
574	 * but should either do a listen or a connect soon.
575	 */
576	if (inp == NULL) {
577		if (log_in_vain) {
578#ifdef INET6
579			char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
580#else
581			char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
582#endif
583
584			if (isipv6) {
585				strcpy(dbuf, "[");
586				strcpy(sbuf, "[");
587				strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
588				strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
589				strcat(dbuf, "]");
590				strcat(sbuf, "]");
591			} else {
592				strcpy(dbuf, inet_ntoa(ip->ip_dst));
593				strcpy(sbuf, inet_ntoa(ip->ip_src));
594			}
595			switch (log_in_vain) {
596			case 1:
597				if (thflags & TH_SYN)
598					log(LOG_INFO,
599					    "Connection attempt to TCP %s:%d "
600					    "from %s:%d\n",
601					    dbuf, ntohs(th->th_dport), sbuf,
602					    ntohs(th->th_sport));
603				break;
604			case 2:
605				log(LOG_INFO,
606				    "Connection attempt to TCP %s:%d "
607				    "from %s:%d flags:0x%x\n",
608				    dbuf, ntohs(th->th_dport), sbuf,
609				    ntohs(th->th_sport), thflags);
610				break;
611			default:
612				break;
613			}
614		}
615		if (blackhole) {
616			switch (blackhole) {
617			case 1:
618				if (thflags & TH_SYN)
619					goto drop;
620				break;
621			case 2:
622				goto drop;
623			default:
624				goto drop;
625			}
626		}
627		rstreason = BANDLIM_RST_CLOSEDPORT;
628		goto dropwithreset;
629	}
630	INP_LOCK(inp);
631	tp = intotcpcb(inp);
632	if (tp == 0) {
633		INP_UNLOCK(inp);
634		rstreason = BANDLIM_RST_CLOSEDPORT;
635		goto dropwithreset;
636	}
637	if (tp->t_state == TCPS_CLOSED)
638		goto drop;
639
640	/* Unscale the window into a 32-bit value. */
641	if ((thflags & TH_SYN) == 0)
642		tiwin = th->th_win << tp->snd_scale;
643	else
644		tiwin = th->th_win;
645
646	so = inp->inp_socket;
647#ifdef MAC
648	error = mac_check_socket_deliver(so, m);
649	if (error)
650		goto drop;
651#endif
652	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
653		struct in_conninfo inc;
654#ifdef TCPDEBUG
655		if (so->so_options & SO_DEBUG) {
656			ostate = tp->t_state;
657			if (isipv6)
658				bcopy((char *)ip6, (char *)tcp_saveipgen,
659					sizeof(*ip6));
660			else
661				bcopy((char *)ip, (char *)tcp_saveipgen,
662					sizeof(*ip));
663			tcp_savetcp = *th;
664		}
665#endif
666		/* skip if this isn't a listen socket */
667		if ((so->so_options & SO_ACCEPTCONN) == 0)
668			goto after_listen;
669#ifdef INET6
670		inc.inc_isipv6 = isipv6;
671#endif
672		if (isipv6) {
673			inc.inc6_faddr = ip6->ip6_src;
674			inc.inc6_laddr = ip6->ip6_dst;
675			inc.inc6_route.ro_rt = NULL;		/* XXX */
676		} else {
677			inc.inc_faddr = ip->ip_src;
678			inc.inc_laddr = ip->ip_dst;
679			inc.inc_route.ro_rt = NULL;		/* XXX */
680		}
681		inc.inc_fport = th->th_sport;
682		inc.inc_lport = th->th_dport;
683
684	        /*
685	         * If the state is LISTEN then ignore segment if it contains
686		 * a RST.  If the segment contains an ACK then it is bad and
687		 * send a RST.  If it does not contain a SYN then it is not
688		 * interesting; drop it.
689		 *
690		 * If the state is SYN_RECEIVED (syncache) and seg contains
691		 * an ACK, but not for our SYN/ACK, send a RST.  If the seg
692		 * contains a RST, check the sequence number to see if it
693		 * is a valid reset segment.
694		 */
695		if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
696			if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
697				if (!syncache_expand(&inc, th, &so, m)) {
698					/*
699					 * No syncache entry, or ACK was not
700					 * for our SYN/ACK.  Send a RST.
701					 */
702					tcpstat.tcps_badsyn++;
703					rstreason = BANDLIM_RST_OPENPORT;
704					goto dropwithreset;
705				}
706				if (so == NULL) {
707					/*
708					 * Could not complete 3-way handshake,
709					 * connection is being closed down, and
710					 * syncache will free mbuf.
711					 */
712					INP_UNLOCK(inp);
713					INP_INFO_WUNLOCK(&tcbinfo);
714					return;
715				}
716				/*
717				 * Socket is created in state SYN_RECEIVED.
718				 * Continue processing segment.
719				 */
720				INP_UNLOCK(inp);
721				inp = sotoinpcb(so);
722				INP_LOCK(inp);
723				tp = intotcpcb(inp);
724				/*
725				 * This is what would have happened in
726				 * tcp_output() when the SYN,ACK was sent.
727				 */
728				tp->snd_up = tp->snd_una;
729				tp->snd_max = tp->snd_nxt = tp->iss + 1;
730				tp->last_ack_sent = tp->rcv_nxt;
731/*
732 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
733 * until the _second_ ACK is received:
734 *    rcv SYN (set wscale opts)	 --> send SYN/ACK, set snd_wnd = window.
735 *    rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
736 *        move to ESTAB, set snd_wnd to tiwin.
737 */
738				tp->snd_wnd = tiwin;	/* unscaled */
739				goto after_listen;
740			}
741			if (thflags & TH_RST) {
742				syncache_chkrst(&inc, th);
743				goto drop;
744			}
745			if (thflags & TH_ACK) {
746				syncache_badack(&inc);
747				tcpstat.tcps_badsyn++;
748				rstreason = BANDLIM_RST_OPENPORT;
749				goto dropwithreset;
750			}
751			goto drop;
752		}
753
754		/*
755		 * Segment's flags are (SYN) or (SYN|FIN).
756		 */
757#ifdef INET6
758		/*
759		 * If deprecated address is forbidden,
760		 * we do not accept SYN to deprecated interface
761		 * address to prevent any new inbound connection from
762		 * getting established.
763		 * When we do not accept SYN, we send a TCP RST,
764		 * with deprecated source address (instead of dropping
765		 * it).  We compromise it as it is much better for peer
766		 * to send a RST, and RST will be the final packet
767		 * for the exchange.
768		 *
769		 * If we do not forbid deprecated addresses, we accept
770		 * the SYN packet.  RFC2462 does not suggest dropping
771		 * SYN in this case.
772		 * If we decipher RFC2462 5.5.4, it says like this:
773		 * 1. use of deprecated addr with existing
774		 *    communication is okay - "SHOULD continue to be
775		 *    used"
776		 * 2. use of it with new communication:
777		 *   (2a) "SHOULD NOT be used if alternate address
778		 *        with sufficient scope is available"
779		 *   (2b) nothing mentioned otherwise.
780		 * Here we fall into (2b) case as we have no choice in
781		 * our source address selection - we must obey the peer.
782		 *
783		 * The wording in RFC2462 is confusing, and there are
784		 * multiple description text for deprecated address
785		 * handling - worse, they are not exactly the same.
786		 * I believe 5.5.4 is the best one, so we follow 5.5.4.
787		 */
788		if (isipv6 && !ip6_use_deprecated) {
789			struct in6_ifaddr *ia6;
790
791			if ((ia6 = ip6_getdstifaddr(m)) &&
792			    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
793				INP_UNLOCK(inp);
794				tp = NULL;
795				rstreason = BANDLIM_RST_OPENPORT;
796				goto dropwithreset;
797			}
798		}
799#endif
800		/*
801		 * If it is from this socket, drop it, it must be forged.
802		 * Don't bother responding if the destination was a broadcast.
803		 */
804		if (th->th_dport == th->th_sport) {
805			if (isipv6) {
806				if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
807						       &ip6->ip6_src))
808					goto drop;
809			} else {
810				if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
811					goto drop;
812			}
813		}
814		/*
815		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
816		 *
817		 * Note that it is quite possible to receive unicast
818		 * link-layer packets with a broadcast IP address. Use
819		 * in_broadcast() to find them.
820		 */
821		if (m->m_flags & (M_BCAST|M_MCAST))
822			goto drop;
823		if (isipv6) {
824			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
825			    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
826				goto drop;
827		} else {
828			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
829			    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
830			    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
831			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
832				goto drop;
833		}
834		/*
835		 * SYN appears to be valid; create compressed TCP state
836		 * for syncache, or perform t/tcp connection.
837		 */
838		if (so->so_qlen <= so->so_qlimit) {
839			tcp_dooptions(&to, optp, optlen, 1);
840			if (!syncache_add(&inc, &to, th, &so, m))
841				goto drop;
842			if (so == NULL) {
843				/*
844				 * Entry added to syncache, mbuf used to
845				 * send SYN,ACK packet.
846				 */
847				KASSERT(headlocked, ("headlocked"));
848				INP_UNLOCK(inp);
849				INP_INFO_WUNLOCK(&tcbinfo);
850				return;
851			}
852			/*
853			 * Segment passed TAO tests.
854			 */
855			INP_UNLOCK(inp);
856			inp = sotoinpcb(so);
857			INP_LOCK(inp);
858			tp = intotcpcb(inp);
859			tp->snd_wnd = tiwin;
860			tp->t_starttime = ticks;
861			tp->t_state = TCPS_ESTABLISHED;
862
863			/*
864			 * If there is a FIN, or if there is data and the
865			 * connection is local, then delay SYN,ACK(SYN) in
866			 * the hope of piggy-backing it on a response
867			 * segment.  Otherwise must send ACK now in case
868			 * the other side is slow starting.
869			 */
870			if (DELAY_ACK(tp) &&
871			    ((thflags & TH_FIN) ||
872			     (tlen != 0 &&
873			      ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
874			       (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
875				callout_reset(tp->tt_delack, tcp_delacktime,
876						tcp_timer_delack, tp);
877				tp->t_flags |= TF_NEEDSYN;
878			} else
879				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
880
881			tcpstat.tcps_connects++;
882			soisconnected(so);
883			goto trimthenstep6;
884		}
885		goto drop;
886	}
887after_listen:
888
889/* XXX temp debugging */
890	/* should not happen - syncache should pick up these connections */
891	if (tp->t_state == TCPS_LISTEN)
892		panic("tcp_input: TCPS_LISTEN");
893
894	/*
895	 * Segment received on connection.
896	 * Reset idle time and keep-alive timer.
897	 */
898	tp->t_rcvtime = ticks;
899	if (TCPS_HAVEESTABLISHED(tp->t_state))
900		callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
901
902	/*
903	 * Process options.
904	 * XXX this is tradtitional behavior, may need to be cleaned up.
905	 */
906	tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
907	if (thflags & TH_SYN) {
908		if (to.to_flags & TOF_SCALE) {
909			tp->t_flags |= TF_RCVD_SCALE;
910			tp->requested_s_scale = to.to_requested_s_scale;
911		}
912		if (to.to_flags & TOF_TS) {
913			tp->t_flags |= TF_RCVD_TSTMP;
914			tp->ts_recent = to.to_tsval;
915			tp->ts_recent_age = ticks;
916		}
917		if (to.to_flags & (TOF_CC|TOF_CCNEW))
918			tp->t_flags |= TF_RCVD_CC;
919		if (to.to_flags & TOF_MSS)
920			tcp_mss(tp, to.to_mss);
921	}
922
923	/*
924	 * Header prediction: check for the two common cases
925	 * of a uni-directional data xfer.  If the packet has
926	 * no control flags, is in-sequence, the window didn't
927	 * change and we're not retransmitting, it's a
928	 * candidate.  If the length is zero and the ack moved
929	 * forward, we're the sender side of the xfer.  Just
930	 * free the data acked & wake any higher level process
931	 * that was blocked waiting for space.  If the length
932	 * is non-zero and the ack didn't move, we're the
933	 * receiver side.  If we're getting packets in-order
934	 * (the reassembly queue is empty), add the data to
935	 * the socket buffer and note that we need a delayed ack.
936	 * Make sure that the hidden state-flags are also off.
937	 * Since we check for TCPS_ESTABLISHED above, it can only
938	 * be TH_NEEDSYN.
939	 */
940	if (tp->t_state == TCPS_ESTABLISHED &&
941	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
942	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
943	    ((to.to_flags & TOF_TS) == 0 ||
944	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
945	    /*
946	     * Using the CC option is compulsory if once started:
947	     *   the segment is OK if no T/TCP was negotiated or
948	     *   if the segment has a CC option equal to CCrecv
949	     */
950	    ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
951	     ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
952	    th->th_seq == tp->rcv_nxt &&
953	    tiwin && tiwin == tp->snd_wnd &&
954	    tp->snd_nxt == tp->snd_max) {
955
956		/*
957		 * If last ACK falls within this segment's sequence numbers,
958		 * record the timestamp.
959		 * NOTE that the test is modified according to the latest
960		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
961		 */
962		if ((to.to_flags & TOF_TS) != 0 &&
963		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
964			tp->ts_recent_age = ticks;
965			tp->ts_recent = to.to_tsval;
966		}
967
968		if (tlen == 0) {
969			if (SEQ_GT(th->th_ack, tp->snd_una) &&
970			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
971			    tp->snd_cwnd >= tp->snd_wnd &&
972			    tp->t_dupacks < tcprexmtthresh) {
973				KASSERT(headlocked, ("headlocked"));
974				INP_INFO_WUNLOCK(&tcbinfo);
975				headlocked = 0;
976				/*
977				 * this is a pure ack for outstanding data.
978				 */
979				++tcpstat.tcps_predack;
980				/*
981				 * "bad retransmit" recovery
982				 */
983				if (tp->t_rxtshift == 1 &&
984				    ticks < tp->t_badrxtwin) {
985					tp->snd_cwnd = tp->snd_cwnd_prev;
986					tp->snd_ssthresh =
987					    tp->snd_ssthresh_prev;
988					tp->snd_nxt = tp->snd_max;
989					tp->t_badrxtwin = 0;
990				}
991				if ((to.to_flags & TOF_TS) != 0)
992					tcp_xmit_timer(tp,
993					    ticks - to.to_tsecr + 1);
994				else if (tp->t_rtttime &&
995					    SEQ_GT(th->th_ack, tp->t_rtseq))
996					tcp_xmit_timer(tp,
997							ticks - tp->t_rtttime);
998				tcp_xmit_bandwidth_limit(tp, th->th_ack);
999				acked = th->th_ack - tp->snd_una;
1000				tcpstat.tcps_rcvackpack++;
1001				tcpstat.tcps_rcvackbyte += acked;
1002				sbdrop(&so->so_snd, acked);
1003				tp->snd_una = th->th_ack;
1004				tp->t_dupacks = 0;
1005				m_freem(m);
1006				ND6_HINT(tp); /* some progress has been done */
1007
1008				/*
1009				 * If all outstanding data are acked, stop
1010				 * retransmit timer, otherwise restart timer
1011				 * using current (possibly backed-off) value.
1012				 * If process is waiting for space,
1013				 * wakeup/selwakeup/signal.  If data
1014				 * are ready to send, let tcp_output
1015				 * decide between more output or persist.
1016				 */
1017				if (tp->snd_una == tp->snd_max)
1018					callout_stop(tp->tt_rexmt);
1019				else if (!callout_active(tp->tt_persist))
1020					callout_reset(tp->tt_rexmt,
1021						      tp->t_rxtcur,
1022						      tcp_timer_rexmt, tp);
1023
1024				sowwakeup(so);
1025				if (so->so_snd.sb_cc)
1026					(void) tcp_output(tp);
1027				INP_UNLOCK(inp);
1028				return;
1029			}
1030		} else if (th->th_ack == tp->snd_una &&
1031		    LIST_EMPTY(&tp->t_segq) &&
1032		    tlen <= sbspace(&so->so_rcv)) {
1033			KASSERT(headlocked, ("headlocked"));
1034			INP_INFO_WUNLOCK(&tcbinfo);
1035			headlocked = 0;
1036			/*
1037			 * this is a pure, in-sequence data packet
1038			 * with nothing on the reassembly queue and
1039			 * we have enough buffer space to take it.
1040			 */
1041			++tcpstat.tcps_preddat;
1042			tp->rcv_nxt += tlen;
1043			tcpstat.tcps_rcvpack++;
1044			tcpstat.tcps_rcvbyte += tlen;
1045			ND6_HINT(tp);	/* some progress has been done */
1046			/*
1047			 * Add data to socket buffer.
1048			 */
1049			m_adj(m, drop_hdrlen);	/* delayed header drop */
1050			sbappend(&so->so_rcv, m);
1051			sorwakeup(so);
1052			if (DELAY_ACK(tp)) {
1053	                        callout_reset(tp->tt_delack, tcp_delacktime,
1054	                            tcp_timer_delack, tp);
1055			} else {
1056				tp->t_flags |= TF_ACKNOW;
1057				tcp_output(tp);
1058			}
1059			INP_UNLOCK(inp);
1060			return;
1061		}
1062	}
1063
1064	/*
1065	 * Calculate amount of space in receive window,
1066	 * and then do TCP input processing.
1067	 * Receive window is amount of space in rcv queue,
1068	 * but not less than advertised window.
1069	 */
1070	{ int win;
1071
1072	win = sbspace(&so->so_rcv);
1073	if (win < 0)
1074		win = 0;
1075	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1076	}
1077
1078	switch (tp->t_state) {
1079
1080	/*
1081	 * If the state is SYN_RECEIVED:
1082	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1083	 */
1084	case TCPS_SYN_RECEIVED:
1085		if ((thflags & TH_ACK) &&
1086		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1087		     SEQ_GT(th->th_ack, tp->snd_max))) {
1088				rstreason = BANDLIM_RST_OPENPORT;
1089				goto dropwithreset;
1090		}
1091		break;
1092
1093	/*
1094	 * If the state is SYN_SENT:
1095	 *	if seg contains an ACK, but not for our SYN, drop the input.
1096	 *	if seg contains a RST, then drop the connection.
1097	 *	if seg does not contain SYN, then drop it.
1098	 * Otherwise this is an acceptable SYN segment
1099	 *	initialize tp->rcv_nxt and tp->irs
1100	 *	if seg contains ack then advance tp->snd_una
1101	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1102	 *	arrange for segment to be acked (eventually)
1103	 *	continue processing rest of data/controls, beginning with URG
1104	 */
1105	case TCPS_SYN_SENT:
1106		if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1107			taop = &tao_noncached;
1108			bzero(taop, sizeof(*taop));
1109		}
1110
1111		if ((thflags & TH_ACK) &&
1112		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1113		     SEQ_GT(th->th_ack, tp->snd_max))) {
1114			/*
1115			 * If we have a cached CCsent for the remote host,
1116			 * hence we haven't just crashed and restarted,
1117			 * do not send a RST.  This may be a retransmission
1118			 * from the other side after our earlier ACK was lost.
1119			 * Our new SYN, when it arrives, will serve as the
1120			 * needed ACK.
1121			 */
1122			if (taop->tao_ccsent != 0)
1123				goto drop;
1124			else {
1125				rstreason = BANDLIM_UNLIMITED;
1126				goto dropwithreset;
1127			}
1128		}
1129		if (thflags & TH_RST) {
1130			if (thflags & TH_ACK)
1131				tp = tcp_drop(tp, ECONNREFUSED);
1132			goto drop;
1133		}
1134		if ((thflags & TH_SYN) == 0)
1135			goto drop;
1136		tp->snd_wnd = th->th_win;	/* initial send window */
1137		tp->cc_recv = to.to_cc;		/* foreign CC */
1138
1139		tp->irs = th->th_seq;
1140		tcp_rcvseqinit(tp);
1141		if (thflags & TH_ACK) {
1142			/*
1143			 * Our SYN was acked.  If segment contains CC.ECHO
1144			 * option, check it to make sure this segment really
1145			 * matches our SYN.  If not, just drop it as old
1146			 * duplicate, but send an RST if we're still playing
1147			 * by the old rules.  If no CC.ECHO option, make sure
1148			 * we don't get fooled into using T/TCP.
1149			 */
1150			if (to.to_flags & TOF_CCECHO) {
1151				if (tp->cc_send != to.to_ccecho) {
1152					if (taop->tao_ccsent != 0)
1153						goto drop;
1154					else {
1155						rstreason = BANDLIM_UNLIMITED;
1156						goto dropwithreset;
1157					}
1158				}
1159			} else
1160				tp->t_flags &= ~TF_RCVD_CC;
1161			tcpstat.tcps_connects++;
1162			soisconnected(so);
1163#ifdef MAC
1164			mac_set_socket_peer_from_mbuf(m, so);
1165#endif
1166			/* Do window scaling on this connection? */
1167			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1168				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1169				tp->snd_scale = tp->requested_s_scale;
1170				tp->rcv_scale = tp->request_r_scale;
1171			}
1172			/* Segment is acceptable, update cache if undefined. */
1173			if (taop->tao_ccsent == 0)
1174				taop->tao_ccsent = to.to_ccecho;
1175
1176			tp->rcv_adv += tp->rcv_wnd;
1177			tp->snd_una++;		/* SYN is acked */
1178			/*
1179			 * If there's data, delay ACK; if there's also a FIN
1180			 * ACKNOW will be turned on later.
1181			 */
1182			if (DELAY_ACK(tp) && tlen != 0)
1183                                callout_reset(tp->tt_delack, tcp_delacktime,
1184                                    tcp_timer_delack, tp);
1185			else
1186				tp->t_flags |= TF_ACKNOW;
1187			/*
1188			 * Received <SYN,ACK> in SYN_SENT[*] state.
1189			 * Transitions:
1190			 *	SYN_SENT  --> ESTABLISHED
1191			 *	SYN_SENT* --> FIN_WAIT_1
1192			 */
1193			tp->t_starttime = ticks;
1194			if (tp->t_flags & TF_NEEDFIN) {
1195				tp->t_state = TCPS_FIN_WAIT_1;
1196				tp->t_flags &= ~TF_NEEDFIN;
1197				thflags &= ~TH_SYN;
1198			} else {
1199				tp->t_state = TCPS_ESTABLISHED;
1200				callout_reset(tp->tt_keep, tcp_keepidle,
1201					      tcp_timer_keep, tp);
1202			}
1203		} else {
1204			/*
1205		 	 * Received initial SYN in SYN-SENT[*] state =>
1206		 	 * simultaneous open.  If segment contains CC option
1207		 	 * and there is a cached CC, apply TAO test.
1208		 	 * If it succeeds, connection is * half-synchronized.
1209		 	 * Otherwise, do 3-way handshake:
1210		 	 *        SYN-SENT -> SYN-RECEIVED
1211		 	 *        SYN-SENT* -> SYN-RECEIVED*
1212		 	 * If there was no CC option, clear cached CC value.
1213		 	 */
1214			tp->t_flags |= TF_ACKNOW;
1215			callout_stop(tp->tt_rexmt);
1216			if (to.to_flags & TOF_CC) {
1217				if (taop->tao_cc != 0 &&
1218				    CC_GT(to.to_cc, taop->tao_cc)) {
1219					/*
1220					 * update cache and make transition:
1221					 *        SYN-SENT -> ESTABLISHED*
1222					 *        SYN-SENT* -> FIN-WAIT-1*
1223					 */
1224					taop->tao_cc = to.to_cc;
1225					tp->t_starttime = ticks;
1226					if (tp->t_flags & TF_NEEDFIN) {
1227						tp->t_state = TCPS_FIN_WAIT_1;
1228						tp->t_flags &= ~TF_NEEDFIN;
1229					} else {
1230						tp->t_state = TCPS_ESTABLISHED;
1231						callout_reset(tp->tt_keep,
1232							      tcp_keepidle,
1233							      tcp_timer_keep,
1234							      tp);
1235					}
1236					tp->t_flags |= TF_NEEDSYN;
1237				} else
1238					tp->t_state = TCPS_SYN_RECEIVED;
1239			} else {
1240				/* CC.NEW or no option => invalidate cache */
1241				taop->tao_cc = 0;
1242				tp->t_state = TCPS_SYN_RECEIVED;
1243			}
1244		}
1245
1246trimthenstep6:
1247		/*
1248		 * Advance th->th_seq to correspond to first data byte.
1249		 * If data, trim to stay within window,
1250		 * dropping FIN if necessary.
1251		 */
1252		th->th_seq++;
1253		if (tlen > tp->rcv_wnd) {
1254			todrop = tlen - tp->rcv_wnd;
1255			m_adj(m, -todrop);
1256			tlen = tp->rcv_wnd;
1257			thflags &= ~TH_FIN;
1258			tcpstat.tcps_rcvpackafterwin++;
1259			tcpstat.tcps_rcvbyteafterwin += todrop;
1260		}
1261		tp->snd_wl1 = th->th_seq - 1;
1262		tp->rcv_up = th->th_seq;
1263		/*
1264		 * Client side of transaction: already sent SYN and data.
1265		 * If the remote host used T/TCP to validate the SYN,
1266		 * our data will be ACK'd; if so, enter normal data segment
1267		 * processing in the middle of step 5, ack processing.
1268		 * Otherwise, goto step 6.
1269		 */
1270 		if (thflags & TH_ACK)
1271			goto process_ACK;
1272
1273		goto step6;
1274
1275	/*
1276	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1277	 *	if segment contains a SYN and CC [not CC.NEW] option:
1278	 *              if state == TIME_WAIT and connection duration > MSL,
1279	 *                  drop packet and send RST;
1280	 *
1281	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
1282	 *		    ack the FIN (and data) in retransmission queue.
1283	 *                  Complete close and delete TCPCB.  Then reprocess
1284	 *                  segment, hoping to find new TCPCB in LISTEN state;
1285	 *
1286	 *		else must be old SYN; drop it.
1287	 *      else do normal processing.
1288	 */
1289	case TCPS_LAST_ACK:
1290	case TCPS_CLOSING:
1291	case TCPS_TIME_WAIT:
1292		if ((thflags & TH_SYN) &&
1293		    (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1294			if (tp->t_state == TCPS_TIME_WAIT &&
1295					(ticks - tp->t_starttime) > tcp_msl) {
1296				rstreason = BANDLIM_UNLIMITED;
1297				goto dropwithreset;
1298			}
1299			if (CC_GT(to.to_cc, tp->cc_recv)) {
1300				tp = tcp_close(tp);
1301				goto findpcb;
1302			}
1303			else
1304				goto drop;
1305		}
1306 		break;  /* continue normal processing */
1307	}
1308
1309	/*
1310	 * States other than LISTEN or SYN_SENT.
1311	 * First check the RST flag and sequence number since reset segments
1312	 * are exempt from the timestamp and connection count tests.  This
1313	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1314	 * below which allowed reset segments in half the sequence space
1315	 * to fall though and be processed (which gives forged reset
1316	 * segments with a random sequence number a 50 percent chance of
1317	 * killing a connection).
1318	 * Then check timestamp, if present.
1319	 * Then check the connection count, if present.
1320	 * Then check that at least some bytes of segment are within
1321	 * receive window.  If segment begins before rcv_nxt,
1322	 * drop leading data (and SYN); if nothing left, just ack.
1323	 *
1324	 *
1325	 * If the RST bit is set, check the sequence number to see
1326	 * if this is a valid reset segment.
1327	 * RFC 793 page 37:
1328	 *   In all states except SYN-SENT, all reset (RST) segments
1329	 *   are validated by checking their SEQ-fields.  A reset is
1330	 *   valid if its sequence number is in the window.
1331	 * Note: this does not take into account delayed ACKs, so
1332	 *   we should test against last_ack_sent instead of rcv_nxt.
1333	 *   The sequence number in the reset segment is normally an
1334	 *   echo of our outgoing acknowlegement numbers, but some hosts
1335	 *   send a reset with the sequence number at the rightmost edge
1336	 *   of our receive window, and we have to handle this case.
1337	 * If we have multiple segments in flight, the intial reset
1338	 * segment sequence numbers will be to the left of last_ack_sent,
1339	 * but they will eventually catch up.
1340	 * In any case, it never made sense to trim reset segments to
1341	 * fit the receive window since RFC 1122 says:
1342	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1343	 *
1344	 *    A TCP SHOULD allow a received RST segment to include data.
1345	 *
1346	 *    DISCUSSION
1347	 *         It has been suggested that a RST segment could contain
1348	 *         ASCII text that encoded and explained the cause of the
1349	 *         RST.  No standard has yet been established for such
1350	 *         data.
1351	 *
1352	 * If the reset segment passes the sequence number test examine
1353	 * the state:
1354	 *    SYN_RECEIVED STATE:
1355	 *	If passive open, return to LISTEN state.
1356	 *	If active open, inform user that connection was refused.
1357	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1358	 *	Inform user that connection was reset, and close tcb.
1359	 *    CLOSING, LAST_ACK STATES:
1360	 *	Close the tcb.
1361	 *    TIME_WAIT STATE:
1362	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1363	 *      RFC 1337.
1364	 */
1365	if (thflags & TH_RST) {
1366		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1367		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1368			switch (tp->t_state) {
1369
1370			case TCPS_SYN_RECEIVED:
1371				so->so_error = ECONNREFUSED;
1372				goto close;
1373
1374			case TCPS_ESTABLISHED:
1375			case TCPS_FIN_WAIT_1:
1376			case TCPS_FIN_WAIT_2:
1377			case TCPS_CLOSE_WAIT:
1378				so->so_error = ECONNRESET;
1379			close:
1380				tp->t_state = TCPS_CLOSED;
1381				tcpstat.tcps_drops++;
1382				tp = tcp_close(tp);
1383				break;
1384
1385			case TCPS_CLOSING:
1386			case TCPS_LAST_ACK:
1387				tp = tcp_close(tp);
1388				break;
1389
1390			case TCPS_TIME_WAIT:
1391				break;
1392			}
1393		}
1394		goto drop;
1395	}
1396
1397	/*
1398	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1399	 * and it's less than ts_recent, drop it.
1400	 */
1401	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1402	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1403
1404		/* Check to see if ts_recent is over 24 days old.  */
1405		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1406			/*
1407			 * Invalidate ts_recent.  If this segment updates
1408			 * ts_recent, the age will be reset later and ts_recent
1409			 * will get a valid value.  If it does not, setting
1410			 * ts_recent to zero will at least satisfy the
1411			 * requirement that zero be placed in the timestamp
1412			 * echo reply when ts_recent isn't valid.  The
1413			 * age isn't reset until we get a valid ts_recent
1414			 * because we don't want out-of-order segments to be
1415			 * dropped when ts_recent is old.
1416			 */
1417			tp->ts_recent = 0;
1418		} else {
1419			tcpstat.tcps_rcvduppack++;
1420			tcpstat.tcps_rcvdupbyte += tlen;
1421			tcpstat.tcps_pawsdrop++;
1422			goto dropafterack;
1423		}
1424	}
1425
1426	/*
1427	 * T/TCP mechanism
1428	 *   If T/TCP was negotiated and the segment doesn't have CC,
1429	 *   or if its CC is wrong then drop the segment.
1430	 *   RST segments do not have to comply with this.
1431	 */
1432	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1433	    ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1434 		goto dropafterack;
1435
1436	/*
1437	 * In the SYN-RECEIVED state, validate that the packet belongs to
1438	 * this connection before trimming the data to fit the receive
1439	 * window.  Check the sequence number versus IRS since we know
1440	 * the sequence numbers haven't wrapped.  This is a partial fix
1441	 * for the "LAND" DoS attack.
1442	 */
1443	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1444		rstreason = BANDLIM_RST_OPENPORT;
1445		goto dropwithreset;
1446	}
1447
1448	todrop = tp->rcv_nxt - th->th_seq;
1449	if (todrop > 0) {
1450		if (thflags & TH_SYN) {
1451			thflags &= ~TH_SYN;
1452			th->th_seq++;
1453			if (th->th_urp > 1)
1454				th->th_urp--;
1455			else
1456				thflags &= ~TH_URG;
1457			todrop--;
1458		}
1459		/*
1460		 * Following if statement from Stevens, vol. 2, p. 960.
1461		 */
1462		if (todrop > tlen
1463		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1464			/*
1465			 * Any valid FIN must be to the left of the window.
1466			 * At this point the FIN must be a duplicate or out
1467			 * of sequence; drop it.
1468			 */
1469			thflags &= ~TH_FIN;
1470
1471			/*
1472			 * Send an ACK to resynchronize and drop any data.
1473			 * But keep on processing for RST or ACK.
1474			 */
1475			tp->t_flags |= TF_ACKNOW;
1476			todrop = tlen;
1477			tcpstat.tcps_rcvduppack++;
1478			tcpstat.tcps_rcvdupbyte += todrop;
1479		} else {
1480			tcpstat.tcps_rcvpartduppack++;
1481			tcpstat.tcps_rcvpartdupbyte += todrop;
1482		}
1483		drop_hdrlen += todrop;	/* drop from the top afterwards */
1484		th->th_seq += todrop;
1485		tlen -= todrop;
1486		if (th->th_urp > todrop)
1487			th->th_urp -= todrop;
1488		else {
1489			thflags &= ~TH_URG;
1490			th->th_urp = 0;
1491		}
1492	}
1493
1494	/*
1495	 * If new data are received on a connection after the
1496	 * user processes are gone, then RST the other end.
1497	 */
1498	if ((so->so_state & SS_NOFDREF) &&
1499	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1500		tp = tcp_close(tp);
1501		tcpstat.tcps_rcvafterclose++;
1502		rstreason = BANDLIM_UNLIMITED;
1503		goto dropwithreset;
1504	}
1505
1506	/*
1507	 * If segment ends after window, drop trailing data
1508	 * (and PUSH and FIN); if nothing left, just ACK.
1509	 */
1510	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1511	if (todrop > 0) {
1512		tcpstat.tcps_rcvpackafterwin++;
1513		if (todrop >= tlen) {
1514			tcpstat.tcps_rcvbyteafterwin += tlen;
1515			/*
1516			 * If a new connection request is received
1517			 * while in TIME_WAIT, drop the old connection
1518			 * and start over if the sequence numbers
1519			 * are above the previous ones.
1520			 */
1521			if (thflags & TH_SYN &&
1522			    tp->t_state == TCPS_TIME_WAIT &&
1523			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1524				tp = tcp_close(tp);
1525				goto findpcb;
1526			}
1527			/*
1528			 * If window is closed can only take segments at
1529			 * window edge, and have to drop data and PUSH from
1530			 * incoming segments.  Continue processing, but
1531			 * remember to ack.  Otherwise, drop segment
1532			 * and ack.
1533			 */
1534			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1535				tp->t_flags |= TF_ACKNOW;
1536				tcpstat.tcps_rcvwinprobe++;
1537			} else
1538				goto dropafterack;
1539		} else
1540			tcpstat.tcps_rcvbyteafterwin += todrop;
1541		m_adj(m, -todrop);
1542		tlen -= todrop;
1543		thflags &= ~(TH_PUSH|TH_FIN);
1544	}
1545
1546	/*
1547	 * If last ACK falls within this segment's sequence numbers,
1548	 * record its timestamp.
1549	 * NOTE that the test is modified according to the latest
1550	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1551	 */
1552	if ((to.to_flags & TOF_TS) != 0 &&
1553	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1554		tp->ts_recent_age = ticks;
1555		tp->ts_recent = to.to_tsval;
1556	}
1557
1558	/*
1559	 * If a SYN is in the window, then this is an
1560	 * error and we send an RST and drop the connection.
1561	 */
1562	if (thflags & TH_SYN) {
1563		tp = tcp_drop(tp, ECONNRESET);
1564		rstreason = BANDLIM_UNLIMITED;
1565		goto dropwithreset;
1566	}
1567
1568	/*
1569	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1570	 * flag is on (half-synchronized state), then queue data for
1571	 * later processing; else drop segment and return.
1572	 */
1573	if ((thflags & TH_ACK) == 0) {
1574		if (tp->t_state == TCPS_SYN_RECEIVED ||
1575		    (tp->t_flags & TF_NEEDSYN))
1576			goto step6;
1577		else
1578			goto drop;
1579	}
1580
1581	/*
1582	 * Ack processing.
1583	 */
1584	switch (tp->t_state) {
1585
1586	/*
1587	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1588	 * ESTABLISHED state and continue processing.
1589	 * The ACK was checked above.
1590	 */
1591	case TCPS_SYN_RECEIVED:
1592
1593		tcpstat.tcps_connects++;
1594		soisconnected(so);
1595		/* Do window scaling? */
1596		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1597			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1598			tp->snd_scale = tp->requested_s_scale;
1599			tp->rcv_scale = tp->request_r_scale;
1600		}
1601		/*
1602		 * Upon successful completion of 3-way handshake,
1603		 * update cache.CC if it was undefined, pass any queued
1604		 * data to the user, and advance state appropriately.
1605		 */
1606		if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1607		    taop->tao_cc == 0)
1608			taop->tao_cc = tp->cc_recv;
1609
1610		/*
1611		 * Make transitions:
1612		 *      SYN-RECEIVED  -> ESTABLISHED
1613		 *      SYN-RECEIVED* -> FIN-WAIT-1
1614		 */
1615		tp->t_starttime = ticks;
1616		if (tp->t_flags & TF_NEEDFIN) {
1617			tp->t_state = TCPS_FIN_WAIT_1;
1618			tp->t_flags &= ~TF_NEEDFIN;
1619		} else {
1620			tp->t_state = TCPS_ESTABLISHED;
1621			callout_reset(tp->tt_keep, tcp_keepidle,
1622				      tcp_timer_keep, tp);
1623		}
1624		/*
1625		 * If segment contains data or ACK, will call tcp_reass()
1626		 * later; if not, do so now to pass queued data to user.
1627		 */
1628		if (tlen == 0 && (thflags & TH_FIN) == 0)
1629			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1630			    (struct mbuf *)0);
1631		tp->snd_wl1 = th->th_seq - 1;
1632		/* fall into ... */
1633
1634	/*
1635	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1636	 * ACKs.  If the ack is in the range
1637	 *	tp->snd_una < th->th_ack <= tp->snd_max
1638	 * then advance tp->snd_una to th->th_ack and drop
1639	 * data from the retransmission queue.  If this ACK reflects
1640	 * more up to date window information we update our window information.
1641	 */
1642	case TCPS_ESTABLISHED:
1643	case TCPS_FIN_WAIT_1:
1644	case TCPS_FIN_WAIT_2:
1645	case TCPS_CLOSE_WAIT:
1646	case TCPS_CLOSING:
1647	case TCPS_LAST_ACK:
1648	case TCPS_TIME_WAIT:
1649
1650		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1651			if (tlen == 0 && tiwin == tp->snd_wnd) {
1652				tcpstat.tcps_rcvdupack++;
1653				/*
1654				 * If we have outstanding data (other than
1655				 * a window probe), this is a completely
1656				 * duplicate ack (ie, window info didn't
1657				 * change), the ack is the biggest we've
1658				 * seen and we've seen exactly our rexmt
1659				 * threshhold of them, assume a packet
1660				 * has been dropped and retransmit it.
1661				 * Kludge snd_nxt & the congestion
1662				 * window so we send only this one
1663				 * packet.
1664				 *
1665				 * We know we're losing at the current
1666				 * window size so do congestion avoidance
1667				 * (set ssthresh to half the current window
1668				 * and pull our congestion window back to
1669				 * the new ssthresh).
1670				 *
1671				 * Dup acks mean that packets have left the
1672				 * network (they're now cached at the receiver)
1673				 * so bump cwnd by the amount in the receiver
1674				 * to keep a constant cwnd packets in the
1675				 * network.
1676				 */
1677				if (!callout_active(tp->tt_rexmt) ||
1678				    th->th_ack != tp->snd_una)
1679					tp->t_dupacks = 0;
1680				else if (++tp->t_dupacks == tcprexmtthresh) {
1681					tcp_seq onxt = tp->snd_nxt;
1682					u_int win =
1683					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1684						tp->t_maxseg;
1685					if (tcp_do_newreno &&
1686					    SEQ_LT(th->th_ack,
1687						   tp->snd_recover)) {
1688						/* False retransmit, should not
1689						 * cut window
1690						 */
1691						tp->snd_cwnd += tp->t_maxseg;
1692						tp->t_dupacks = 0;
1693						(void) tcp_output(tp);
1694						goto drop;
1695					}
1696					if (win < 2)
1697						win = 2;
1698					tp->snd_ssthresh = win * tp->t_maxseg;
1699					tp->snd_recover = tp->snd_max;
1700					callout_stop(tp->tt_rexmt);
1701					tp->t_rtttime = 0;
1702					tp->snd_nxt = th->th_ack;
1703					tp->snd_cwnd = tp->t_maxseg;
1704					(void) tcp_output(tp);
1705					tp->snd_cwnd = tp->snd_ssthresh +
1706						tp->t_maxseg * tp->t_dupacks;
1707					if (SEQ_GT(onxt, tp->snd_nxt))
1708						tp->snd_nxt = onxt;
1709					goto drop;
1710				} else if (tp->t_dupacks > tcprexmtthresh) {
1711					tp->snd_cwnd += tp->t_maxseg;
1712					(void) tcp_output(tp);
1713					goto drop;
1714				}
1715			} else
1716				tp->t_dupacks = 0;
1717			break;
1718		}
1719		/*
1720		 * If the congestion window was inflated to account
1721		 * for the other side's cached packets, retract it.
1722		 */
1723		if (tcp_do_newreno) {
1724			int is_partialack = SEQ_LT(th->th_ack, tp->snd_recover);
1725			if (tp->t_dupacks >= tcprexmtthresh) {
1726				if (is_partialack) {
1727					tcp_newreno_partial_ack(tp, th);
1728				} else {
1729					/*
1730					 * Window inflation should have left us
1731					 * with approximately snd_ssthresh
1732					 * outstanding data.
1733					 * But in case we would be inclined to
1734					 * send a burst, better to do it via
1735					 * the slow start mechanism.
1736					 */
1737					if (SEQ_GT(th->th_ack +
1738							tp->snd_ssthresh,
1739						   tp->snd_max))
1740						tp->snd_cwnd = tp->snd_max -
1741								th->th_ack +
1742								tp->t_maxseg;
1743					else
1744						tp->snd_cwnd = tp->snd_ssthresh;
1745				}
1746			}
1747			/*
1748			 * Reset dupacks, except on partial acks in
1749			 *   fast recovery.
1750			 */
1751			if (!(tp->t_dupacks >= tcprexmtthresh && is_partialack))
1752				tp->t_dupacks = 0;
1753                } else {
1754                        if (tp->t_dupacks >= tcprexmtthresh &&
1755                            tp->snd_cwnd > tp->snd_ssthresh)
1756				tp->snd_cwnd = tp->snd_ssthresh;
1757			tp->t_dupacks = 0;
1758                }
1759		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1760			tcpstat.tcps_rcvacktoomuch++;
1761			goto dropafterack;
1762		}
1763		/*
1764		 * If we reach this point, ACK is not a duplicate,
1765		 *     i.e., it ACKs something we sent.
1766		 */
1767		if (tp->t_flags & TF_NEEDSYN) {
1768			/*
1769			 * T/TCP: Connection was half-synchronized, and our
1770			 * SYN has been ACK'd (so connection is now fully
1771			 * synchronized).  Go to non-starred state,
1772			 * increment snd_una for ACK of SYN, and check if
1773			 * we can do window scaling.
1774			 */
1775			tp->t_flags &= ~TF_NEEDSYN;
1776			tp->snd_una++;
1777			/* Do window scaling? */
1778			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1779				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1780				tp->snd_scale = tp->requested_s_scale;
1781				tp->rcv_scale = tp->request_r_scale;
1782			}
1783		}
1784
1785process_ACK:
1786		acked = th->th_ack - tp->snd_una;
1787		tcpstat.tcps_rcvackpack++;
1788		tcpstat.tcps_rcvackbyte += acked;
1789
1790		/*
1791		 * If we just performed our first retransmit, and the ACK
1792		 * arrives within our recovery window, then it was a mistake
1793		 * to do the retransmit in the first place.  Recover our
1794		 * original cwnd and ssthresh, and proceed to transmit where
1795		 * we left off.
1796		 */
1797		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1798			++tcpstat.tcps_sndrexmitbad;
1799			tp->snd_cwnd = tp->snd_cwnd_prev;
1800			tp->snd_ssthresh = tp->snd_ssthresh_prev;
1801			tp->snd_nxt = tp->snd_max;
1802			tp->t_badrxtwin = 0;	/* XXX probably not required */
1803		}
1804
1805		/*
1806		 * If we have a timestamp reply, update smoothed
1807		 * round trip time.  If no timestamp is present but
1808		 * transmit timer is running and timed sequence
1809		 * number was acked, update smoothed round trip time.
1810		 * Since we now have an rtt measurement, cancel the
1811		 * timer backoff (cf., Phil Karn's retransmit alg.).
1812		 * Recompute the initial retransmit timer.
1813		 */
1814		if (to.to_flags & TOF_TS)
1815			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1816		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
1817			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1818		tcp_xmit_bandwidth_limit(tp, th->th_ack);
1819
1820		/*
1821		 * If all outstanding data is acked, stop retransmit
1822		 * timer and remember to restart (more output or persist).
1823		 * If there is more data to be acked, restart retransmit
1824		 * timer, using current (possibly backed-off) value.
1825		 */
1826		if (th->th_ack == tp->snd_max) {
1827			callout_stop(tp->tt_rexmt);
1828			needoutput = 1;
1829		} else if (!callout_active(tp->tt_persist))
1830			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1831				      tcp_timer_rexmt, tp);
1832
1833		/*
1834		 * If no data (only SYN) was ACK'd,
1835		 *    skip rest of ACK processing.
1836		 */
1837		if (acked == 0)
1838			goto step6;
1839
1840		/*
1841		 * When new data is acked, open the congestion window.
1842		 * If the window gives us less than ssthresh packets
1843		 * in flight, open exponentially (maxseg per packet).
1844		 * Otherwise open linearly: maxseg per window
1845		 * (maxseg^2 / cwnd per packet).
1846		 */
1847		{
1848		register u_int cw = tp->snd_cwnd;
1849		register u_int incr = tp->t_maxseg;
1850
1851		if (cw > tp->snd_ssthresh)
1852			incr = incr * incr / cw;
1853		/*
1854		 * If t_dupacks != 0 here, it indicates that we are still
1855		 * in NewReno fast recovery mode, so we leave the congestion
1856		 * window alone.
1857		 */
1858		if (!tcp_do_newreno || tp->t_dupacks == 0)
1859			tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
1860		}
1861		if (acked > so->so_snd.sb_cc) {
1862			tp->snd_wnd -= so->so_snd.sb_cc;
1863			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1864			ourfinisacked = 1;
1865		} else {
1866			sbdrop(&so->so_snd, acked);
1867			tp->snd_wnd -= acked;
1868			ourfinisacked = 0;
1869		}
1870		sowwakeup(so);
1871		tp->snd_una = th->th_ack;
1872		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1873			tp->snd_nxt = tp->snd_una;
1874
1875		switch (tp->t_state) {
1876
1877		/*
1878		 * In FIN_WAIT_1 STATE in addition to the processing
1879		 * for the ESTABLISHED state if our FIN is now acknowledged
1880		 * then enter FIN_WAIT_2.
1881		 */
1882		case TCPS_FIN_WAIT_1:
1883			if (ourfinisacked) {
1884				/*
1885				 * If we can't receive any more
1886				 * data, then closing user can proceed.
1887				 * Starting the timer is contrary to the
1888				 * specification, but if we don't get a FIN
1889				 * we'll hang forever.
1890				 */
1891				if (so->so_state & SS_CANTRCVMORE) {
1892					soisdisconnected(so);
1893					callout_reset(tp->tt_2msl, tcp_maxidle,
1894						      tcp_timer_2msl, tp);
1895				}
1896				tp->t_state = TCPS_FIN_WAIT_2;
1897			}
1898			break;
1899
1900	 	/*
1901		 * In CLOSING STATE in addition to the processing for
1902		 * the ESTABLISHED state if the ACK acknowledges our FIN
1903		 * then enter the TIME-WAIT state, otherwise ignore
1904		 * the segment.
1905		 */
1906		case TCPS_CLOSING:
1907			if (ourfinisacked) {
1908				tp->t_state = TCPS_TIME_WAIT;
1909				tcp_canceltimers(tp);
1910				/* Shorten TIME_WAIT [RFC-1644, p.28] */
1911				if (tp->cc_recv != 0 &&
1912				    (ticks - tp->t_starttime) < tcp_msl)
1913					callout_reset(tp->tt_2msl,
1914						      tp->t_rxtcur *
1915						      TCPTV_TWTRUNC,
1916						      tcp_timer_2msl, tp);
1917				else
1918					callout_reset(tp->tt_2msl, 2 * tcp_msl,
1919						      tcp_timer_2msl, tp);
1920				soisdisconnected(so);
1921			}
1922			break;
1923
1924		/*
1925		 * In LAST_ACK, we may still be waiting for data to drain
1926		 * and/or to be acked, as well as for the ack of our FIN.
1927		 * If our FIN is now acknowledged, delete the TCB,
1928		 * enter the closed state and return.
1929		 */
1930		case TCPS_LAST_ACK:
1931			if (ourfinisacked) {
1932				tp = tcp_close(tp);
1933				goto drop;
1934			}
1935			break;
1936
1937		/*
1938		 * In TIME_WAIT state the only thing that should arrive
1939		 * is a retransmission of the remote FIN.  Acknowledge
1940		 * it and restart the finack timer.
1941		 */
1942		case TCPS_TIME_WAIT:
1943			callout_reset(tp->tt_2msl, 2 * tcp_msl,
1944				      tcp_timer_2msl, tp);
1945			goto dropafterack;
1946		}
1947	}
1948
1949step6:
1950	/*
1951	 * Update window information.
1952	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1953	 */
1954	if ((thflags & TH_ACK) &&
1955	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1956	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1957	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1958		/* keep track of pure window updates */
1959		if (tlen == 0 &&
1960		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1961			tcpstat.tcps_rcvwinupd++;
1962		tp->snd_wnd = tiwin;
1963		tp->snd_wl1 = th->th_seq;
1964		tp->snd_wl2 = th->th_ack;
1965		if (tp->snd_wnd > tp->max_sndwnd)
1966			tp->max_sndwnd = tp->snd_wnd;
1967		needoutput = 1;
1968	}
1969
1970	/*
1971	 * Process segments with URG.
1972	 */
1973	if ((thflags & TH_URG) && th->th_urp &&
1974	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1975		/*
1976		 * This is a kludge, but if we receive and accept
1977		 * random urgent pointers, we'll crash in
1978		 * soreceive.  It's hard to imagine someone
1979		 * actually wanting to send this much urgent data.
1980		 */
1981		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1982			th->th_urp = 0;			/* XXX */
1983			thflags &= ~TH_URG;		/* XXX */
1984			goto dodata;			/* XXX */
1985		}
1986		/*
1987		 * If this segment advances the known urgent pointer,
1988		 * then mark the data stream.  This should not happen
1989		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1990		 * a FIN has been received from the remote side.
1991		 * In these states we ignore the URG.
1992		 *
1993		 * According to RFC961 (Assigned Protocols),
1994		 * the urgent pointer points to the last octet
1995		 * of urgent data.  We continue, however,
1996		 * to consider it to indicate the first octet
1997		 * of data past the urgent section as the original
1998		 * spec states (in one of two places).
1999		 */
2000		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2001			tp->rcv_up = th->th_seq + th->th_urp;
2002			so->so_oobmark = so->so_rcv.sb_cc +
2003			    (tp->rcv_up - tp->rcv_nxt) - 1;
2004			if (so->so_oobmark == 0)
2005				so->so_state |= SS_RCVATMARK;
2006			sohasoutofband(so);
2007			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2008		}
2009		/*
2010		 * Remove out of band data so doesn't get presented to user.
2011		 * This can happen independent of advancing the URG pointer,
2012		 * but if two URG's are pending at once, some out-of-band
2013		 * data may creep in... ick.
2014		 */
2015		if (th->th_urp <= (u_long)tlen
2016#ifdef SO_OOBINLINE
2017		     && (so->so_options & SO_OOBINLINE) == 0
2018#endif
2019		     )
2020			tcp_pulloutofband(so, th, m,
2021				drop_hdrlen);	/* hdr drop is delayed */
2022	} else {
2023		/*
2024		 * If no out of band data is expected,
2025		 * pull receive urgent pointer along
2026		 * with the receive window.
2027		 */
2028		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2029			tp->rcv_up = tp->rcv_nxt;
2030	}
2031dodata:							/* XXX */
2032	KASSERT(headlocked, ("headlocked"));
2033	INP_INFO_WUNLOCK(&tcbinfo);
2034	headlocked = 0;
2035	/*
2036	 * Process the segment text, merging it into the TCP sequencing queue,
2037	 * and arranging for acknowledgment of receipt if necessary.
2038	 * This process logically involves adjusting tp->rcv_wnd as data
2039	 * is presented to the user (this happens in tcp_usrreq.c,
2040	 * case PRU_RCVD).  If a FIN has already been received on this
2041	 * connection then we just ignore the text.
2042	 */
2043	if ((tlen || (thflags & TH_FIN)) &&
2044	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2045		m_adj(m, drop_hdrlen);	/* delayed header drop */
2046		/*
2047		 * Insert segment which includes th into TCP reassembly queue
2048		 * with control block tp.  Set thflags to whether reassembly now
2049		 * includes a segment with FIN.  This handles the common case
2050		 * inline (segment is the next to be received on an established
2051		 * connection, and the queue is empty), avoiding linkage into
2052		 * and removal from the queue and repetition of various
2053		 * conversions.
2054		 * Set DELACK for segments received in order, but ack
2055		 * immediately when segments are out of order (so
2056		 * fast retransmit can work).
2057		 */
2058		if (th->th_seq == tp->rcv_nxt &&
2059		    LIST_EMPTY(&tp->t_segq) &&
2060		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2061			if (DELAY_ACK(tp))
2062				callout_reset(tp->tt_delack, tcp_delacktime,
2063					      tcp_timer_delack, tp);
2064			else
2065				tp->t_flags |= TF_ACKNOW;
2066			tp->rcv_nxt += tlen;
2067			thflags = th->th_flags & TH_FIN;
2068			tcpstat.tcps_rcvpack++;
2069			tcpstat.tcps_rcvbyte += tlen;
2070			ND6_HINT(tp);
2071			sbappend(&so->so_rcv, m);
2072			sorwakeup(so);
2073		} else {
2074			thflags = tcp_reass(tp, th, &tlen, m);
2075			tp->t_flags |= TF_ACKNOW;
2076		}
2077
2078		/*
2079		 * Note the amount of data that peer has sent into
2080		 * our window, in order to estimate the sender's
2081		 * buffer size.
2082		 */
2083		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2084	} else {
2085		m_freem(m);
2086		thflags &= ~TH_FIN;
2087	}
2088
2089	/*
2090	 * If FIN is received ACK the FIN and let the user know
2091	 * that the connection is closing.
2092	 */
2093	if (thflags & TH_FIN) {
2094		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2095			socantrcvmore(so);
2096			/*
2097			 * If connection is half-synchronized
2098			 * (ie NEEDSYN flag on) then delay ACK,
2099			 * so it may be piggybacked when SYN is sent.
2100			 * Otherwise, since we received a FIN then no
2101			 * more input can be expected, send ACK now.
2102			 */
2103			if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2104                                callout_reset(tp->tt_delack, tcp_delacktime,
2105                                    tcp_timer_delack, tp);
2106			else
2107				tp->t_flags |= TF_ACKNOW;
2108			tp->rcv_nxt++;
2109		}
2110		switch (tp->t_state) {
2111
2112	 	/*
2113		 * In SYN_RECEIVED and ESTABLISHED STATES
2114		 * enter the CLOSE_WAIT state.
2115		 */
2116		case TCPS_SYN_RECEIVED:
2117			tp->t_starttime = ticks;
2118			/*FALLTHROUGH*/
2119		case TCPS_ESTABLISHED:
2120			tp->t_state = TCPS_CLOSE_WAIT;
2121			break;
2122
2123	 	/*
2124		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2125		 * enter the CLOSING state.
2126		 */
2127		case TCPS_FIN_WAIT_1:
2128			tp->t_state = TCPS_CLOSING;
2129			break;
2130
2131	 	/*
2132		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2133		 * starting the time-wait timer, turning off the other
2134		 * standard timers.
2135		 */
2136		case TCPS_FIN_WAIT_2:
2137			tp->t_state = TCPS_TIME_WAIT;
2138			tcp_canceltimers(tp);
2139			/* Shorten TIME_WAIT [RFC-1644, p.28] */
2140			if (tp->cc_recv != 0 &&
2141			    (ticks - tp->t_starttime) < tcp_msl) {
2142				callout_reset(tp->tt_2msl,
2143					      tp->t_rxtcur * TCPTV_TWTRUNC,
2144					      tcp_timer_2msl, tp);
2145				/* For transaction client, force ACK now. */
2146				tp->t_flags |= TF_ACKNOW;
2147			}
2148			else
2149				callout_reset(tp->tt_2msl, 2 * tcp_msl,
2150					      tcp_timer_2msl, tp);
2151			soisdisconnected(so);
2152			break;
2153
2154		/*
2155		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2156		 */
2157		case TCPS_TIME_WAIT:
2158			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2159				      tcp_timer_2msl, tp);
2160			break;
2161		}
2162	}
2163#ifdef TCPDEBUG
2164	if (so->so_options & SO_DEBUG)
2165		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2166			  &tcp_savetcp, 0);
2167#endif
2168
2169	/*
2170	 * Return any desired output.
2171	 */
2172	if (needoutput || (tp->t_flags & TF_ACKNOW))
2173		(void) tcp_output(tp);
2174	INP_UNLOCK(inp);
2175	return;
2176
2177dropafterack:
2178	/*
2179	 * Generate an ACK dropping incoming segment if it occupies
2180	 * sequence space, where the ACK reflects our state.
2181	 *
2182	 * We can now skip the test for the RST flag since all
2183	 * paths to this code happen after packets containing
2184	 * RST have been dropped.
2185	 *
2186	 * In the SYN-RECEIVED state, don't send an ACK unless the
2187	 * segment we received passes the SYN-RECEIVED ACK test.
2188	 * If it fails send a RST.  This breaks the loop in the
2189	 * "LAND" DoS attack, and also prevents an ACK storm
2190	 * between two listening ports that have been sent forged
2191	 * SYN segments, each with the source address of the other.
2192	 */
2193	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2194	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2195	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2196		rstreason = BANDLIM_RST_OPENPORT;
2197		goto dropwithreset;
2198	}
2199#ifdef TCPDEBUG
2200	if (so->so_options & SO_DEBUG)
2201		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2202			  &tcp_savetcp, 0);
2203#endif
2204	if (headlocked)
2205		INP_INFO_WUNLOCK(&tcbinfo);
2206	m_freem(m);
2207	tp->t_flags |= TF_ACKNOW;
2208	(void) tcp_output(tp);
2209	INP_UNLOCK(inp);
2210	return;
2211
2212dropwithreset:
2213	/*
2214	 * Generate a RST, dropping incoming segment.
2215	 * Make ACK acceptable to originator of segment.
2216	 * Don't bother to respond if destination was broadcast/multicast.
2217	 */
2218	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2219		goto drop;
2220	if (isipv6) {
2221		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2222		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2223			goto drop;
2224	} else {
2225		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2226		    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2227	    	    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2228	    	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2229			goto drop;
2230	}
2231	/* IPv6 anycast check is done at tcp6_input() */
2232
2233	/*
2234	 * Perform bandwidth limiting.
2235	 */
2236	if (badport_bandlim(rstreason) < 0)
2237		goto drop;
2238
2239#ifdef TCPDEBUG
2240	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2241		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2242			  &tcp_savetcp, 0);
2243#endif
2244
2245	if (tp)
2246		INP_UNLOCK(inp);
2247
2248	if (thflags & TH_ACK)
2249		/* mtod() below is safe as long as hdr dropping is delayed */
2250		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2251			    TH_RST);
2252	else {
2253		if (thflags & TH_SYN)
2254			tlen++;
2255		/* mtod() below is safe as long as hdr dropping is delayed */
2256		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2257			    (tcp_seq)0, TH_RST|TH_ACK);
2258	}
2259	if (headlocked)
2260		INP_INFO_WUNLOCK(&tcbinfo);
2261	return;
2262
2263drop:
2264	/*
2265	 * Drop space held by incoming segment and return.
2266	 */
2267#ifdef TCPDEBUG
2268	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2269		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2270			  &tcp_savetcp, 0);
2271#endif
2272	if (tp)
2273		INP_UNLOCK(inp);
2274	m_freem(m);
2275	if (headlocked)
2276		INP_INFO_WUNLOCK(&tcbinfo);
2277	return;
2278}
2279
2280/*
2281 * Parse TCP options and place in tcpopt.
2282 */
2283static void
2284tcp_dooptions(to, cp, cnt, is_syn)
2285	struct tcpopt *to;
2286	u_char *cp;
2287	int cnt;
2288{
2289	int opt, optlen;
2290
2291	to->to_flags = 0;
2292	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2293		opt = cp[0];
2294		if (opt == TCPOPT_EOL)
2295			break;
2296		if (opt == TCPOPT_NOP)
2297			optlen = 1;
2298		else {
2299			if (cnt < 2)
2300				break;
2301			optlen = cp[1];
2302			if (optlen < 2 || optlen > cnt)
2303				break;
2304		}
2305		switch (opt) {
2306		case TCPOPT_MAXSEG:
2307			if (optlen != TCPOLEN_MAXSEG)
2308				continue;
2309			if (!is_syn)
2310				continue;
2311			to->to_flags |= TOF_MSS;
2312			bcopy((char *)cp + 2,
2313			    (char *)&to->to_mss, sizeof(to->to_mss));
2314			to->to_mss = ntohs(to->to_mss);
2315			break;
2316		case TCPOPT_WINDOW:
2317			if (optlen != TCPOLEN_WINDOW)
2318				continue;
2319			if (! is_syn)
2320				continue;
2321			to->to_flags |= TOF_SCALE;
2322			to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2323			break;
2324		case TCPOPT_TIMESTAMP:
2325			if (optlen != TCPOLEN_TIMESTAMP)
2326				continue;
2327			to->to_flags |= TOF_TS;
2328			bcopy((char *)cp + 2,
2329			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2330			to->to_tsval = ntohl(to->to_tsval);
2331			bcopy((char *)cp + 6,
2332			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2333			to->to_tsecr = ntohl(to->to_tsecr);
2334			break;
2335		case TCPOPT_CC:
2336			if (optlen != TCPOLEN_CC)
2337				continue;
2338			to->to_flags |= TOF_CC;
2339			bcopy((char *)cp + 2,
2340			    (char *)&to->to_cc, sizeof(to->to_cc));
2341			to->to_cc = ntohl(to->to_cc);
2342			break;
2343		case TCPOPT_CCNEW:
2344			if (optlen != TCPOLEN_CC)
2345				continue;
2346			if (!is_syn)
2347				continue;
2348			to->to_flags |= TOF_CCNEW;
2349			bcopy((char *)cp + 2,
2350			    (char *)&to->to_cc, sizeof(to->to_cc));
2351			to->to_cc = ntohl(to->to_cc);
2352			break;
2353		case TCPOPT_CCECHO:
2354			if (optlen != TCPOLEN_CC)
2355				continue;
2356			if (!is_syn)
2357				continue;
2358			to->to_flags |= TOF_CCECHO;
2359			bcopy((char *)cp + 2,
2360			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2361			to->to_ccecho = ntohl(to->to_ccecho);
2362			break;
2363		default:
2364			continue;
2365		}
2366	}
2367}
2368
2369/*
2370 * Pull out of band byte out of a segment so
2371 * it doesn't appear in the user's data queue.
2372 * It is still reflected in the segment length for
2373 * sequencing purposes.
2374 */
2375static void
2376tcp_pulloutofband(so, th, m, off)
2377	struct socket *so;
2378	struct tcphdr *th;
2379	register struct mbuf *m;
2380	int off;		/* delayed to be droped hdrlen */
2381{
2382	int cnt = off + th->th_urp - 1;
2383
2384	while (cnt >= 0) {
2385		if (m->m_len > cnt) {
2386			char *cp = mtod(m, caddr_t) + cnt;
2387			struct tcpcb *tp = sototcpcb(so);
2388
2389			tp->t_iobc = *cp;
2390			tp->t_oobflags |= TCPOOB_HAVEDATA;
2391			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2392			m->m_len--;
2393			if (m->m_flags & M_PKTHDR)
2394				m->m_pkthdr.len--;
2395			return;
2396		}
2397		cnt -= m->m_len;
2398		m = m->m_next;
2399		if (m == 0)
2400			break;
2401	}
2402	panic("tcp_pulloutofband");
2403}
2404
2405/*
2406 * Collect new round-trip time estimate
2407 * and update averages and current timeout.
2408 */
2409static void
2410tcp_xmit_timer(tp, rtt)
2411	register struct tcpcb *tp;
2412	int rtt;
2413{
2414	register int delta;
2415
2416	tcpstat.tcps_rttupdated++;
2417	tp->t_rttupdated++;
2418	if (tp->t_srtt != 0) {
2419		/*
2420		 * srtt is stored as fixed point with 5 bits after the
2421		 * binary point (i.e., scaled by 8).  The following magic
2422		 * is equivalent to the smoothing algorithm in rfc793 with
2423		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2424		 * point).  Adjust rtt to origin 0.
2425		 */
2426		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2427			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2428
2429		if ((tp->t_srtt += delta) <= 0)
2430			tp->t_srtt = 1;
2431
2432		/*
2433		 * We accumulate a smoothed rtt variance (actually, a
2434		 * smoothed mean difference), then set the retransmit
2435		 * timer to smoothed rtt + 4 times the smoothed variance.
2436		 * rttvar is stored as fixed point with 4 bits after the
2437		 * binary point (scaled by 16).  The following is
2438		 * equivalent to rfc793 smoothing with an alpha of .75
2439		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2440		 * rfc793's wired-in beta.
2441		 */
2442		if (delta < 0)
2443			delta = -delta;
2444		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2445		if ((tp->t_rttvar += delta) <= 0)
2446			tp->t_rttvar = 1;
2447		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2448		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2449	} else {
2450		/*
2451		 * No rtt measurement yet - use the unsmoothed rtt.
2452		 * Set the variance to half the rtt (so our first
2453		 * retransmit happens at 3*rtt).
2454		 */
2455		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2456		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2457		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2458	}
2459	tp->t_rtttime = 0;
2460	tp->t_rxtshift = 0;
2461
2462	/*
2463	 * the retransmit should happen at rtt + 4 * rttvar.
2464	 * Because of the way we do the smoothing, srtt and rttvar
2465	 * will each average +1/2 tick of bias.  When we compute
2466	 * the retransmit timer, we want 1/2 tick of rounding and
2467	 * 1 extra tick because of +-1/2 tick uncertainty in the
2468	 * firing of the timer.  The bias will give us exactly the
2469	 * 1.5 tick we need.  But, because the bias is
2470	 * statistical, we have to test that we don't drop below
2471	 * the minimum feasible timer (which is 2 ticks).
2472	 */
2473	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2474		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2475
2476	/*
2477	 * We received an ack for a packet that wasn't retransmitted;
2478	 * it is probably safe to discard any error indications we've
2479	 * received recently.  This isn't quite right, but close enough
2480	 * for now (a route might have failed after we sent a segment,
2481	 * and the return path might not be symmetrical).
2482	 */
2483	tp->t_softerror = 0;
2484}
2485
2486/*
2487 * Determine a reasonable value for maxseg size.
2488 * If the route is known, check route for mtu.
2489 * If none, use an mss that can be handled on the outgoing
2490 * interface without forcing IP to fragment; if bigger than
2491 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2492 * to utilize large mbufs.  If no route is found, route has no mtu,
2493 * or the destination isn't local, use a default, hopefully conservative
2494 * size (usually 512 or the default IP max size, but no more than the mtu
2495 * of the interface), as we can't discover anything about intervening
2496 * gateways or networks.  We also initialize the congestion/slow start
2497 * window to be a single segment if the destination isn't local.
2498 * While looking at the routing entry, we also initialize other path-dependent
2499 * parameters from pre-set or cached values in the routing entry.
2500 *
2501 * Also take into account the space needed for options that we
2502 * send regularly.  Make maxseg shorter by that amount to assure
2503 * that we can send maxseg amount of data even when the options
2504 * are present.  Store the upper limit of the length of options plus
2505 * data in maxopd.
2506 *
2507 * NOTE that this routine is only called when we process an incoming
2508 * segment, for outgoing segments only tcp_mssopt is called.
2509 *
2510 * In case of T/TCP, we call this routine during implicit connection
2511 * setup as well (offer = -1), to initialize maxseg from the cached
2512 * MSS of our peer.
2513 */
2514void
2515tcp_mss(tp, offer)
2516	struct tcpcb *tp;
2517	int offer;
2518{
2519	register struct rtentry *rt;
2520	struct ifnet *ifp;
2521	register int rtt, mss;
2522	u_long bufsize;
2523	struct inpcb *inp = tp->t_inpcb;
2524	struct socket *so;
2525	struct rmxp_tao *taop;
2526	int origoffer = offer;
2527#ifdef INET6
2528	int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2529	size_t min_protoh = isipv6 ?
2530			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2531			    sizeof (struct tcpiphdr);
2532#else
2533	const int isipv6 = 0;
2534	const size_t min_protoh = sizeof (struct tcpiphdr);
2535#endif
2536
2537	if (isipv6)
2538		rt = tcp_rtlookup6(&inp->inp_inc);
2539	else
2540		rt = tcp_rtlookup(&inp->inp_inc);
2541	if (rt == NULL) {
2542		tp->t_maxopd = tp->t_maxseg =
2543				isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2544		return;
2545	}
2546	ifp = rt->rt_ifp;
2547	so = inp->inp_socket;
2548
2549	taop = rmx_taop(rt->rt_rmx);
2550	/*
2551	 * Offer == -1 means that we didn't receive SYN yet,
2552	 * use cached value in that case;
2553	 */
2554	if (offer == -1)
2555		offer = taop->tao_mssopt;
2556	/*
2557	 * Offer == 0 means that there was no MSS on the SYN segment,
2558	 * in this case we use tcp_mssdflt.
2559	 */
2560	if (offer == 0)
2561		offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2562	else
2563		/*
2564		 * Sanity check: make sure that maxopd will be large
2565		 * enough to allow some data on segments even is the
2566		 * all the option space is used (40bytes).  Otherwise
2567		 * funny things may happen in tcp_output.
2568		 */
2569		offer = max(offer, 64);
2570	taop->tao_mssopt = offer;
2571
2572	/*
2573	 * While we're here, check if there's an initial rtt
2574	 * or rttvar.  Convert from the route-table units
2575	 * to scaled multiples of the slow timeout timer.
2576	 */
2577	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2578		/*
2579		 * XXX the lock bit for RTT indicates that the value
2580		 * is also a minimum value; this is subject to time.
2581		 */
2582		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2583			tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2584		tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2585		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2586		tcpstat.tcps_usedrtt++;
2587		if (rt->rt_rmx.rmx_rttvar) {
2588			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2589			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2590			tcpstat.tcps_usedrttvar++;
2591		} else {
2592			/* default variation is +- 1 rtt */
2593			tp->t_rttvar =
2594			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2595		}
2596		TCPT_RANGESET(tp->t_rxtcur,
2597			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2598			      tp->t_rttmin, TCPTV_REXMTMAX);
2599	}
2600	/*
2601	 * if there's an mtu associated with the route, use it
2602	 * else, use the link mtu.
2603	 */
2604	if (rt->rt_rmx.rmx_mtu)
2605		mss = rt->rt_rmx.rmx_mtu - min_protoh;
2606	else {
2607		if (isipv6) {
2608			mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2609				min_protoh;
2610			if (!in6_localaddr(&inp->in6p_faddr))
2611				mss = min(mss, tcp_v6mssdflt);
2612		} else {
2613			mss = ifp->if_mtu - min_protoh;
2614			if (!in_localaddr(inp->inp_faddr))
2615				mss = min(mss, tcp_mssdflt);
2616		}
2617	}
2618	mss = min(mss, offer);
2619	/*
2620	 * maxopd stores the maximum length of data AND options
2621	 * in a segment; maxseg is the amount of data in a normal
2622	 * segment.  We need to store this value (maxopd) apart
2623	 * from maxseg, because now every segment carries options
2624	 * and thus we normally have somewhat less data in segments.
2625	 */
2626	tp->t_maxopd = mss;
2627
2628	/*
2629	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2630	 * were received yet.  In this case we just guess, otherwise
2631	 * we do the same as before T/TCP.
2632	 */
2633 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2634	    (origoffer == -1 ||
2635	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2636		mss -= TCPOLEN_TSTAMP_APPA;
2637 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2638	    (origoffer == -1 ||
2639	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2640		mss -= TCPOLEN_CC_APPA;
2641
2642#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2643		if (mss > MCLBYTES)
2644			mss &= ~(MCLBYTES-1);
2645#else
2646		if (mss > MCLBYTES)
2647			mss = mss / MCLBYTES * MCLBYTES;
2648#endif
2649	/*
2650	 * If there's a pipesize, change the socket buffer
2651	 * to that size.  Make the socket buffers an integral
2652	 * number of mss units; if the mss is larger than
2653	 * the socket buffer, decrease the mss.
2654	 */
2655#ifdef RTV_SPIPE
2656	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2657#endif
2658		bufsize = so->so_snd.sb_hiwat;
2659	if (bufsize < mss)
2660		mss = bufsize;
2661	else {
2662		bufsize = roundup(bufsize, mss);
2663		if (bufsize > sb_max)
2664			bufsize = sb_max;
2665		if (bufsize > so->so_snd.sb_hiwat)
2666			(void)sbreserve(&so->so_snd, bufsize, so, NULL);
2667	}
2668	tp->t_maxseg = mss;
2669
2670#ifdef RTV_RPIPE
2671	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2672#endif
2673		bufsize = so->so_rcv.sb_hiwat;
2674	if (bufsize > mss) {
2675		bufsize = roundup(bufsize, mss);
2676		if (bufsize > sb_max)
2677			bufsize = sb_max;
2678		if (bufsize > so->so_rcv.sb_hiwat)
2679			(void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2680	}
2681
2682	/*
2683	 * Set the slow-start flight size depending on whether this
2684	 * is a local network or not.
2685	 */
2686	if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2687	    (!isipv6 && in_localaddr(inp->inp_faddr)))
2688		tp->snd_cwnd = mss * ss_fltsz_local;
2689	else
2690		tp->snd_cwnd = mss * ss_fltsz;
2691
2692	if (rt->rt_rmx.rmx_ssthresh) {
2693		/*
2694		 * There's some sort of gateway or interface
2695		 * buffer limit on the path.  Use this to set
2696		 * the slow start threshhold, but set the
2697		 * threshold to no less than 2*mss.
2698		 */
2699		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2700		tcpstat.tcps_usedssthresh++;
2701	}
2702}
2703
2704/*
2705 * Determine the MSS option to send on an outgoing SYN.
2706 */
2707int
2708tcp_mssopt(tp)
2709	struct tcpcb *tp;
2710{
2711	struct rtentry *rt;
2712#ifdef INET6
2713	int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2714	size_t min_protoh = isipv6 ?
2715			    sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2716			    sizeof (struct tcpiphdr);
2717#else
2718	const int isipv6 = 0;
2719	const size_t min_protoh = sizeof (struct tcpiphdr);
2720#endif
2721
2722	if (isipv6)
2723		rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2724	else
2725		rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2726	if (rt == NULL)
2727		return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2728
2729	return (rt->rt_ifp->if_mtu - min_protoh);
2730}
2731
2732
2733/*
2734 * On a partial ack arrives, force the retransmission of the
2735 * next unacknowledged segment.  Do not clear tp->t_dupacks.
2736 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2737 * be started again.
2738 */
2739static void
2740tcp_newreno_partial_ack(tp, th)
2741	struct tcpcb *tp;
2742	struct tcphdr *th;
2743{
2744	tcp_seq onxt = tp->snd_nxt;
2745	u_long  ocwnd = tp->snd_cwnd;
2746
2747	callout_stop(tp->tt_rexmt);
2748	tp->t_rtttime = 0;
2749	tp->snd_nxt = th->th_ack;
2750	/*
2751	 * Set snd_cwnd to one segment beyond acknowledged offset.
2752	 * (tp->snd_una has not yet been updated when this function is called.)
2753	 */
2754	tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2755	(void) tcp_output(tp);
2756	tp->snd_cwnd = ocwnd;
2757	if (SEQ_GT(onxt, tp->snd_nxt))
2758		tp->snd_nxt = onxt;
2759	/*
2760	 * Partial window deflation.  Relies on fact that tp->snd_una
2761	 * not updated yet.
2762	 */
2763	tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2764}
2765