tcp_input.c revision 35421
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 *	$Id: tcp_input.c,v 1.73 1998/04/17 22:36:59 des Exp $
35 */
36
37#include "opt_tcpdebug.h"
38
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/kernel.h>
42#include <sys/sysctl.h>
43#include <sys/malloc.h>
44#include <sys/mbuf.h>
45#include <sys/proc.h>		/* for proc0 declaration */
46#include <sys/protosw.h>
47#include <sys/socket.h>
48#include <sys/socketvar.h>
49#include <sys/syslog.h>
50
51#include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
52
53#include <net/if.h>
54#include <net/route.h>
55
56#include <netinet/in.h>
57#include <netinet/in_systm.h>
58#include <netinet/ip.h>
59#include <netinet/in_pcb.h>
60#include <netinet/ip_var.h>
61#include <netinet/tcp.h>
62#include <netinet/tcp_fsm.h>
63#include <netinet/tcp_seq.h>
64#include <netinet/tcp_timer.h>
65#include <netinet/tcp_var.h>
66#include <netinet/tcpip.h>
67#ifdef TCPDEBUG
68#include <netinet/tcp_debug.h>
69static struct	tcpiphdr tcp_saveti;
70#endif
71
72static int	tcprexmtthresh = 3;
73tcp_seq	tcp_iss;
74tcp_cc	tcp_ccgen;
75
76struct	tcpstat tcpstat;
77SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats,
78	CTLFLAG_RD, &tcpstat , tcpstat, "");
79
80static int log_in_vain = 0;
81SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
82	&log_in_vain, 0, "");
83
84int tcp_delack_enabled = 1;
85SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
86	&tcp_delack_enabled, 0, "");
87
88u_long	tcp_now;
89struct inpcbhead tcb;
90struct inpcbinfo tcbinfo;
91
92static void	 tcp_dooptions __P((struct tcpcb *,
93	    u_char *, int, struct tcpiphdr *, struct tcpopt *));
94static void	 tcp_pulloutofband __P((struct socket *,
95	    struct tcpiphdr *, struct mbuf *));
96static int	 tcp_reass __P((struct tcpcb *, struct tcpiphdr *, struct mbuf *));
97static void	 tcp_xmit_timer __P((struct tcpcb *, int));
98
99
100/*
101 * Insert segment ti into reassembly queue of tcp with
102 * control block tp.  Return TH_FIN if reassembly now includes
103 * a segment with FIN.  The macro form does the common case inline
104 * (segment is the next to be received on an established connection,
105 * and the queue is empty), avoiding linkage into and removal
106 * from the queue and repetition of various conversions.
107 * Set DELACK for segments received in order, but ack immediately
108 * when segments are out of order (so fast retransmit can work).
109 */
110#define	TCP_REASS(tp, ti, m, so, flags) { \
111	if ((ti)->ti_seq == (tp)->rcv_nxt && \
112	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
113	    (tp)->t_state == TCPS_ESTABLISHED) { \
114		if (tcp_delack_enabled) \
115			tp->t_flags |= TF_DELACK; \
116		else \
117			tp->t_flags |= TF_ACKNOW; \
118		(tp)->rcv_nxt += (ti)->ti_len; \
119		flags = (ti)->ti_flags & TH_FIN; \
120		tcpstat.tcps_rcvpack++;\
121		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
122		sbappend(&(so)->so_rcv, (m)); \
123		sorwakeup(so); \
124	} else { \
125		(flags) = tcp_reass((tp), (ti), (m)); \
126		tp->t_flags |= TF_ACKNOW; \
127	} \
128}
129
130static int
131tcp_reass(tp, ti, m)
132	register struct tcpcb *tp;
133	register struct tcpiphdr *ti;
134	struct mbuf *m;
135{
136	register struct tcpiphdr *q;
137	struct socket *so = tp->t_inpcb->inp_socket;
138	int flags;
139
140	/*
141	 * Call with ti==0 after become established to
142	 * force pre-ESTABLISHED data up to user socket.
143	 */
144	if (ti == 0)
145		goto present;
146
147	/*
148	 * Find a segment which begins after this one does.
149	 */
150	for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
151	    q = (struct tcpiphdr *)q->ti_next)
152		if (SEQ_GT(q->ti_seq, ti->ti_seq))
153			break;
154
155	/*
156	 * If there is a preceding segment, it may provide some of
157	 * our data already.  If so, drop the data from the incoming
158	 * segment.  If it provides all of our data, drop us.
159	 */
160	if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
161		register int i;
162		q = (struct tcpiphdr *)q->ti_prev;
163		/* conversion to int (in i) handles seq wraparound */
164		i = q->ti_seq + q->ti_len - ti->ti_seq;
165		if (i > 0) {
166			if (i >= ti->ti_len) {
167				tcpstat.tcps_rcvduppack++;
168				tcpstat.tcps_rcvdupbyte += ti->ti_len;
169				m_freem(m);
170				/*
171				 * Try to present any queued data
172				 * at the left window edge to the user.
173				 * This is needed after the 3-WHS
174				 * completes.
175				 */
176				goto present;	/* ??? */
177			}
178			m_adj(m, i);
179			ti->ti_len -= i;
180			ti->ti_seq += i;
181		}
182		q = (struct tcpiphdr *)(q->ti_next);
183	}
184	tcpstat.tcps_rcvoopack++;
185	tcpstat.tcps_rcvoobyte += ti->ti_len;
186	REASS_MBUF(ti) = m;		/* XXX */
187
188	/*
189	 * While we overlap succeeding segments trim them or,
190	 * if they are completely covered, dequeue them.
191	 */
192	while (q != (struct tcpiphdr *)tp) {
193		register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
194		if (i <= 0)
195			break;
196		if (i < q->ti_len) {
197			q->ti_seq += i;
198			q->ti_len -= i;
199			m_adj(REASS_MBUF(q), i);
200			break;
201		}
202		q = (struct tcpiphdr *)q->ti_next;
203		m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
204		remque(q->ti_prev);
205		m_freem(m);
206	}
207
208	/*
209	 * Stick new segment in its place.
210	 */
211	insque(ti, q->ti_prev);
212
213present:
214	/*
215	 * Present data to user, advancing rcv_nxt through
216	 * completed sequence space.
217	 */
218	if (!TCPS_HAVEESTABLISHED(tp->t_state))
219		return (0);
220	ti = tp->seg_next;
221	if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
222		return (0);
223	do {
224		tp->rcv_nxt += ti->ti_len;
225		flags = ti->ti_flags & TH_FIN;
226		remque(ti);
227		m = REASS_MBUF(ti);
228		ti = (struct tcpiphdr *)ti->ti_next;
229		if (so->so_state & SS_CANTRCVMORE)
230			m_freem(m);
231		else
232			sbappend(&so->so_rcv, m);
233	} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
234	sorwakeup(so);
235	return (flags);
236}
237
238/*
239 * TCP input routine, follows pages 65-76 of the
240 * protocol specification dated September, 1981 very closely.
241 */
242void
243tcp_input(m, iphlen)
244	register struct mbuf *m;
245	int iphlen;
246{
247	register struct tcpiphdr *ti;
248	register struct inpcb *inp;
249	u_char *optp = NULL;
250	int optlen = 0;
251	int len, tlen, off;
252	register struct tcpcb *tp = 0;
253	register int tiflags;
254	struct socket *so = 0;
255	int todrop, acked, ourfinisacked, needoutput = 0;
256	struct in_addr laddr;
257	int dropsocket = 0;
258	int iss = 0;
259	u_long tiwin;
260	struct tcpopt to;		/* options in this segment */
261	struct rmxp_tao *taop;		/* pointer to our TAO cache entry */
262	struct rmxp_tao	tao_noncached;	/* in case there's no cached entry */
263#ifdef TCPDEBUG
264	short ostate = 0;
265#endif
266
267	bzero((char *)&to, sizeof(to));
268
269	tcpstat.tcps_rcvtotal++;
270	/*
271	 * Get IP and TCP header together in first mbuf.
272	 * Note: IP leaves IP header in first mbuf.
273	 */
274	ti = mtod(m, struct tcpiphdr *);
275	if (iphlen > sizeof (struct ip))
276		ip_stripoptions(m, (struct mbuf *)0);
277	if (m->m_len < sizeof (struct tcpiphdr)) {
278		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
279			tcpstat.tcps_rcvshort++;
280			return;
281		}
282		ti = mtod(m, struct tcpiphdr *);
283	}
284
285	/*
286	 * Checksum extended TCP header and data.
287	 */
288	tlen = ((struct ip *)ti)->ip_len;
289	len = sizeof (struct ip) + tlen;
290	ti->ti_next = ti->ti_prev = 0;
291	ti->ti_x1 = 0;
292	ti->ti_len = (u_short)tlen;
293	HTONS(ti->ti_len);
294	ti->ti_sum = in_cksum(m, len);
295	if (ti->ti_sum) {
296		tcpstat.tcps_rcvbadsum++;
297		goto drop;
298	}
299
300	/*
301	 * Check that TCP offset makes sense,
302	 * pull out TCP options and adjust length.		XXX
303	 */
304	off = ti->ti_off << 2;
305	if (off < sizeof (struct tcphdr) || off > tlen) {
306		tcpstat.tcps_rcvbadoff++;
307		goto drop;
308	}
309	tlen -= off;
310	ti->ti_len = tlen;
311	if (off > sizeof (struct tcphdr)) {
312		if (m->m_len < sizeof(struct ip) + off) {
313			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
314				tcpstat.tcps_rcvshort++;
315				return;
316			}
317			ti = mtod(m, struct tcpiphdr *);
318		}
319		optlen = off - sizeof (struct tcphdr);
320		optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
321	}
322	tiflags = ti->ti_flags;
323
324	/*
325	 * Convert TCP protocol specific fields to host format.
326	 */
327	NTOHL(ti->ti_seq);
328	NTOHL(ti->ti_ack);
329	NTOHS(ti->ti_win);
330	NTOHS(ti->ti_urp);
331
332	/*
333	 * Drop TCP, IP headers and TCP options.
334	 */
335	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
336	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
337
338	/*
339	 * Locate pcb for segment.
340	 */
341findpcb:
342	inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
343	    ti->ti_dst, ti->ti_dport, 1);
344
345	/*
346	 * If the state is CLOSED (i.e., TCB does not exist) then
347	 * all data in the incoming segment is discarded.
348	 * If the TCB exists but is in CLOSED state, it is embryonic,
349	 * but should either do a listen or a connect soon.
350	 */
351	if (inp == NULL) {
352		if (log_in_vain && tiflags & TH_SYN) {
353			char buf[4*sizeof "123"];
354
355			strcpy(buf, inet_ntoa(ti->ti_dst));
356			log(LOG_INFO,
357			    "Connection attempt to TCP %s:%d from %s:%d\n",
358			    buf, ntohs(ti->ti_dport), inet_ntoa(ti->ti_src),
359			    ntohs(ti->ti_sport));
360		}
361		goto dropwithreset;
362	}
363	tp = intotcpcb(inp);
364	if (tp == 0)
365		goto dropwithreset;
366	if (tp->t_state == TCPS_CLOSED)
367		goto drop;
368
369	/* Unscale the window into a 32-bit value. */
370	if ((tiflags & TH_SYN) == 0)
371		tiwin = ti->ti_win << tp->snd_scale;
372	else
373		tiwin = ti->ti_win;
374
375	so = inp->inp_socket;
376	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
377#ifdef TCPDEBUG
378		if (so->so_options & SO_DEBUG) {
379			ostate = tp->t_state;
380			tcp_saveti = *ti;
381		}
382#endif
383		if (so->so_options & SO_ACCEPTCONN) {
384			register struct tcpcb *tp0 = tp;
385			struct socket *so2;
386			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
387				/*
388				 * Note: dropwithreset makes sure we don't
389				 * send a RST in response to a RST.
390				 */
391				if (tiflags & TH_ACK) {
392					tcpstat.tcps_badsyn++;
393					goto dropwithreset;
394				}
395				goto drop;
396			}
397			so2 = sonewconn(so, 0);
398			if (so2 == 0) {
399				tcpstat.tcps_listendrop++;
400				so2 = sodropablereq(so);
401				if (so2) {
402					tcp_drop(sototcpcb(so2), ETIMEDOUT);
403					so2 = sonewconn(so, 0);
404				}
405				if (!so2)
406					goto drop;
407			}
408			so = so2;
409			/*
410			 * This is ugly, but ....
411			 *
412			 * Mark socket as temporary until we're
413			 * committed to keeping it.  The code at
414			 * ``drop'' and ``dropwithreset'' check the
415			 * flag dropsocket to see if the temporary
416			 * socket created here should be discarded.
417			 * We mark the socket as discardable until
418			 * we're committed to it below in TCPS_LISTEN.
419			 */
420			dropsocket++;
421			inp = (struct inpcb *)so->so_pcb;
422			inp->inp_laddr = ti->ti_dst;
423			inp->inp_lport = ti->ti_dport;
424			if (in_pcbinshash(inp) != 0) {
425				/*
426				 * Undo the assignments above if we failed to put
427				 * the PCB on the hash lists.
428				 */
429				inp->inp_laddr.s_addr = INADDR_ANY;
430				inp->inp_lport = 0;
431				goto drop;
432			}
433			inp->inp_options = ip_srcroute();
434			tp = intotcpcb(inp);
435			tp->t_state = TCPS_LISTEN;
436			tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
437
438			/* Compute proper scaling value from buffer space */
439			while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
440			   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
441				tp->request_r_scale++;
442		}
443	}
444
445	/*
446	 * Segment received on connection.
447	 * Reset idle time and keep-alive timer.
448	 */
449	tp->t_idle = 0;
450	if (TCPS_HAVEESTABLISHED(tp->t_state))
451		tp->t_timer[TCPT_KEEP] = tcp_keepidle;
452
453	/*
454	 * Process options if not in LISTEN state,
455	 * else do it below (after getting remote address).
456	 */
457	if (tp->t_state != TCPS_LISTEN)
458		tcp_dooptions(tp, optp, optlen, ti, &to);
459
460	/*
461	 * Header prediction: check for the two common cases
462	 * of a uni-directional data xfer.  If the packet has
463	 * no control flags, is in-sequence, the window didn't
464	 * change and we're not retransmitting, it's a
465	 * candidate.  If the length is zero and the ack moved
466	 * forward, we're the sender side of the xfer.  Just
467	 * free the data acked & wake any higher level process
468	 * that was blocked waiting for space.  If the length
469	 * is non-zero and the ack didn't move, we're the
470	 * receiver side.  If we're getting packets in-order
471	 * (the reassembly queue is empty), add the data to
472	 * the socket buffer and note that we need a delayed ack.
473	 * Make sure that the hidden state-flags are also off.
474	 * Since we check for TCPS_ESTABLISHED above, it can only
475	 * be TH_NEEDSYN.
476	 */
477	if (tp->t_state == TCPS_ESTABLISHED &&
478	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
479	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
480	    ((to.to_flag & TOF_TS) == 0 ||
481	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
482	    /*
483	     * Using the CC option is compulsory if once started:
484	     *   the segment is OK if no T/TCP was negotiated or
485	     *   if the segment has a CC option equal to CCrecv
486	     */
487	    ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
488	     (to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv) &&
489	    ti->ti_seq == tp->rcv_nxt &&
490	    tiwin && tiwin == tp->snd_wnd &&
491	    tp->snd_nxt == tp->snd_max) {
492
493		/*
494		 * If last ACK falls within this segment's sequence numbers,
495		 * record the timestamp.
496		 * NOTE that the test is modified according to the latest
497		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
498		 */
499		if ((to.to_flag & TOF_TS) != 0 &&
500		   SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
501			tp->ts_recent_age = tcp_now;
502			tp->ts_recent = to.to_tsval;
503		}
504
505		if (ti->ti_len == 0) {
506			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
507			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
508			    tp->snd_cwnd >= tp->snd_wnd &&
509			    tp->t_dupacks < tcprexmtthresh) {
510				/*
511				 * this is a pure ack for outstanding data.
512				 */
513				++tcpstat.tcps_predack;
514				if ((to.to_flag & TOF_TS) != 0)
515					tcp_xmit_timer(tp,
516					    tcp_now - to.to_tsecr + 1);
517				else if (tp->t_rtt &&
518					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
519					tcp_xmit_timer(tp, tp->t_rtt);
520				acked = ti->ti_ack - tp->snd_una;
521				tcpstat.tcps_rcvackpack++;
522				tcpstat.tcps_rcvackbyte += acked;
523				sbdrop(&so->so_snd, acked);
524				tp->snd_una = ti->ti_ack;
525				m_freem(m);
526
527				/*
528				 * If all outstanding data are acked, stop
529				 * retransmit timer, otherwise restart timer
530				 * using current (possibly backed-off) value.
531				 * If process is waiting for space,
532				 * wakeup/selwakeup/signal.  If data
533				 * are ready to send, let tcp_output
534				 * decide between more output or persist.
535				 */
536				if (tp->snd_una == tp->snd_max)
537					tp->t_timer[TCPT_REXMT] = 0;
538				else if (tp->t_timer[TCPT_PERSIST] == 0)
539					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
540
541				if (so->so_snd.sb_flags & SB_NOTIFY)
542					sowwakeup(so);
543				if (so->so_snd.sb_cc)
544					(void) tcp_output(tp);
545				return;
546			}
547		} else if (ti->ti_ack == tp->snd_una &&
548		    tp->seg_next == (struct tcpiphdr *)tp &&
549		    ti->ti_len <= sbspace(&so->so_rcv)) {
550			/*
551			 * this is a pure, in-sequence data packet
552			 * with nothing on the reassembly queue and
553			 * we have enough buffer space to take it.
554			 */
555			++tcpstat.tcps_preddat;
556			tp->rcv_nxt += ti->ti_len;
557			tcpstat.tcps_rcvpack++;
558			tcpstat.tcps_rcvbyte += ti->ti_len;
559			/*
560			 * Add data to socket buffer.
561			 */
562			sbappend(&so->so_rcv, m);
563			sorwakeup(so);
564			if (tcp_delack_enabled) {
565				tp->t_flags |= TF_DELACK;
566			} else {
567				tp->t_flags |= TF_ACKNOW;
568				tcp_output(tp);
569			}
570			return;
571		}
572	}
573
574	/*
575	 * Calculate amount of space in receive window,
576	 * and then do TCP input processing.
577	 * Receive window is amount of space in rcv queue,
578	 * but not less than advertised window.
579	 */
580	{ int win;
581
582	win = sbspace(&so->so_rcv);
583	if (win < 0)
584		win = 0;
585	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
586	}
587
588	switch (tp->t_state) {
589
590	/*
591	 * If the state is LISTEN then ignore segment if it contains an RST.
592	 * If the segment contains an ACK then it is bad and send a RST.
593	 * If it does not contain a SYN then it is not interesting; drop it.
594	 * If it is from this socket, drop it, it must be forged.
595	 * Don't bother responding if the destination was a broadcast.
596	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
597	 * tp->iss, and send a segment:
598	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
599	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
600	 * Fill in remote peer address fields if not previously specified.
601	 * Enter SYN_RECEIVED state, and process any other fields of this
602	 * segment in this state.
603	 */
604	case TCPS_LISTEN: {
605		register struct sockaddr_in *sin;
606
607		if (tiflags & TH_RST)
608			goto drop;
609		if (tiflags & TH_ACK)
610			goto dropwithreset;
611		if ((tiflags & TH_SYN) == 0)
612			goto drop;
613		if ((ti->ti_dport == ti->ti_sport) &&
614		    (ti->ti_dst.s_addr == ti->ti_src.s_addr))
615			goto drop;
616		/*
617		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
618		 * in_broadcast() should never return true on a received
619		 * packet with M_BCAST not set.
620		 */
621		if (m->m_flags & (M_BCAST|M_MCAST) ||
622		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
623			goto drop;
624		MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
625		       M_NOWAIT);
626		if (sin == NULL)
627			goto drop;
628		sin->sin_family = AF_INET;
629		sin->sin_len = sizeof(*sin);
630		sin->sin_addr = ti->ti_src;
631		sin->sin_port = ti->ti_sport;
632		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
633		laddr = inp->inp_laddr;
634		if (inp->inp_laddr.s_addr == INADDR_ANY)
635			inp->inp_laddr = ti->ti_dst;
636		if (in_pcbconnect(inp, (struct sockaddr *)sin, &proc0)) {
637			inp->inp_laddr = laddr;
638			FREE(sin, M_SONAME);
639			goto drop;
640		}
641		FREE(sin, M_SONAME);
642		tp->t_template = tcp_template(tp);
643		if (tp->t_template == 0) {
644			tp = tcp_drop(tp, ENOBUFS);
645			dropsocket = 0;		/* socket is already gone */
646			goto drop;
647		}
648		if ((taop = tcp_gettaocache(inp)) == NULL) {
649			taop = &tao_noncached;
650			bzero(taop, sizeof(*taop));
651		}
652		tcp_dooptions(tp, optp, optlen, ti, &to);
653		if (iss)
654			tp->iss = iss;
655		else
656			tp->iss = tcp_iss;
657		tcp_iss += TCP_ISSINCR/4;
658		tp->irs = ti->ti_seq;
659		tcp_sendseqinit(tp);
660		tcp_rcvseqinit(tp);
661		/*
662		 * Initialization of the tcpcb for transaction;
663		 *   set SND.WND = SEG.WND,
664		 *   initialize CCsend and CCrecv.
665		 */
666		tp->snd_wnd = tiwin;	/* initial send-window */
667		tp->cc_send = CC_INC(tcp_ccgen);
668		tp->cc_recv = to.to_cc;
669		/*
670		 * Perform TAO test on incoming CC (SEG.CC) option, if any.
671		 * - compare SEG.CC against cached CC from the same host,
672		 *	if any.
673		 * - if SEG.CC > chached value, SYN must be new and is accepted
674		 *	immediately: save new CC in the cache, mark the socket
675		 *	connected, enter ESTABLISHED state, turn on flag to
676		 *	send a SYN in the next segment.
677		 *	A virtual advertised window is set in rcv_adv to
678		 *	initialize SWS prevention.  Then enter normal segment
679		 *	processing: drop SYN, process data and FIN.
680		 * - otherwise do a normal 3-way handshake.
681		 */
682		if ((to.to_flag & TOF_CC) != 0) {
683		    if (taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
684			taop->tao_cc = to.to_cc;
685			tp->t_state = TCPS_ESTABLISHED;
686
687			/*
688			 * If there is a FIN, or if there is data and the
689			 * connection is local, then delay SYN,ACK(SYN) in
690			 * the hope of piggy-backing it on a response
691			 * segment.  Otherwise must send ACK now in case
692			 * the other side is slow starting.
693			 */
694			if (tcp_delack_enabled && ((tiflags & TH_FIN) || (ti->ti_len != 0 &&
695			    in_localaddr(inp->inp_faddr))))
696				tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
697			else
698				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
699
700			/*
701			 * Limit the `virtual advertised window' to TCP_MAXWIN
702			 * here.  Even if we requested window scaling, it will
703			 * become effective only later when our SYN is acked.
704			 */
705			tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
706			tcpstat.tcps_connects++;
707			soisconnected(so);
708			tp->t_timer[TCPT_KEEP] = tcp_keepinit;
709			dropsocket = 0;		/* committed to socket */
710			tcpstat.tcps_accepts++;
711			goto trimthenstep6;
712		    }
713		/* else do standard 3-way handshake */
714		} else {
715		    /*
716		     * No CC option, but maybe CC.NEW:
717		     *   invalidate cached value.
718		     */
719		     taop->tao_cc = 0;
720		}
721		/*
722		 * TAO test failed or there was no CC option,
723		 *    do a standard 3-way handshake.
724		 */
725		tp->t_flags |= TF_ACKNOW;
726		tp->t_state = TCPS_SYN_RECEIVED;
727		tp->t_timer[TCPT_KEEP] = tcp_keepinit;
728		dropsocket = 0;		/* committed to socket */
729		tcpstat.tcps_accepts++;
730		goto trimthenstep6;
731		}
732
733	/*
734	 * If the state is SYN_RECEIVED:
735	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
736	 */
737	case TCPS_SYN_RECEIVED:
738		if ((tiflags & TH_ACK) &&
739		    (SEQ_LEQ(ti->ti_ack, tp->snd_una) ||
740		     SEQ_GT(ti->ti_ack, tp->snd_max)))
741				goto dropwithreset;
742		break;
743
744	/*
745	 * If the state is SYN_SENT:
746	 *	if seg contains an ACK, but not for our SYN, drop the input.
747	 *	if seg contains a RST, then drop the connection.
748	 *	if seg does not contain SYN, then drop it.
749	 * Otherwise this is an acceptable SYN segment
750	 *	initialize tp->rcv_nxt and tp->irs
751	 *	if seg contains ack then advance tp->snd_una
752	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
753	 *	arrange for segment to be acked (eventually)
754	 *	continue processing rest of data/controls, beginning with URG
755	 */
756	case TCPS_SYN_SENT:
757		if ((taop = tcp_gettaocache(inp)) == NULL) {
758			taop = &tao_noncached;
759			bzero(taop, sizeof(*taop));
760		}
761
762		if ((tiflags & TH_ACK) &&
763		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
764		     SEQ_GT(ti->ti_ack, tp->snd_max))) {
765			/*
766			 * If we have a cached CCsent for the remote host,
767			 * hence we haven't just crashed and restarted,
768			 * do not send a RST.  This may be a retransmission
769			 * from the other side after our earlier ACK was lost.
770			 * Our new SYN, when it arrives, will serve as the
771			 * needed ACK.
772			 */
773			if (taop->tao_ccsent != 0)
774				goto drop;
775			else
776				goto dropwithreset;
777		}
778		if (tiflags & TH_RST) {
779			if (tiflags & TH_ACK)
780				tp = tcp_drop(tp, ECONNREFUSED);
781			goto drop;
782		}
783		if ((tiflags & TH_SYN) == 0)
784			goto drop;
785		tp->snd_wnd = ti->ti_win;	/* initial send window */
786		tp->cc_recv = to.to_cc;		/* foreign CC */
787
788		tp->irs = ti->ti_seq;
789		tcp_rcvseqinit(tp);
790		if (tiflags & TH_ACK) {
791			/*
792			 * Our SYN was acked.  If segment contains CC.ECHO
793			 * option, check it to make sure this segment really
794			 * matches our SYN.  If not, just drop it as old
795			 * duplicate, but send an RST if we're still playing
796			 * by the old rules.  If no CC.ECHO option, make sure
797			 * we don't get fooled into using T/TCP.
798			 */
799			if (to.to_flag & TOF_CCECHO) {
800				if (tp->cc_send != to.to_ccecho)
801					if (taop->tao_ccsent != 0)
802						goto drop;
803					else
804						goto dropwithreset;
805			} else
806				tp->t_flags &= ~TF_RCVD_CC;
807			tcpstat.tcps_connects++;
808			soisconnected(so);
809			/* Do window scaling on this connection? */
810			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
811				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
812				tp->snd_scale = tp->requested_s_scale;
813				tp->rcv_scale = tp->request_r_scale;
814			}
815			/* Segment is acceptable, update cache if undefined. */
816			if (taop->tao_ccsent == 0)
817				taop->tao_ccsent = to.to_ccecho;
818
819			tp->rcv_adv += tp->rcv_wnd;
820			tp->snd_una++;		/* SYN is acked */
821			/*
822			 * If there's data, delay ACK; if there's also a FIN
823			 * ACKNOW will be turned on later.
824			 */
825			if (tcp_delack_enabled && ti->ti_len != 0)
826				tp->t_flags |= TF_DELACK;
827			else
828				tp->t_flags |= TF_ACKNOW;
829			/*
830			 * Received <SYN,ACK> in SYN_SENT[*] state.
831			 * Transitions:
832			 *	SYN_SENT  --> ESTABLISHED
833			 *	SYN_SENT* --> FIN_WAIT_1
834			 */
835			if (tp->t_flags & TF_NEEDFIN) {
836				tp->t_state = TCPS_FIN_WAIT_1;
837				tp->t_flags &= ~TF_NEEDFIN;
838				tiflags &= ~TH_SYN;
839			} else {
840				tp->t_state = TCPS_ESTABLISHED;
841				tp->t_timer[TCPT_KEEP] = tcp_keepidle;
842			}
843		} else {
844		/*
845		 *  Received initial SYN in SYN-SENT[*] state => simul-
846		 *  taneous open.  If segment contains CC option and there is
847		 *  a cached CC, apply TAO test; if it succeeds, connection is
848		 *  half-synchronized.  Otherwise, do 3-way handshake:
849		 *        SYN-SENT -> SYN-RECEIVED
850		 *        SYN-SENT* -> SYN-RECEIVED*
851		 *  If there was no CC option, clear cached CC value.
852		 */
853			tp->t_flags |= TF_ACKNOW;
854			tp->t_timer[TCPT_REXMT] = 0;
855			if (to.to_flag & TOF_CC) {
856				if (taop->tao_cc != 0 &&
857				    CC_GT(to.to_cc, taop->tao_cc)) {
858					/*
859					 * update cache and make transition:
860					 *        SYN-SENT -> ESTABLISHED*
861					 *        SYN-SENT* -> FIN-WAIT-1*
862					 */
863					taop->tao_cc = to.to_cc;
864					if (tp->t_flags & TF_NEEDFIN) {
865						tp->t_state = TCPS_FIN_WAIT_1;
866						tp->t_flags &= ~TF_NEEDFIN;
867					} else {
868						tp->t_state = TCPS_ESTABLISHED;
869						tp->t_timer[TCPT_KEEP] = tcp_keepidle;
870					}
871					tp->t_flags |= TF_NEEDSYN;
872				} else
873					tp->t_state = TCPS_SYN_RECEIVED;
874			} else {
875				/* CC.NEW or no option => invalidate cache */
876				taop->tao_cc = 0;
877				tp->t_state = TCPS_SYN_RECEIVED;
878			}
879		}
880
881trimthenstep6:
882		/*
883		 * Advance ti->ti_seq to correspond to first data byte.
884		 * If data, trim to stay within window,
885		 * dropping FIN if necessary.
886		 */
887		ti->ti_seq++;
888		if (ti->ti_len > tp->rcv_wnd) {
889			todrop = ti->ti_len - tp->rcv_wnd;
890			m_adj(m, -todrop);
891			ti->ti_len = tp->rcv_wnd;
892			tiflags &= ~TH_FIN;
893			tcpstat.tcps_rcvpackafterwin++;
894			tcpstat.tcps_rcvbyteafterwin += todrop;
895		}
896		tp->snd_wl1 = ti->ti_seq - 1;
897		tp->rcv_up = ti->ti_seq;
898		/*
899		 *  Client side of transaction: already sent SYN and data.
900		 *  If the remote host used T/TCP to validate the SYN,
901		 *  our data will be ACK'd; if so, enter normal data segment
902		 *  processing in the middle of step 5, ack processing.
903		 *  Otherwise, goto step 6.
904		 */
905 		if (tiflags & TH_ACK)
906			goto process_ACK;
907		goto step6;
908	/*
909	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
910	 *	if segment contains a SYN and CC [not CC.NEW] option:
911	 *              if state == TIME_WAIT and connection duration > MSL,
912	 *                  drop packet and send RST;
913	 *
914	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
915	 *		    ack the FIN (and data) in retransmission queue.
916	 *                  Complete close and delete TCPCB.  Then reprocess
917	 *                  segment, hoping to find new TCPCB in LISTEN state;
918	 *
919	 *		else must be old SYN; drop it.
920	 *      else do normal processing.
921	 */
922	case TCPS_LAST_ACK:
923	case TCPS_CLOSING:
924	case TCPS_TIME_WAIT:
925		if ((tiflags & TH_SYN) &&
926		    (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
927			if (tp->t_state == TCPS_TIME_WAIT &&
928					tp->t_duration > TCPTV_MSL)
929				goto dropwithreset;
930			if (CC_GT(to.to_cc, tp->cc_recv)) {
931				tp = tcp_close(tp);
932				goto findpcb;
933			}
934			else
935				goto drop;
936		}
937 		break;  /* continue normal processing */
938	}
939
940	/*
941	 * States other than LISTEN or SYN_SENT.
942	 * First check timestamp, if present.
943	 * Then check the connection count, if present.
944	 * Then check that at least some bytes of segment are within
945	 * receive window.  If segment begins before rcv_nxt,
946	 * drop leading data (and SYN); if nothing left, just ack.
947	 *
948	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
949	 * and it's less than ts_recent, drop it.
950	 */
951	if ((to.to_flag & TOF_TS) != 0 && (tiflags & TH_RST) == 0 &&
952	    tp->ts_recent && TSTMP_LT(to.to_tsval, tp->ts_recent)) {
953
954		/* Check to see if ts_recent is over 24 days old.  */
955		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
956			/*
957			 * Invalidate ts_recent.  If this segment updates
958			 * ts_recent, the age will be reset later and ts_recent
959			 * will get a valid value.  If it does not, setting
960			 * ts_recent to zero will at least satisfy the
961			 * requirement that zero be placed in the timestamp
962			 * echo reply when ts_recent isn't valid.  The
963			 * age isn't reset until we get a valid ts_recent
964			 * because we don't want out-of-order segments to be
965			 * dropped when ts_recent is old.
966			 */
967			tp->ts_recent = 0;
968		} else {
969			tcpstat.tcps_rcvduppack++;
970			tcpstat.tcps_rcvdupbyte += ti->ti_len;
971			tcpstat.tcps_pawsdrop++;
972			goto dropafterack;
973		}
974	}
975
976	/*
977	 * T/TCP mechanism
978	 *   If T/TCP was negotiated and the segment doesn't have CC,
979	 *   or if its CC is wrong then drop the segment.
980	 *   RST segments do not have to comply with this.
981	 */
982	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
983	    ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc) &&
984	    (tiflags & TH_RST) == 0)
985 		goto dropafterack;
986
987	todrop = tp->rcv_nxt - ti->ti_seq;
988	if (todrop > 0) {
989		if (tiflags & TH_SYN) {
990			tiflags &= ~TH_SYN;
991			ti->ti_seq++;
992			if (ti->ti_urp > 1)
993				ti->ti_urp--;
994			else
995				tiflags &= ~TH_URG;
996			todrop--;
997		}
998		/*
999		 * Following if statement from Stevens, vol. 2, p. 960.
1000		 */
1001		if (todrop > ti->ti_len
1002		    || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
1003			/*
1004			 * Any valid FIN must be to the left of the window.
1005			 * At this point the FIN must be a duplicate or out
1006			 * of sequence; drop it.
1007			 */
1008			tiflags &= ~TH_FIN;
1009
1010			/*
1011			 * Send an ACK to resynchronize and drop any data.
1012			 * But keep on processing for RST or ACK.
1013			 */
1014			tp->t_flags |= TF_ACKNOW;
1015			todrop = ti->ti_len;
1016			tcpstat.tcps_rcvduppack++;
1017			tcpstat.tcps_rcvdupbyte += todrop;
1018		} else {
1019			tcpstat.tcps_rcvpartduppack++;
1020			tcpstat.tcps_rcvpartdupbyte += todrop;
1021		}
1022		m_adj(m, todrop);
1023		ti->ti_seq += todrop;
1024		ti->ti_len -= todrop;
1025		if (ti->ti_urp > todrop)
1026			ti->ti_urp -= todrop;
1027		else {
1028			tiflags &= ~TH_URG;
1029			ti->ti_urp = 0;
1030		}
1031	}
1032
1033	/*
1034	 * If new data are received on a connection after the
1035	 * user processes are gone, then RST the other end.
1036	 */
1037	if ((so->so_state & SS_NOFDREF) &&
1038	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
1039		tp = tcp_close(tp);
1040		tcpstat.tcps_rcvafterclose++;
1041		goto dropwithreset;
1042	}
1043
1044	/*
1045	 * If segment ends after window, drop trailing data
1046	 * (and PUSH and FIN); if nothing left, just ACK.
1047	 */
1048	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
1049	if (todrop > 0) {
1050		tcpstat.tcps_rcvpackafterwin++;
1051		if (todrop >= ti->ti_len) {
1052			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
1053			/*
1054			 * If a new connection request is received
1055			 * while in TIME_WAIT, drop the old connection
1056			 * and start over if the sequence numbers
1057			 * are above the previous ones.
1058			 */
1059			if (tiflags & TH_SYN &&
1060			    tp->t_state == TCPS_TIME_WAIT &&
1061			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1062				iss = tp->rcv_nxt + TCP_ISSINCR;
1063				tp = tcp_close(tp);
1064				goto findpcb;
1065			}
1066			/*
1067			 * If window is closed can only take segments at
1068			 * window edge, and have to drop data and PUSH from
1069			 * incoming segments.  Continue processing, but
1070			 * remember to ack.  Otherwise, drop segment
1071			 * and ack.
1072			 */
1073			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1074				tp->t_flags |= TF_ACKNOW;
1075				tcpstat.tcps_rcvwinprobe++;
1076			} else
1077				goto dropafterack;
1078		} else
1079			tcpstat.tcps_rcvbyteafterwin += todrop;
1080		m_adj(m, -todrop);
1081		ti->ti_len -= todrop;
1082		tiflags &= ~(TH_PUSH|TH_FIN);
1083	}
1084
1085	/*
1086	 * If last ACK falls within this segment's sequence numbers,
1087	 * record its timestamp.
1088	 * NOTE that the test is modified according to the latest
1089	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1090	 */
1091	if ((to.to_flag & TOF_TS) != 0 &&
1092	    SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
1093		tp->ts_recent_age = tcp_now;
1094		tp->ts_recent = to.to_tsval;
1095	}
1096
1097	/*
1098	 * If the RST bit is set examine the state:
1099	 *    SYN_RECEIVED STATE:
1100	 *	If passive open, return to LISTEN state.
1101	 *	If active open, inform user that connection was refused.
1102	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1103	 *	Inform user that connection was reset, and close tcb.
1104	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
1105	 *	Close the tcb.
1106	 */
1107	if (tiflags&TH_RST) switch (tp->t_state) {
1108
1109	case TCPS_SYN_RECEIVED:
1110		so->so_error = ECONNREFUSED;
1111		goto close;
1112
1113	case TCPS_ESTABLISHED:
1114	case TCPS_FIN_WAIT_1:
1115	case TCPS_FIN_WAIT_2:
1116	case TCPS_CLOSE_WAIT:
1117		so->so_error = ECONNRESET;
1118	close:
1119		tp->t_state = TCPS_CLOSED;
1120		tcpstat.tcps_drops++;
1121		tp = tcp_close(tp);
1122		goto drop;
1123
1124	case TCPS_CLOSING:
1125	case TCPS_LAST_ACK:
1126	case TCPS_TIME_WAIT:
1127		tp = tcp_close(tp);
1128		goto drop;
1129	}
1130
1131	/*
1132	 * If a SYN is in the window, then this is an
1133	 * error and we send an RST and drop the connection.
1134	 */
1135	if (tiflags & TH_SYN) {
1136		tp = tcp_drop(tp, ECONNRESET);
1137		goto dropwithreset;
1138	}
1139
1140	/*
1141	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1142	 * flag is on (half-synchronized state), then queue data for
1143	 * later processing; else drop segment and return.
1144	 */
1145	if ((tiflags & TH_ACK) == 0) {
1146		if (tp->t_state == TCPS_SYN_RECEIVED ||
1147		    (tp->t_flags & TF_NEEDSYN))
1148			goto step6;
1149		else
1150			goto drop;
1151	}
1152
1153	/*
1154	 * Ack processing.
1155	 */
1156	switch (tp->t_state) {
1157
1158	/*
1159	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1160	 * ESTABLISHED state and continue processing.
1161	 * The ACK was checked above.
1162	 */
1163	case TCPS_SYN_RECEIVED:
1164
1165		tcpstat.tcps_connects++;
1166		soisconnected(so);
1167		/* Do window scaling? */
1168		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1169			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1170			tp->snd_scale = tp->requested_s_scale;
1171			tp->rcv_scale = tp->request_r_scale;
1172		}
1173		/*
1174		 * Upon successful completion of 3-way handshake,
1175		 * update cache.CC if it was undefined, pass any queued
1176		 * data to the user, and advance state appropriately.
1177		 */
1178		if ((taop = tcp_gettaocache(inp)) != NULL &&
1179		    taop->tao_cc == 0)
1180			taop->tao_cc = tp->cc_recv;
1181
1182		/*
1183		 * Make transitions:
1184		 *      SYN-RECEIVED  -> ESTABLISHED
1185		 *      SYN-RECEIVED* -> FIN-WAIT-1
1186		 */
1187		if (tp->t_flags & TF_NEEDFIN) {
1188			tp->t_state = TCPS_FIN_WAIT_1;
1189			tp->t_flags &= ~TF_NEEDFIN;
1190		} else {
1191			tp->t_state = TCPS_ESTABLISHED;
1192			tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1193		}
1194		/*
1195		 * If segment contains data or ACK, will call tcp_reass()
1196		 * later; if not, do so now to pass queued data to user.
1197		 */
1198		if (ti->ti_len == 0 && (tiflags & TH_FIN) == 0)
1199			(void) tcp_reass(tp, (struct tcpiphdr *)0,
1200			    (struct mbuf *)0);
1201		tp->snd_wl1 = ti->ti_seq - 1;
1202		/* fall into ... */
1203
1204	/*
1205	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1206	 * ACKs.  If the ack is in the range
1207	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
1208	 * then advance tp->snd_una to ti->ti_ack and drop
1209	 * data from the retransmission queue.  If this ACK reflects
1210	 * more up to date window information we update our window information.
1211	 */
1212	case TCPS_ESTABLISHED:
1213	case TCPS_FIN_WAIT_1:
1214	case TCPS_FIN_WAIT_2:
1215	case TCPS_CLOSE_WAIT:
1216	case TCPS_CLOSING:
1217	case TCPS_LAST_ACK:
1218	case TCPS_TIME_WAIT:
1219
1220		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1221			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1222				tcpstat.tcps_rcvdupack++;
1223				/*
1224				 * If we have outstanding data (other than
1225				 * a window probe), this is a completely
1226				 * duplicate ack (ie, window info didn't
1227				 * change), the ack is the biggest we've
1228				 * seen and we've seen exactly our rexmt
1229				 * threshhold of them, assume a packet
1230				 * has been dropped and retransmit it.
1231				 * Kludge snd_nxt & the congestion
1232				 * window so we send only this one
1233				 * packet.
1234				 *
1235				 * We know we're losing at the current
1236				 * window size so do congestion avoidance
1237				 * (set ssthresh to half the current window
1238				 * and pull our congestion window back to
1239				 * the new ssthresh).
1240				 *
1241				 * Dup acks mean that packets have left the
1242				 * network (they're now cached at the receiver)
1243				 * so bump cwnd by the amount in the receiver
1244				 * to keep a constant cwnd packets in the
1245				 * network.
1246				 */
1247				if (tp->t_timer[TCPT_REXMT] == 0 ||
1248				    ti->ti_ack != tp->snd_una)
1249					tp->t_dupacks = 0;
1250				else if (++tp->t_dupacks == tcprexmtthresh) {
1251					tcp_seq onxt = tp->snd_nxt;
1252					u_int win =
1253					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1254						tp->t_maxseg;
1255
1256					if (win < 2)
1257						win = 2;
1258					tp->snd_ssthresh = win * tp->t_maxseg;
1259					tp->t_timer[TCPT_REXMT] = 0;
1260					tp->t_rtt = 0;
1261					tp->snd_nxt = ti->ti_ack;
1262					tp->snd_cwnd = tp->t_maxseg;
1263					(void) tcp_output(tp);
1264					tp->snd_cwnd = tp->snd_ssthresh +
1265					       tp->t_maxseg * tp->t_dupacks;
1266					if (SEQ_GT(onxt, tp->snd_nxt))
1267						tp->snd_nxt = onxt;
1268					goto drop;
1269				} else if (tp->t_dupacks > tcprexmtthresh) {
1270					tp->snd_cwnd += tp->t_maxseg;
1271					(void) tcp_output(tp);
1272					goto drop;
1273				}
1274			} else
1275				tp->t_dupacks = 0;
1276			break;
1277		}
1278		/*
1279		 * If the congestion window was inflated to account
1280		 * for the other side's cached packets, retract it.
1281		 */
1282		if (tp->t_dupacks >= tcprexmtthresh &&
1283		    tp->snd_cwnd > tp->snd_ssthresh)
1284			tp->snd_cwnd = tp->snd_ssthresh;
1285		tp->t_dupacks = 0;
1286		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1287			tcpstat.tcps_rcvacktoomuch++;
1288			goto dropafterack;
1289		}
1290		/*
1291		 *  If we reach this point, ACK is not a duplicate,
1292		 *     i.e., it ACKs something we sent.
1293		 */
1294		if (tp->t_flags & TF_NEEDSYN) {
1295			/*
1296			 * T/TCP: Connection was half-synchronized, and our
1297			 * SYN has been ACK'd (so connection is now fully
1298			 * synchronized).  Go to non-starred state,
1299			 * increment snd_una for ACK of SYN, and check if
1300			 * we can do window scaling.
1301			 */
1302			tp->t_flags &= ~TF_NEEDSYN;
1303			tp->snd_una++;
1304			/* Do window scaling? */
1305			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1306				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1307				tp->snd_scale = tp->requested_s_scale;
1308				tp->rcv_scale = tp->request_r_scale;
1309			}
1310		}
1311
1312process_ACK:
1313		acked = ti->ti_ack - tp->snd_una;
1314		tcpstat.tcps_rcvackpack++;
1315		tcpstat.tcps_rcvackbyte += acked;
1316
1317		/*
1318		 * If we have a timestamp reply, update smoothed
1319		 * round trip time.  If no timestamp is present but
1320		 * transmit timer is running and timed sequence
1321		 * number was acked, update smoothed round trip time.
1322		 * Since we now have an rtt measurement, cancel the
1323		 * timer backoff (cf., Phil Karn's retransmit alg.).
1324		 * Recompute the initial retransmit timer.
1325		 */
1326		if (to.to_flag & TOF_TS)
1327			tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1328		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1329			tcp_xmit_timer(tp,tp->t_rtt);
1330
1331		/*
1332		 * If all outstanding data is acked, stop retransmit
1333		 * timer and remember to restart (more output or persist).
1334		 * If there is more data to be acked, restart retransmit
1335		 * timer, using current (possibly backed-off) value.
1336		 */
1337		if (ti->ti_ack == tp->snd_max) {
1338			tp->t_timer[TCPT_REXMT] = 0;
1339			needoutput = 1;
1340		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1341			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1342
1343		/*
1344		 * If no data (only SYN) was ACK'd,
1345		 *    skip rest of ACK processing.
1346		 */
1347		if (acked == 0)
1348			goto step6;
1349
1350		/*
1351		 * When new data is acked, open the congestion window.
1352		 * If the window gives us less than ssthresh packets
1353		 * in flight, open exponentially (maxseg per packet).
1354		 * Otherwise open linearly: maxseg per window
1355		 * (maxseg^2 / cwnd per packet).
1356		 */
1357		{
1358		register u_int cw = tp->snd_cwnd;
1359		register u_int incr = tp->t_maxseg;
1360
1361		if (cw > tp->snd_ssthresh)
1362			incr = incr * incr / cw;
1363		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1364		}
1365		if (acked > so->so_snd.sb_cc) {
1366			tp->snd_wnd -= so->so_snd.sb_cc;
1367			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1368			ourfinisacked = 1;
1369		} else {
1370			sbdrop(&so->so_snd, acked);
1371			tp->snd_wnd -= acked;
1372			ourfinisacked = 0;
1373		}
1374		if (so->so_snd.sb_flags & SB_NOTIFY)
1375			sowwakeup(so);
1376		tp->snd_una = ti->ti_ack;
1377		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1378			tp->snd_nxt = tp->snd_una;
1379
1380		switch (tp->t_state) {
1381
1382		/*
1383		 * In FIN_WAIT_1 STATE in addition to the processing
1384		 * for the ESTABLISHED state if our FIN is now acknowledged
1385		 * then enter FIN_WAIT_2.
1386		 */
1387		case TCPS_FIN_WAIT_1:
1388			if (ourfinisacked) {
1389				/*
1390				 * If we can't receive any more
1391				 * data, then closing user can proceed.
1392				 * Starting the timer is contrary to the
1393				 * specification, but if we don't get a FIN
1394				 * we'll hang forever.
1395				 */
1396				if (so->so_state & SS_CANTRCVMORE) {
1397					soisdisconnected(so);
1398					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1399				}
1400				tp->t_state = TCPS_FIN_WAIT_2;
1401			}
1402			break;
1403
1404	 	/*
1405		 * In CLOSING STATE in addition to the processing for
1406		 * the ESTABLISHED state if the ACK acknowledges our FIN
1407		 * then enter the TIME-WAIT state, otherwise ignore
1408		 * the segment.
1409		 */
1410		case TCPS_CLOSING:
1411			if (ourfinisacked) {
1412				tp->t_state = TCPS_TIME_WAIT;
1413				tcp_canceltimers(tp);
1414				/* Shorten TIME_WAIT [RFC-1644, p.28] */
1415				if (tp->cc_recv != 0 &&
1416				    tp->t_duration < TCPTV_MSL)
1417					tp->t_timer[TCPT_2MSL] =
1418					    tp->t_rxtcur * TCPTV_TWTRUNC;
1419				else
1420					tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1421				soisdisconnected(so);
1422			}
1423			break;
1424
1425		/*
1426		 * In LAST_ACK, we may still be waiting for data to drain
1427		 * and/or to be acked, as well as for the ack of our FIN.
1428		 * If our FIN is now acknowledged, delete the TCB,
1429		 * enter the closed state and return.
1430		 */
1431		case TCPS_LAST_ACK:
1432			if (ourfinisacked) {
1433				tp = tcp_close(tp);
1434				goto drop;
1435			}
1436			break;
1437
1438		/*
1439		 * In TIME_WAIT state the only thing that should arrive
1440		 * is a retransmission of the remote FIN.  Acknowledge
1441		 * it and restart the finack timer.
1442		 */
1443		case TCPS_TIME_WAIT:
1444			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1445			goto dropafterack;
1446		}
1447	}
1448
1449step6:
1450	/*
1451	 * Update window information.
1452	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1453	 */
1454	if ((tiflags & TH_ACK) &&
1455	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1456	    (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1457	     (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1458		/* keep track of pure window updates */
1459		if (ti->ti_len == 0 &&
1460		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1461			tcpstat.tcps_rcvwinupd++;
1462		tp->snd_wnd = tiwin;
1463		tp->snd_wl1 = ti->ti_seq;
1464		tp->snd_wl2 = ti->ti_ack;
1465		if (tp->snd_wnd > tp->max_sndwnd)
1466			tp->max_sndwnd = tp->snd_wnd;
1467		needoutput = 1;
1468	}
1469
1470	/*
1471	 * Process segments with URG.
1472	 */
1473	if ((tiflags & TH_URG) && ti->ti_urp &&
1474	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1475		/*
1476		 * This is a kludge, but if we receive and accept
1477		 * random urgent pointers, we'll crash in
1478		 * soreceive.  It's hard to imagine someone
1479		 * actually wanting to send this much urgent data.
1480		 */
1481		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1482			ti->ti_urp = 0;			/* XXX */
1483			tiflags &= ~TH_URG;		/* XXX */
1484			goto dodata;			/* XXX */
1485		}
1486		/*
1487		 * If this segment advances the known urgent pointer,
1488		 * then mark the data stream.  This should not happen
1489		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1490		 * a FIN has been received from the remote side.
1491		 * In these states we ignore the URG.
1492		 *
1493		 * According to RFC961 (Assigned Protocols),
1494		 * the urgent pointer points to the last octet
1495		 * of urgent data.  We continue, however,
1496		 * to consider it to indicate the first octet
1497		 * of data past the urgent section as the original
1498		 * spec states (in one of two places).
1499		 */
1500		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1501			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1502			so->so_oobmark = so->so_rcv.sb_cc +
1503			    (tp->rcv_up - tp->rcv_nxt) - 1;
1504			if (so->so_oobmark == 0)
1505				so->so_state |= SS_RCVATMARK;
1506			sohasoutofband(so);
1507			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1508		}
1509		/*
1510		 * Remove out of band data so doesn't get presented to user.
1511		 * This can happen independent of advancing the URG pointer,
1512		 * but if two URG's are pending at once, some out-of-band
1513		 * data may creep in... ick.
1514		 */
1515		if (ti->ti_urp <= (u_long)ti->ti_len
1516#ifdef SO_OOBINLINE
1517		     && (so->so_options & SO_OOBINLINE) == 0
1518#endif
1519		     )
1520			tcp_pulloutofband(so, ti, m);
1521	} else
1522		/*
1523		 * If no out of band data is expected,
1524		 * pull receive urgent pointer along
1525		 * with the receive window.
1526		 */
1527		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1528			tp->rcv_up = tp->rcv_nxt;
1529dodata:							/* XXX */
1530
1531	/*
1532	 * Process the segment text, merging it into the TCP sequencing queue,
1533	 * and arranging for acknowledgment of receipt if necessary.
1534	 * This process logically involves adjusting tp->rcv_wnd as data
1535	 * is presented to the user (this happens in tcp_usrreq.c,
1536	 * case PRU_RCVD).  If a FIN has already been received on this
1537	 * connection then we just ignore the text.
1538	 */
1539	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1540	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1541		TCP_REASS(tp, ti, m, so, tiflags);
1542		/*
1543		 * Note the amount of data that peer has sent into
1544		 * our window, in order to estimate the sender's
1545		 * buffer size.
1546		 */
1547		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1548	} else {
1549		m_freem(m);
1550		tiflags &= ~TH_FIN;
1551	}
1552
1553	/*
1554	 * If FIN is received ACK the FIN and let the user know
1555	 * that the connection is closing.
1556	 */
1557	if (tiflags & TH_FIN) {
1558		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1559			socantrcvmore(so);
1560			/*
1561			 *  If connection is half-synchronized
1562			 *  (ie NEEDSYN flag on) then delay ACK,
1563			 *  so it may be piggybacked when SYN is sent.
1564			 *  Otherwise, since we received a FIN then no
1565			 *  more input can be expected, send ACK now.
1566			 */
1567			if (tcp_delack_enabled && (tp->t_flags & TF_NEEDSYN))
1568				tp->t_flags |= TF_DELACK;
1569			else
1570				tp->t_flags |= TF_ACKNOW;
1571			tp->rcv_nxt++;
1572		}
1573		switch (tp->t_state) {
1574
1575	 	/*
1576		 * In SYN_RECEIVED and ESTABLISHED STATES
1577		 * enter the CLOSE_WAIT state.
1578		 */
1579		case TCPS_SYN_RECEIVED:
1580		case TCPS_ESTABLISHED:
1581			tp->t_state = TCPS_CLOSE_WAIT;
1582			break;
1583
1584	 	/*
1585		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1586		 * enter the CLOSING state.
1587		 */
1588		case TCPS_FIN_WAIT_1:
1589			tp->t_state = TCPS_CLOSING;
1590			break;
1591
1592	 	/*
1593		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1594		 * starting the time-wait timer, turning off the other
1595		 * standard timers.
1596		 */
1597		case TCPS_FIN_WAIT_2:
1598			tp->t_state = TCPS_TIME_WAIT;
1599			tcp_canceltimers(tp);
1600			/* Shorten TIME_WAIT [RFC-1644, p.28] */
1601			if (tp->cc_recv != 0 &&
1602			    tp->t_duration < TCPTV_MSL) {
1603				tp->t_timer[TCPT_2MSL] =
1604				    tp->t_rxtcur * TCPTV_TWTRUNC;
1605				/* For transaction client, force ACK now. */
1606				tp->t_flags |= TF_ACKNOW;
1607			}
1608			else
1609				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1610			soisdisconnected(so);
1611			break;
1612
1613		/*
1614		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1615		 */
1616		case TCPS_TIME_WAIT:
1617			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1618			break;
1619		}
1620	}
1621#ifdef TCPDEBUG
1622	if (so->so_options & SO_DEBUG)
1623		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1624#endif
1625
1626	/*
1627	 * Return any desired output.
1628	 */
1629	if (needoutput || (tp->t_flags & TF_ACKNOW))
1630		(void) tcp_output(tp);
1631	return;
1632
1633dropafterack:
1634	/*
1635	 * Generate an ACK dropping incoming segment if it occupies
1636	 * sequence space, where the ACK reflects our state.
1637	 */
1638	if (tiflags & TH_RST)
1639		goto drop;
1640#ifdef TCPDEBUG
1641	if (so->so_options & SO_DEBUG)
1642		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1643#endif
1644	m_freem(m);
1645	tp->t_flags |= TF_ACKNOW;
1646	(void) tcp_output(tp);
1647	return;
1648
1649dropwithreset:
1650	/*
1651	 * Generate a RST, dropping incoming segment.
1652	 * Make ACK acceptable to originator of segment.
1653	 * Don't bother to respond if destination was broadcast/multicast.
1654	 */
1655	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1656	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1657		goto drop;
1658#ifdef TCPDEBUG
1659	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1660		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1661#endif
1662	if (tiflags & TH_ACK)
1663		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1664	else {
1665		if (tiflags & TH_SYN)
1666			ti->ti_len++;
1667		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1668		    TH_RST|TH_ACK);
1669	}
1670	/* destroy temporarily created socket */
1671	if (dropsocket)
1672		(void) soabort(so);
1673	return;
1674
1675drop:
1676	/*
1677	 * Drop space held by incoming segment and return.
1678	 */
1679#ifdef TCPDEBUG
1680	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1681		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1682#endif
1683	m_freem(m);
1684	/* destroy temporarily created socket */
1685	if (dropsocket)
1686		(void) soabort(so);
1687	return;
1688}
1689
1690static void
1691tcp_dooptions(tp, cp, cnt, ti, to)
1692	struct tcpcb *tp;
1693	u_char *cp;
1694	int cnt;
1695	struct tcpiphdr *ti;
1696	struct tcpopt *to;
1697{
1698	u_short mss = 0;
1699	int opt, optlen;
1700
1701	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1702		opt = cp[0];
1703		if (opt == TCPOPT_EOL)
1704			break;
1705		if (opt == TCPOPT_NOP)
1706			optlen = 1;
1707		else {
1708			optlen = cp[1];
1709			if (optlen <= 0)
1710				break;
1711		}
1712		switch (opt) {
1713
1714		default:
1715			continue;
1716
1717		case TCPOPT_MAXSEG:
1718			if (optlen != TCPOLEN_MAXSEG)
1719				continue;
1720			if (!(ti->ti_flags & TH_SYN))
1721				continue;
1722			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1723			NTOHS(mss);
1724			break;
1725
1726		case TCPOPT_WINDOW:
1727			if (optlen != TCPOLEN_WINDOW)
1728				continue;
1729			if (!(ti->ti_flags & TH_SYN))
1730				continue;
1731			tp->t_flags |= TF_RCVD_SCALE;
1732			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1733			break;
1734
1735		case TCPOPT_TIMESTAMP:
1736			if (optlen != TCPOLEN_TIMESTAMP)
1737				continue;
1738			to->to_flag |= TOF_TS;
1739			bcopy((char *)cp + 2,
1740			    (char *)&to->to_tsval, sizeof(to->to_tsval));
1741			NTOHL(to->to_tsval);
1742			bcopy((char *)cp + 6,
1743			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
1744			NTOHL(to->to_tsecr);
1745
1746			/*
1747			 * A timestamp received in a SYN makes
1748			 * it ok to send timestamp requests and replies.
1749			 */
1750			if (ti->ti_flags & TH_SYN) {
1751				tp->t_flags |= TF_RCVD_TSTMP;
1752				tp->ts_recent = to->to_tsval;
1753				tp->ts_recent_age = tcp_now;
1754			}
1755			break;
1756		case TCPOPT_CC:
1757			if (optlen != TCPOLEN_CC)
1758				continue;
1759			to->to_flag |= TOF_CC;
1760			bcopy((char *)cp + 2,
1761			    (char *)&to->to_cc, sizeof(to->to_cc));
1762			NTOHL(to->to_cc);
1763			/*
1764			 * A CC or CC.new option received in a SYN makes
1765			 * it ok to send CC in subsequent segments.
1766			 */
1767			if (ti->ti_flags & TH_SYN)
1768				tp->t_flags |= TF_RCVD_CC;
1769			break;
1770		case TCPOPT_CCNEW:
1771			if (optlen != TCPOLEN_CC)
1772				continue;
1773			if (!(ti->ti_flags & TH_SYN))
1774				continue;
1775			to->to_flag |= TOF_CCNEW;
1776			bcopy((char *)cp + 2,
1777			    (char *)&to->to_cc, sizeof(to->to_cc));
1778			NTOHL(to->to_cc);
1779			/*
1780			 * A CC or CC.new option received in a SYN makes
1781			 * it ok to send CC in subsequent segments.
1782			 */
1783			tp->t_flags |= TF_RCVD_CC;
1784			break;
1785		case TCPOPT_CCECHO:
1786			if (optlen != TCPOLEN_CC)
1787				continue;
1788			if (!(ti->ti_flags & TH_SYN))
1789				continue;
1790			to->to_flag |= TOF_CCECHO;
1791			bcopy((char *)cp + 2,
1792			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
1793			NTOHL(to->to_ccecho);
1794			break;
1795		}
1796	}
1797	if (ti->ti_flags & TH_SYN)
1798		tcp_mss(tp, mss);	/* sets t_maxseg */
1799}
1800
1801/*
1802 * Pull out of band byte out of a segment so
1803 * it doesn't appear in the user's data queue.
1804 * It is still reflected in the segment length for
1805 * sequencing purposes.
1806 */
1807static void
1808tcp_pulloutofband(so, ti, m)
1809	struct socket *so;
1810	struct tcpiphdr *ti;
1811	register struct mbuf *m;
1812{
1813	int cnt = ti->ti_urp - 1;
1814
1815	while (cnt >= 0) {
1816		if (m->m_len > cnt) {
1817			char *cp = mtod(m, caddr_t) + cnt;
1818			struct tcpcb *tp = sototcpcb(so);
1819
1820			tp->t_iobc = *cp;
1821			tp->t_oobflags |= TCPOOB_HAVEDATA;
1822			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1823			m->m_len--;
1824			return;
1825		}
1826		cnt -= m->m_len;
1827		m = m->m_next;
1828		if (m == 0)
1829			break;
1830	}
1831	panic("tcp_pulloutofband");
1832}
1833
1834/*
1835 * Collect new round-trip time estimate
1836 * and update averages and current timeout.
1837 */
1838static void
1839tcp_xmit_timer(tp, rtt)
1840	register struct tcpcb *tp;
1841	short rtt;
1842{
1843	register int delta;
1844
1845	tcpstat.tcps_rttupdated++;
1846	tp->t_rttupdated++;
1847	if (tp->t_srtt != 0) {
1848		/*
1849		 * srtt is stored as fixed point with 5 bits after the
1850		 * binary point (i.e., scaled by 8).  The following magic
1851		 * is equivalent to the smoothing algorithm in rfc793 with
1852		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1853		 * point).  Adjust rtt to origin 0.
1854		 */
1855		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
1856			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
1857
1858		if ((tp->t_srtt += delta) <= 0)
1859			tp->t_srtt = 1;
1860
1861		/*
1862		 * We accumulate a smoothed rtt variance (actually, a
1863		 * smoothed mean difference), then set the retransmit
1864		 * timer to smoothed rtt + 4 times the smoothed variance.
1865		 * rttvar is stored as fixed point with 4 bits after the
1866		 * binary point (scaled by 16).  The following is
1867		 * equivalent to rfc793 smoothing with an alpha of .75
1868		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1869		 * rfc793's wired-in beta.
1870		 */
1871		if (delta < 0)
1872			delta = -delta;
1873		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
1874		if ((tp->t_rttvar += delta) <= 0)
1875			tp->t_rttvar = 1;
1876	} else {
1877		/*
1878		 * No rtt measurement yet - use the unsmoothed rtt.
1879		 * Set the variance to half the rtt (so our first
1880		 * retransmit happens at 3*rtt).
1881		 */
1882		tp->t_srtt = rtt << TCP_RTT_SHIFT;
1883		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1884	}
1885	tp->t_rtt = 0;
1886	tp->t_rxtshift = 0;
1887
1888	/*
1889	 * the retransmit should happen at rtt + 4 * rttvar.
1890	 * Because of the way we do the smoothing, srtt and rttvar
1891	 * will each average +1/2 tick of bias.  When we compute
1892	 * the retransmit timer, we want 1/2 tick of rounding and
1893	 * 1 extra tick because of +-1/2 tick uncertainty in the
1894	 * firing of the timer.  The bias will give us exactly the
1895	 * 1.5 tick we need.  But, because the bias is
1896	 * statistical, we have to test that we don't drop below
1897	 * the minimum feasible timer (which is 2 ticks).
1898	 */
1899	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1900		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
1901
1902	/*
1903	 * We received an ack for a packet that wasn't retransmitted;
1904	 * it is probably safe to discard any error indications we've
1905	 * received recently.  This isn't quite right, but close enough
1906	 * for now (a route might have failed after we sent a segment,
1907	 * and the return path might not be symmetrical).
1908	 */
1909	tp->t_softerror = 0;
1910}
1911
1912/*
1913 * Determine a reasonable value for maxseg size.
1914 * If the route is known, check route for mtu.
1915 * If none, use an mss that can be handled on the outgoing
1916 * interface without forcing IP to fragment; if bigger than
1917 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1918 * to utilize large mbufs.  If no route is found, route has no mtu,
1919 * or the destination isn't local, use a default, hopefully conservative
1920 * size (usually 512 or the default IP max size, but no more than the mtu
1921 * of the interface), as we can't discover anything about intervening
1922 * gateways or networks.  We also initialize the congestion/slow start
1923 * window to be a single segment if the destination isn't local.
1924 * While looking at the routing entry, we also initialize other path-dependent
1925 * parameters from pre-set or cached values in the routing entry.
1926 *
1927 * Also take into account the space needed for options that we
1928 * send regularly.  Make maxseg shorter by that amount to assure
1929 * that we can send maxseg amount of data even when the options
1930 * are present.  Store the upper limit of the length of options plus
1931 * data in maxopd.
1932 *
1933 * NOTE that this routine is only called when we process an incoming
1934 * segment, for outgoing segments only tcp_mssopt is called.
1935 *
1936 * In case of T/TCP, we call this routine during implicit connection
1937 * setup as well (offer = -1), to initialize maxseg from the cached
1938 * MSS of our peer.
1939 */
1940void
1941tcp_mss(tp, offer)
1942	struct tcpcb *tp;
1943	int offer;
1944{
1945	register struct rtentry *rt;
1946	struct ifnet *ifp;
1947	register int rtt, mss;
1948	u_long bufsize;
1949	struct inpcb *inp;
1950	struct socket *so;
1951	struct rmxp_tao *taop;
1952	int origoffer = offer;
1953
1954	inp = tp->t_inpcb;
1955	if ((rt = tcp_rtlookup(inp)) == NULL) {
1956		tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
1957		return;
1958	}
1959	ifp = rt->rt_ifp;
1960	so = inp->inp_socket;
1961
1962	taop = rmx_taop(rt->rt_rmx);
1963	/*
1964	 * Offer == -1 means that we didn't receive SYN yet,
1965	 * use cached value in that case;
1966	 */
1967	if (offer == -1)
1968		offer = taop->tao_mssopt;
1969	/*
1970	 * Offer == 0 means that there was no MSS on the SYN segment,
1971	 * in this case we use tcp_mssdflt.
1972	 */
1973	if (offer == 0)
1974		offer = tcp_mssdflt;
1975	else
1976		/*
1977		 * Sanity check: make sure that maxopd will be large
1978		 * enough to allow some data on segments even is the
1979		 * all the option space is used (40bytes).  Otherwise
1980		 * funny things may happen in tcp_output.
1981		 */
1982		offer = max(offer, 64);
1983	taop->tao_mssopt = offer;
1984
1985	/*
1986	 * While we're here, check if there's an initial rtt
1987	 * or rttvar.  Convert from the route-table units
1988	 * to scaled multiples of the slow timeout timer.
1989	 */
1990	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1991		/*
1992		 * XXX the lock bit for RTT indicates that the value
1993		 * is also a minimum value; this is subject to time.
1994		 */
1995		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1996			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
1997		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
1998		tcpstat.tcps_usedrtt++;
1999		if (rt->rt_rmx.rmx_rttvar) {
2000			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2001			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2002			tcpstat.tcps_usedrttvar++;
2003		} else {
2004			/* default variation is +- 1 rtt */
2005			tp->t_rttvar =
2006			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2007		}
2008		TCPT_RANGESET(tp->t_rxtcur,
2009		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2010		    tp->t_rttmin, TCPTV_REXMTMAX);
2011	}
2012	/*
2013	 * if there's an mtu associated with the route, use it
2014	 */
2015	if (rt->rt_rmx.rmx_mtu)
2016		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
2017	else
2018	{
2019		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
2020		if (!in_localaddr(inp->inp_faddr))
2021			mss = min(mss, tcp_mssdflt);
2022	}
2023	mss = min(mss, offer);
2024	/*
2025	 * maxopd stores the maximum length of data AND options
2026	 * in a segment; maxseg is the amount of data in a normal
2027	 * segment.  We need to store this value (maxopd) apart
2028	 * from maxseg, because now every segment carries options
2029	 * and thus we normally have somewhat less data in segments.
2030	 */
2031	tp->t_maxopd = mss;
2032
2033	/*
2034	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2035	 * were received yet.  In this case we just guess, otherwise
2036	 * we do the same as before T/TCP.
2037	 */
2038 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2039	    (origoffer == -1 ||
2040	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2041		mss -= TCPOLEN_TSTAMP_APPA;
2042 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2043	    (origoffer == -1 ||
2044	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2045		mss -= TCPOLEN_CC_APPA;
2046
2047#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2048		if (mss > MCLBYTES)
2049			mss &= ~(MCLBYTES-1);
2050#else
2051		if (mss > MCLBYTES)
2052			mss = mss / MCLBYTES * MCLBYTES;
2053#endif
2054	/*
2055	 * If there's a pipesize, change the socket buffer
2056	 * to that size.  Make the socket buffers an integral
2057	 * number of mss units; if the mss is larger than
2058	 * the socket buffer, decrease the mss.
2059	 */
2060#ifdef RTV_SPIPE
2061	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2062#endif
2063		bufsize = so->so_snd.sb_hiwat;
2064	if (bufsize < mss)
2065		mss = bufsize;
2066	else {
2067		bufsize = roundup(bufsize, mss);
2068		if (bufsize > sb_max)
2069			bufsize = sb_max;
2070		(void)sbreserve(&so->so_snd, bufsize);
2071	}
2072	tp->t_maxseg = mss;
2073
2074#ifdef RTV_RPIPE
2075	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2076#endif
2077		bufsize = so->so_rcv.sb_hiwat;
2078	if (bufsize > mss) {
2079		bufsize = roundup(bufsize, mss);
2080		if (bufsize > sb_max)
2081			bufsize = sb_max;
2082		(void)sbreserve(&so->so_rcv, bufsize);
2083	}
2084	/*
2085	 * Don't force slow-start on local network.
2086	 */
2087	if (!in_localaddr(inp->inp_faddr))
2088		tp->snd_cwnd = mss;
2089
2090	if (rt->rt_rmx.rmx_ssthresh) {
2091		/*
2092		 * There's some sort of gateway or interface
2093		 * buffer limit on the path.  Use this to set
2094		 * the slow start threshhold, but set the
2095		 * threshold to no less than 2*mss.
2096		 */
2097		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2098		tcpstat.tcps_usedssthresh++;
2099	}
2100}
2101
2102/*
2103 * Determine the MSS option to send on an outgoing SYN.
2104 */
2105int
2106tcp_mssopt(tp)
2107	struct tcpcb *tp;
2108{
2109	struct rtentry *rt;
2110
2111	rt = tcp_rtlookup(tp->t_inpcb);
2112	if (rt == NULL)
2113		return tcp_mssdflt;
2114
2115	return rt->rt_ifp->if_mtu - sizeof(struct tcpiphdr);
2116}
2117