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