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