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