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