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