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