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