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