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