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