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