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