xref: /netbsd-src/sys/netinet/tcp_input.c (revision ce0bb6e8d2e560ecacbe865a848624f94498063b)
1 /*	$NetBSD: tcp_input.c,v 1.12 1995/04/13 06:36:37 cgd Exp $	*/
2 
3 /*
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	@(#)tcp_input.c	8.5 (Berkeley) 4/10/94
36  */
37 
38 #ifndef TUBA_INCLUDE
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/malloc.h>
42 #include <sys/mbuf.h>
43 #include <sys/protosw.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/errno.h>
47 
48 #include <net/if.h>
49 #include <net/route.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/in_pcb.h>
55 #include <netinet/ip_var.h>
56 #include <netinet/tcp.h>
57 #include <netinet/tcp_fsm.h>
58 #include <netinet/tcp_seq.h>
59 #include <netinet/tcp_timer.h>
60 #include <netinet/tcp_var.h>
61 #include <netinet/tcpip.h>
62 #include <netinet/tcp_debug.h>
63 
64 int	tcprexmtthresh = 3;
65 struct	tcpiphdr tcp_saveti;
66 struct	inpcb *tcp_last_inpcb = &tcb;
67 
68 extern u_long sb_max;
69 
70 #endif /* TUBA_INCLUDE */
71 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
72 
73 /* for modulo comparisons of timestamps */
74 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
75 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
76 
77 
78 /*
79  * Insert segment ti into reassembly queue of tcp with
80  * control block tp.  Return TH_FIN if reassembly now includes
81  * a segment with FIN.  The macro form does the common case inline
82  * (segment is the next to be received on an established connection,
83  * and the queue is empty), avoiding linkage into and removal
84  * from the queue and repetition of various conversions.
85  * Set DELACK for segments received in order, but ack immediately
86  * when segments are out of order (so fast retransmit can work).
87  */
88 #define	TCP_REASS(tp, ti, m, so, flags) { \
89 	if ((ti)->ti_seq == (tp)->rcv_nxt && \
90 	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
91 	    (tp)->t_state == TCPS_ESTABLISHED) { \
92 		if ((ti)->ti_flags & TH_PUSH) \
93 			tp->t_flags |= TF_ACKNOW; \
94 		else \
95 			tp->t_flags |= TF_DELACK; \
96 		(tp)->rcv_nxt += (ti)->ti_len; \
97 		flags = (ti)->ti_flags & TH_FIN; \
98 		tcpstat.tcps_rcvpack++;\
99 		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
100 		sbappend(&(so)->so_rcv, (m)); \
101 		sorwakeup(so); \
102 	} else { \
103 		(flags) = tcp_reass((tp), (ti), (m)); \
104 		tp->t_flags |= TF_ACKNOW; \
105 	} \
106 }
107 #ifndef TUBA_INCLUDE
108 
109 int
110 tcp_reass(tp, ti, m)
111 	register struct tcpcb *tp;
112 	register struct tcpiphdr *ti;
113 	struct mbuf *m;
114 {
115 	register struct tcpiphdr *q;
116 	struct socket *so = tp->t_inpcb->inp_socket;
117 	int flags;
118 
119 	/*
120 	 * Call with ti==0 after become established to
121 	 * force pre-ESTABLISHED data up to user socket.
122 	 */
123 	if (ti == 0)
124 		goto present;
125 
126 	/*
127 	 * Find a segment which begins after this one does.
128 	 */
129 	for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
130 	    q = (struct tcpiphdr *)q->ti_next)
131 		if (SEQ_GT(q->ti_seq, ti->ti_seq))
132 			break;
133 
134 	/*
135 	 * If there is a preceding segment, it may provide some of
136 	 * our data already.  If so, drop the data from the incoming
137 	 * segment.  If it provides all of our data, drop us.
138 	 */
139 	if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
140 		register int i;
141 		q = (struct tcpiphdr *)q->ti_prev;
142 		/* conversion to int (in i) handles seq wraparound */
143 		i = q->ti_seq + q->ti_len - ti->ti_seq;
144 		if (i > 0) {
145 			if (i >= ti->ti_len) {
146 				tcpstat.tcps_rcvduppack++;
147 				tcpstat.tcps_rcvdupbyte += ti->ti_len;
148 				m_freem(m);
149 				return (0);
150 			}
151 			m_adj(m, i);
152 			ti->ti_len -= i;
153 			ti->ti_seq += i;
154 		}
155 		q = (struct tcpiphdr *)(q->ti_next);
156 	}
157 	tcpstat.tcps_rcvoopack++;
158 	tcpstat.tcps_rcvoobyte += ti->ti_len;
159 	REASS_MBUF(ti) = m;		/* XXX */
160 
161 	/*
162 	 * While we overlap succeeding segments trim them or,
163 	 * if they are completely covered, dequeue them.
164 	 */
165 	while (q != (struct tcpiphdr *)tp) {
166 		register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
167 		if (i <= 0)
168 			break;
169 		if (i < q->ti_len) {
170 			q->ti_seq += i;
171 			q->ti_len -= i;
172 			m_adj(REASS_MBUF(q), i);
173 			break;
174 		}
175 		q = (struct tcpiphdr *)q->ti_next;
176 		m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
177 		remque(q->ti_prev);
178 		m_freem(m);
179 	}
180 
181 	/*
182 	 * Stick new segment in its place.
183 	 */
184 	insque(ti, q->ti_prev);
185 
186 present:
187 	/*
188 	 * Present data to user, advancing rcv_nxt through
189 	 * completed sequence space.
190 	 */
191 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
192 		return (0);
193 	ti = tp->seg_next;
194 	if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
195 		return (0);
196 	if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
197 		return (0);
198 	do {
199 		tp->rcv_nxt += ti->ti_len;
200 		flags = ti->ti_flags & TH_FIN;
201 		remque(ti);
202 		m = REASS_MBUF(ti);
203 		ti = (struct tcpiphdr *)ti->ti_next;
204 		if (so->so_state & SS_CANTRCVMORE)
205 			m_freem(m);
206 		else
207 			sbappend(&so->so_rcv, m);
208 	} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
209 	sorwakeup(so);
210 	return (flags);
211 }
212 
213 /*
214  * TCP input routine, follows pages 65-76 of the
215  * protocol specification dated September, 1981 very closely.
216  */
217 void
218 tcp_input(m, iphlen)
219 	register struct mbuf *m;
220 	int iphlen;
221 {
222 	register struct tcpiphdr *ti;
223 	register struct inpcb *inp;
224 	caddr_t optp = NULL;
225 	int optlen;
226 	int len, tlen, off;
227 	register struct tcpcb *tp = 0;
228 	register int tiflags;
229 	struct socket *so;
230 	int todrop, acked, ourfinisacked, needoutput = 0;
231 	short ostate;
232 	struct in_addr laddr;
233 	int dropsocket = 0;
234 	int iss = 0;
235 	u_long tiwin;
236 	u_int32_t ts_val, ts_ecr;
237 	int ts_present = 0;
238 
239 	tcpstat.tcps_rcvtotal++;
240 	/*
241 	 * Get IP and TCP header together in first mbuf.
242 	 * Note: IP leaves IP header in first mbuf.
243 	 */
244 	ti = mtod(m, struct tcpiphdr *);
245 	if (iphlen > sizeof (struct ip))
246 		ip_stripoptions(m, (struct mbuf *)0);
247 	if (m->m_len < sizeof (struct tcpiphdr)) {
248 		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
249 			tcpstat.tcps_rcvshort++;
250 			return;
251 		}
252 		ti = mtod(m, struct tcpiphdr *);
253 	}
254 
255 	/*
256 	 * Checksum extended TCP header and data.
257 	 */
258 	tlen = ((struct ip *)ti)->ip_len;
259 	len = sizeof (struct ip) + tlen;
260 	ti->ti_next = ti->ti_prev = 0;
261 	ti->ti_x1 = 0;
262 	ti->ti_len = (u_int16_t)tlen;
263 	HTONS(ti->ti_len);
264 	if (ti->ti_sum = in_cksum(m, len)) {
265 		tcpstat.tcps_rcvbadsum++;
266 		goto drop;
267 	}
268 #endif /* TUBA_INCLUDE */
269 
270 	/*
271 	 * Check that TCP offset makes sense,
272 	 * pull out TCP options and adjust length.		XXX
273 	 */
274 	off = ti->ti_off << 2;
275 	if (off < sizeof (struct tcphdr) || off > tlen) {
276 		tcpstat.tcps_rcvbadoff++;
277 		goto drop;
278 	}
279 	tlen -= off;
280 	ti->ti_len = tlen;
281 	if (off > sizeof (struct tcphdr)) {
282 		if (m->m_len < sizeof(struct ip) + off) {
283 			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
284 				tcpstat.tcps_rcvshort++;
285 				return;
286 			}
287 			ti = mtod(m, struct tcpiphdr *);
288 		}
289 		optlen = off - sizeof (struct tcphdr);
290 		optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
291 		/*
292 		 * Do quick retrieval of timestamp options ("options
293 		 * prediction?").  If timestamp is the only option and it's
294 		 * formatted as recommended in RFC 1323 appendix A, we
295 		 * quickly get the values now and not bother calling
296 		 * tcp_dooptions(), etc.
297 		 */
298 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
299 		     (optlen > TCPOLEN_TSTAMP_APPA &&
300 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
301 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
302 		     (ti->ti_flags & TH_SYN) == 0) {
303 			ts_present = 1;
304 			ts_val = ntohl(*(u_int32_t *)(optp + 4));
305 			ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
306 			optp = NULL;	/* we've parsed the options */
307 		}
308 	}
309 	tiflags = ti->ti_flags;
310 
311 	/*
312 	 * Convert TCP protocol specific fields to host format.
313 	 */
314 	NTOHL(ti->ti_seq);
315 	NTOHL(ti->ti_ack);
316 	NTOHS(ti->ti_win);
317 	NTOHS(ti->ti_urp);
318 
319 	/*
320 	 * Locate pcb for segment.
321 	 */
322 findpcb:
323 	inp = tcp_last_inpcb;
324 	if (inp->inp_lport != ti->ti_dport ||
325 	    inp->inp_fport != ti->ti_sport ||
326 	    inp->inp_faddr.s_addr != ti->ti_src.s_addr ||
327 	    inp->inp_laddr.s_addr != ti->ti_dst.s_addr) {
328 		inp = in_pcblookup(&tcb, ti->ti_src, ti->ti_sport,
329 		    ti->ti_dst, ti->ti_dport, INPLOOKUP_WILDCARD);
330 		if (inp)
331 			tcp_last_inpcb = inp;
332 		++tcpstat.tcps_pcbcachemiss;
333 	}
334 
335 	/*
336 	 * If the state is CLOSED (i.e., TCB does not exist) then
337 	 * all data in the incoming segment is discarded.
338 	 * If the TCB exists but is in CLOSED state, it is embryonic,
339 	 * but should either do a listen or a connect soon.
340 	 */
341 	if (inp == 0)
342 		goto dropwithreset;
343 	tp = intotcpcb(inp);
344 	if (tp == 0)
345 		goto dropwithreset;
346 	if (tp->t_state == TCPS_CLOSED)
347 		goto drop;
348 
349 	/* Unscale the window into a 32-bit value. */
350 	if ((tiflags & TH_SYN) == 0)
351 		tiwin = ti->ti_win << tp->snd_scale;
352 	else
353 		tiwin = ti->ti_win;
354 
355 	so = inp->inp_socket;
356 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
357 		if (so->so_options & SO_DEBUG) {
358 			ostate = tp->t_state;
359 			tcp_saveti = *ti;
360 		}
361 		if (so->so_options & SO_ACCEPTCONN) {
362 			so = sonewconn(so, 0);
363 			if (so == 0)
364 				goto drop;
365 			/*
366 			 * This is ugly, but ....
367 			 *
368 			 * Mark socket as temporary until we're
369 			 * committed to keeping it.  The code at
370 			 * ``drop'' and ``dropwithreset'' check the
371 			 * flag dropsocket to see if the temporary
372 			 * socket created here should be discarded.
373 			 * We mark the socket as discardable until
374 			 * we're committed to it below in TCPS_LISTEN.
375 			 */
376 			dropsocket++;
377 			inp = (struct inpcb *)so->so_pcb;
378 			inp->inp_laddr = ti->ti_dst;
379 			inp->inp_lport = ti->ti_dport;
380 #if BSD>=43
381 			inp->inp_options = ip_srcroute();
382 #endif
383 			tp = intotcpcb(inp);
384 			tp->t_state = TCPS_LISTEN;
385 
386 			/* Compute proper scaling value from buffer space
387 			 */
388 			while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
389 			   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
390 				tp->request_r_scale++;
391 		}
392 	}
393 
394 	/*
395 	 * Segment received on connection.
396 	 * Reset idle time and keep-alive timer.
397 	 */
398 	tp->t_idle = 0;
399 	tp->t_timer[TCPT_KEEP] = tcp_keepidle;
400 
401 	/*
402 	 * Process options if not in LISTEN state,
403 	 * else do it below (after getting remote address).
404 	 */
405 	if (optp && tp->t_state != TCPS_LISTEN)
406 		tcp_dooptions(tp, optp, optlen, ti,
407 			&ts_present, &ts_val, &ts_ecr);
408 
409 	/*
410 	 * Header prediction: check for the two common cases
411 	 * of a uni-directional data xfer.  If the packet has
412 	 * no control flags, is in-sequence, the window didn't
413 	 * change and we're not retransmitting, it's a
414 	 * candidate.  If the length is zero and the ack moved
415 	 * forward, we're the sender side of the xfer.  Just
416 	 * free the data acked & wake any higher level process
417 	 * that was blocked waiting for space.  If the length
418 	 * is non-zero and the ack didn't move, we're the
419 	 * receiver side.  If we're getting packets in-order
420 	 * (the reassembly queue is empty), add the data to
421 	 * the socket buffer and note that we need a delayed ack.
422 	 */
423 	if (tp->t_state == TCPS_ESTABLISHED &&
424 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
425 	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) &&
426 	    ti->ti_seq == tp->rcv_nxt &&
427 	    tiwin && tiwin == tp->snd_wnd &&
428 	    tp->snd_nxt == tp->snd_max) {
429 
430 		/*
431 		 * If last ACK falls within this segment's sequence numbers,
432 		 *  record the timestamp.
433 		 */
434 		if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
435 		   SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
436 			tp->ts_recent_age = tcp_now;
437 			tp->ts_recent = ts_val;
438 		}
439 
440 		if (ti->ti_len == 0) {
441 			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
442 			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
443 			    tp->snd_cwnd >= tp->snd_wnd) {
444 				/*
445 				 * this is a pure ack for outstanding data.
446 				 */
447 				++tcpstat.tcps_predack;
448 				if (ts_present)
449 					tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
450 				else if (tp->t_rtt &&
451 					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
452 					tcp_xmit_timer(tp, tp->t_rtt);
453 				acked = ti->ti_ack - tp->snd_una;
454 				tcpstat.tcps_rcvackpack++;
455 				tcpstat.tcps_rcvackbyte += acked;
456 				sbdrop(&so->so_snd, acked);
457 				tp->snd_una = ti->ti_ack;
458 				m_freem(m);
459 
460 				/*
461 				 * If all outstanding data are acked, stop
462 				 * retransmit timer, otherwise restart timer
463 				 * using current (possibly backed-off) value.
464 				 * If process is waiting for space,
465 				 * wakeup/selwakeup/signal.  If data
466 				 * are ready to send, let tcp_output
467 				 * decide between more output or persist.
468 				 */
469 				if (tp->snd_una == tp->snd_max)
470 					tp->t_timer[TCPT_REXMT] = 0;
471 				else if (tp->t_timer[TCPT_PERSIST] == 0)
472 					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
473 
474 				if (so->so_snd.sb_flags & SB_NOTIFY)
475 					sowwakeup(so);
476 				if (so->so_snd.sb_cc)
477 					(void) tcp_output(tp);
478 				return;
479 			}
480 		} else if (ti->ti_ack == tp->snd_una &&
481 		    tp->seg_next == (struct tcpiphdr *)tp &&
482 		    ti->ti_len <= sbspace(&so->so_rcv)) {
483 			/*
484 			 * this is a pure, in-sequence data packet
485 			 * with nothing on the reassembly queue and
486 			 * we have enough buffer space to take it.
487 			 */
488 			++tcpstat.tcps_preddat;
489 			tp->rcv_nxt += ti->ti_len;
490 			tcpstat.tcps_rcvpack++;
491 			tcpstat.tcps_rcvbyte += ti->ti_len;
492 			/*
493 			 * Drop TCP, IP headers and TCP options then add data
494 			 * to socket buffer.
495 			 */
496 			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
497 			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
498 			sbappend(&so->so_rcv, m);
499 			sorwakeup(so);
500 			if (ti->ti_flags & TH_PUSH)
501 				tp->t_flags |= TF_ACKNOW;
502 			else
503 				tp->t_flags |= TF_DELACK;
504 			return;
505 		}
506 	}
507 
508 	/*
509 	 * Drop TCP, IP headers and TCP options.
510 	 */
511 	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
512 	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
513 
514 	/*
515 	 * Calculate amount of space in receive window,
516 	 * and then do TCP input processing.
517 	 * Receive window is amount of space in rcv queue,
518 	 * but not less than advertised window.
519 	 */
520 	{ int win;
521 
522 	win = sbspace(&so->so_rcv);
523 	if (win < 0)
524 		win = 0;
525 	tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
526 	}
527 
528 	switch (tp->t_state) {
529 
530 	/*
531 	 * If the state is LISTEN then ignore segment if it contains an RST.
532 	 * If the segment contains an ACK then it is bad and send a RST.
533 	 * If it does not contain a SYN then it is not interesting; drop it.
534 	 * Don't bother responding if the destination was a broadcast.
535 	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
536 	 * tp->iss, and send a segment:
537 	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
538 	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
539 	 * Fill in remote peer address fields if not previously specified.
540 	 * Enter SYN_RECEIVED state, and process any other fields of this
541 	 * segment in this state.
542 	 */
543 	case TCPS_LISTEN: {
544 		struct mbuf *am;
545 		register struct sockaddr_in *sin;
546 
547 		if (tiflags & TH_RST)
548 			goto drop;
549 		if (tiflags & TH_ACK)
550 			goto dropwithreset;
551 		if ((tiflags & TH_SYN) == 0)
552 			goto drop;
553 		/*
554 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
555 		 * in_broadcast() should never return true on a received
556 		 * packet with M_BCAST not set.
557 		 */
558 		if (m->m_flags & (M_BCAST|M_MCAST) ||
559 		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
560 			goto drop;
561 		am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
562 		if (am == NULL)
563 			goto drop;
564 		am->m_len = sizeof (struct sockaddr_in);
565 		sin = mtod(am, struct sockaddr_in *);
566 		sin->sin_family = AF_INET;
567 		sin->sin_len = sizeof(*sin);
568 		sin->sin_addr = ti->ti_src;
569 		sin->sin_port = ti->ti_sport;
570 		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
571 		laddr = inp->inp_laddr;
572 		if (inp->inp_laddr.s_addr == INADDR_ANY)
573 			inp->inp_laddr = ti->ti_dst;
574 		if (in_pcbconnect(inp, am)) {
575 			inp->inp_laddr = laddr;
576 			(void) m_free(am);
577 			goto drop;
578 		}
579 		(void) m_free(am);
580 		tp->t_template = tcp_template(tp);
581 		if (tp->t_template == 0) {
582 			tp = tcp_drop(tp, ENOBUFS);
583 			dropsocket = 0;		/* socket is already gone */
584 			goto drop;
585 		}
586 		if (optp)
587 			tcp_dooptions(tp, optp, optlen, ti,
588 				&ts_present, &ts_val, &ts_ecr);
589 		if (iss)
590 			tp->iss = iss;
591 		else
592 			tp->iss = tcp_iss;
593 		tcp_iss += TCP_ISSINCR/2;
594 		tp->irs = ti->ti_seq;
595 		tcp_sendseqinit(tp);
596 		tcp_rcvseqinit(tp);
597 		tp->t_flags |= TF_ACKNOW;
598 		tp->t_state = TCPS_SYN_RECEIVED;
599 		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
600 		dropsocket = 0;		/* committed to socket */
601 		tcpstat.tcps_accepts++;
602 		goto trimthenstep6;
603 		}
604 
605 	/*
606 	 * If the state is SYN_SENT:
607 	 *	if seg contains an ACK, but not for our SYN, drop the input.
608 	 *	if seg contains a RST, then drop the connection.
609 	 *	if seg does not contain SYN, then drop it.
610 	 * Otherwise this is an acceptable SYN segment
611 	 *	initialize tp->rcv_nxt and tp->irs
612 	 *	if seg contains ack then advance tp->snd_una
613 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
614 	 *	arrange for segment to be acked (eventually)
615 	 *	continue processing rest of data/controls, beginning with URG
616 	 */
617 	case TCPS_SYN_SENT:
618 		if ((tiflags & TH_ACK) &&
619 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
620 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
621 			goto dropwithreset;
622 		if (tiflags & TH_RST) {
623 			if (tiflags & TH_ACK)
624 				tp = tcp_drop(tp, ECONNREFUSED);
625 			goto drop;
626 		}
627 		if ((tiflags & TH_SYN) == 0)
628 			goto drop;
629 		if (tiflags & TH_ACK) {
630 			tp->snd_una = ti->ti_ack;
631 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
632 				tp->snd_nxt = tp->snd_una;
633 		}
634 		tp->t_timer[TCPT_REXMT] = 0;
635 		tp->irs = ti->ti_seq;
636 		tcp_rcvseqinit(tp);
637 		tp->t_flags |= TF_ACKNOW;
638 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
639 			tcpstat.tcps_connects++;
640 			soisconnected(so);
641 			tp->t_state = TCPS_ESTABLISHED;
642 			/* Do window scaling on this connection? */
643 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
644 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
645 				tp->snd_scale = tp->requested_s_scale;
646 				tp->rcv_scale = tp->request_r_scale;
647 			}
648 			(void) tcp_reass(tp, (struct tcpiphdr *)0,
649 				(struct mbuf *)0);
650 			/*
651 			 * if we didn't have to retransmit the SYN,
652 			 * use its rtt as our initial srtt & rtt var.
653 			 */
654 			if (tp->t_rtt)
655 				tcp_xmit_timer(tp, tp->t_rtt);
656 		} else
657 			tp->t_state = TCPS_SYN_RECEIVED;
658 
659 trimthenstep6:
660 		/*
661 		 * Advance ti->ti_seq to correspond to first data byte.
662 		 * If data, trim to stay within window,
663 		 * dropping FIN if necessary.
664 		 */
665 		ti->ti_seq++;
666 		if (ti->ti_len > tp->rcv_wnd) {
667 			todrop = ti->ti_len - tp->rcv_wnd;
668 			m_adj(m, -todrop);
669 			ti->ti_len = tp->rcv_wnd;
670 			tiflags &= ~TH_FIN;
671 			tcpstat.tcps_rcvpackafterwin++;
672 			tcpstat.tcps_rcvbyteafterwin += todrop;
673 		}
674 		tp->snd_wl1 = ti->ti_seq - 1;
675 		tp->rcv_up = ti->ti_seq;
676 		goto step6;
677 	}
678 
679 	/*
680 	 * States other than LISTEN or SYN_SENT.
681 	 * First check timestamp, if present.
682 	 * Then check that at least some bytes of segment are within
683 	 * receive window.  If segment begins before rcv_nxt,
684 	 * drop leading data (and SYN); if nothing left, just ack.
685 	 *
686 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
687 	 * and it's less than ts_recent, drop it.
688 	 */
689 	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
690 	    TSTMP_LT(ts_val, tp->ts_recent)) {
691 
692 		/* Check to see if ts_recent is over 24 days old.  */
693 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
694 			/*
695 			 * Invalidate ts_recent.  If this segment updates
696 			 * ts_recent, the age will be reset later and ts_recent
697 			 * will get a valid value.  If it does not, setting
698 			 * ts_recent to zero will at least satisfy the
699 			 * requirement that zero be placed in the timestamp
700 			 * echo reply when ts_recent isn't valid.  The
701 			 * age isn't reset until we get a valid ts_recent
702 			 * because we don't want out-of-order segments to be
703 			 * dropped when ts_recent is old.
704 			 */
705 			tp->ts_recent = 0;
706 		} else {
707 			tcpstat.tcps_rcvduppack++;
708 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
709 			tcpstat.tcps_pawsdrop++;
710 			goto dropafterack;
711 		}
712 	}
713 
714 	todrop = tp->rcv_nxt - ti->ti_seq;
715 	if (todrop > 0) {
716 		if (tiflags & TH_SYN) {
717 			tiflags &= ~TH_SYN;
718 			ti->ti_seq++;
719 			if (ti->ti_urp > 1)
720 				ti->ti_urp--;
721 			else
722 				tiflags &= ~TH_URG;
723 			todrop--;
724 		}
725 		if (todrop >= ti->ti_len) {
726 			/*
727 			 * Any valid FIN must be to the left of the
728 			 * window.  At this point, FIN must be a
729 			 * duplicate or out-of-sequence, so drop it.
730 			 */
731 			tiflags &= ~TH_FIN;
732 			/*
733 			 * Send ACK to resynchronize, and drop any data,
734 			 * but keep on processing for RST or ACK.
735 			 */
736 			tp->t_flags |= TF_ACKNOW;
737 			tcpstat.tcps_rcvdupbyte += todrop = ti->ti_len;
738 			tcpstat.tcps_rcvduppack++;
739 		} else {
740 			tcpstat.tcps_rcvpartduppack++;
741 			tcpstat.tcps_rcvpartdupbyte += todrop;
742 		}
743 		m_adj(m, todrop);
744 		ti->ti_seq += todrop;
745 		ti->ti_len -= todrop;
746 		if (ti->ti_urp > todrop)
747 			ti->ti_urp -= todrop;
748 		else {
749 			tiflags &= ~TH_URG;
750 			ti->ti_urp = 0;
751 		}
752 	}
753 
754 	/*
755 	 * If new data are received on a connection after the
756 	 * user processes are gone, then RST the other end.
757 	 */
758 	if ((so->so_state & SS_NOFDREF) &&
759 	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
760 		tp = tcp_close(tp);
761 		tcpstat.tcps_rcvafterclose++;
762 		goto dropwithreset;
763 	}
764 
765 	/*
766 	 * If segment ends after window, drop trailing data
767 	 * (and PUSH and FIN); if nothing left, just ACK.
768 	 */
769 	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
770 	if (todrop > 0) {
771 		tcpstat.tcps_rcvpackafterwin++;
772 		if (todrop >= ti->ti_len) {
773 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
774 			/*
775 			 * If a new connection request is received
776 			 * while in TIME_WAIT, drop the old connection
777 			 * and start over if the sequence numbers
778 			 * are above the previous ones.
779 			 */
780 			if (tiflags & TH_SYN &&
781 			    tp->t_state == TCPS_TIME_WAIT &&
782 			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
783 				iss = tp->rcv_nxt + TCP_ISSINCR;
784 				tp = tcp_close(tp);
785 				goto findpcb;
786 			}
787 			/*
788 			 * If window is closed can only take segments at
789 			 * window edge, and have to drop data and PUSH from
790 			 * incoming segments.  Continue processing, but
791 			 * remember to ack.  Otherwise, drop segment
792 			 * and ack.
793 			 */
794 			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
795 				tp->t_flags |= TF_ACKNOW;
796 				tcpstat.tcps_rcvwinprobe++;
797 			} else
798 				goto dropafterack;
799 		} else
800 			tcpstat.tcps_rcvbyteafterwin += todrop;
801 		m_adj(m, -todrop);
802 		ti->ti_len -= todrop;
803 		tiflags &= ~(TH_PUSH|TH_FIN);
804 	}
805 
806 	/*
807 	 * If last ACK falls within this segment's sequence numbers,
808 	 * record its timestamp.
809 	 */
810 	if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
811 	    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
812 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
813 		tp->ts_recent_age = tcp_now;
814 		tp->ts_recent = ts_val;
815 	}
816 
817 	/*
818 	 * If the RST bit is set examine the state:
819 	 *    SYN_RECEIVED STATE:
820 	 *	If passive open, return to LISTEN state.
821 	 *	If active open, inform user that connection was refused.
822 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
823 	 *	Inform user that connection was reset, and close tcb.
824 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
825 	 *	Close the tcb.
826 	 */
827 	if (tiflags&TH_RST) switch (tp->t_state) {
828 
829 	case TCPS_SYN_RECEIVED:
830 		so->so_error = ECONNREFUSED;
831 		goto close;
832 
833 	case TCPS_ESTABLISHED:
834 	case TCPS_FIN_WAIT_1:
835 	case TCPS_FIN_WAIT_2:
836 	case TCPS_CLOSE_WAIT:
837 		so->so_error = ECONNRESET;
838 	close:
839 		tp->t_state = TCPS_CLOSED;
840 		tcpstat.tcps_drops++;
841 		tp = tcp_close(tp);
842 		goto drop;
843 
844 	case TCPS_CLOSING:
845 	case TCPS_LAST_ACK:
846 	case TCPS_TIME_WAIT:
847 		tp = tcp_close(tp);
848 		goto drop;
849 	}
850 
851 	/*
852 	 * If a SYN is in the window, then this is an
853 	 * error and we send an RST and drop the connection.
854 	 */
855 	if (tiflags & TH_SYN) {
856 		tp = tcp_drop(tp, ECONNRESET);
857 		goto dropwithreset;
858 	}
859 
860 	/*
861 	 * If the ACK bit is off we drop the segment and return.
862 	 */
863 	if ((tiflags & TH_ACK) == 0)
864 		goto drop;
865 
866 	/*
867 	 * Ack processing.
868 	 */
869 	switch (tp->t_state) {
870 
871 	/*
872 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
873 	 * ESTABLISHED state and continue processing, otherwise
874 	 * send an RST.
875 	 */
876 	case TCPS_SYN_RECEIVED:
877 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
878 		    SEQ_GT(ti->ti_ack, tp->snd_max))
879 			goto dropwithreset;
880 		tcpstat.tcps_connects++;
881 		soisconnected(so);
882 		tp->t_state = TCPS_ESTABLISHED;
883 		/* Do window scaling? */
884 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
885 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
886 			tp->snd_scale = tp->requested_s_scale;
887 			tp->rcv_scale = tp->request_r_scale;
888 		}
889 		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
890 		tp->snd_wl1 = ti->ti_seq - 1;
891 		/* fall into ... */
892 
893 	/*
894 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
895 	 * ACKs.  If the ack is in the range
896 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
897 	 * then advance tp->snd_una to ti->ti_ack and drop
898 	 * data from the retransmission queue.  If this ACK reflects
899 	 * more up to date window information we update our window information.
900 	 */
901 	case TCPS_ESTABLISHED:
902 	case TCPS_FIN_WAIT_1:
903 	case TCPS_FIN_WAIT_2:
904 	case TCPS_CLOSE_WAIT:
905 	case TCPS_CLOSING:
906 	case TCPS_LAST_ACK:
907 	case TCPS_TIME_WAIT:
908 
909 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
910 			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
911 				tcpstat.tcps_rcvdupack++;
912 				/*
913 				 * If we have outstanding data (other than
914 				 * a window probe), this is a completely
915 				 * duplicate ack (ie, window info didn't
916 				 * change), the ack is the biggest we've
917 				 * seen and we've seen exactly our rexmt
918 				 * threshhold of them, assume a packet
919 				 * has been dropped and retransmit it.
920 				 * Kludge snd_nxt & the congestion
921 				 * window so we send only this one
922 				 * packet.
923 				 *
924 				 * We know we're losing at the current
925 				 * window size so do congestion avoidance
926 				 * (set ssthresh to half the current window
927 				 * and pull our congestion window back to
928 				 * the new ssthresh).
929 				 *
930 				 * Dup acks mean that packets have left the
931 				 * network (they're now cached at the receiver)
932 				 * so bump cwnd by the amount in the receiver
933 				 * to keep a constant cwnd packets in the
934 				 * network.
935 				 */
936 				if (tp->t_timer[TCPT_REXMT] == 0 ||
937 				    ti->ti_ack != tp->snd_una)
938 					tp->t_dupacks = 0;
939 				else if (++tp->t_dupacks == tcprexmtthresh) {
940 					tcp_seq onxt = tp->snd_nxt;
941 					u_int win =
942 					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
943 						tp->t_maxseg;
944 
945 					if (win < 2)
946 						win = 2;
947 					tp->snd_ssthresh = win * tp->t_maxseg;
948 					tp->t_timer[TCPT_REXMT] = 0;
949 					tp->t_rtt = 0;
950 					tp->snd_nxt = ti->ti_ack;
951 					tp->snd_cwnd = tp->t_maxseg;
952 					(void) tcp_output(tp);
953 					tp->snd_cwnd = tp->snd_ssthresh +
954 					       tp->t_maxseg * tp->t_dupacks;
955 					if (SEQ_GT(onxt, tp->snd_nxt))
956 						tp->snd_nxt = onxt;
957 					goto drop;
958 				} else if (tp->t_dupacks > tcprexmtthresh) {
959 					tp->snd_cwnd += tp->t_maxseg;
960 					(void) tcp_output(tp);
961 					goto drop;
962 				}
963 			} else
964 				tp->t_dupacks = 0;
965 			break;
966 		}
967 		/*
968 		 * If the congestion window was inflated to account
969 		 * for the other side's cached packets, retract it.
970 		 */
971 		if (tp->t_dupacks > tcprexmtthresh &&
972 		    tp->snd_cwnd > tp->snd_ssthresh)
973 			tp->snd_cwnd = tp->snd_ssthresh;
974 		tp->t_dupacks = 0;
975 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
976 			tcpstat.tcps_rcvacktoomuch++;
977 			goto dropafterack;
978 		}
979 		acked = ti->ti_ack - tp->snd_una;
980 		tcpstat.tcps_rcvackpack++;
981 		tcpstat.tcps_rcvackbyte += acked;
982 
983 		/*
984 		 * If we have a timestamp reply, update smoothed
985 		 * round trip time.  If no timestamp is present but
986 		 * transmit timer is running and timed sequence
987 		 * number was acked, update smoothed round trip time.
988 		 * Since we now have an rtt measurement, cancel the
989 		 * timer backoff (cf., Phil Karn's retransmit alg.).
990 		 * Recompute the initial retransmit timer.
991 		 */
992 		if (ts_present)
993 			tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
994 		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
995 			tcp_xmit_timer(tp,tp->t_rtt);
996 
997 		/*
998 		 * If all outstanding data is acked, stop retransmit
999 		 * timer and remember to restart (more output or persist).
1000 		 * If there is more data to be acked, restart retransmit
1001 		 * timer, using current (possibly backed-off) value.
1002 		 */
1003 		if (ti->ti_ack == tp->snd_max) {
1004 			tp->t_timer[TCPT_REXMT] = 0;
1005 			needoutput = 1;
1006 		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1007 			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1008 		/*
1009 		 * When new data is acked, open the congestion window.
1010 		 * If the window gives us less than ssthresh packets
1011 		 * in flight, open exponentially (maxseg per packet).
1012 		 * Otherwise open linearly: maxseg per window
1013 		 * (maxseg^2 / cwnd per packet), plus a constant
1014 		 * fraction of a packet (maxseg/8) to help larger windows
1015 		 * open quickly enough.
1016 		 */
1017 		{
1018 		register u_int cw = tp->snd_cwnd;
1019 		register u_int incr = tp->t_maxseg;
1020 
1021 		if (cw > tp->snd_ssthresh)
1022 			incr = incr * incr / cw + incr / 8;
1023 		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1024 		}
1025 		if (acked > so->so_snd.sb_cc) {
1026 			tp->snd_wnd -= so->so_snd.sb_cc;
1027 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1028 			ourfinisacked = 1;
1029 		} else {
1030 			sbdrop(&so->so_snd, acked);
1031 			tp->snd_wnd -= acked;
1032 			ourfinisacked = 0;
1033 		}
1034 		if (so->so_snd.sb_flags & SB_NOTIFY)
1035 			sowwakeup(so);
1036 		tp->snd_una = ti->ti_ack;
1037 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1038 			tp->snd_nxt = tp->snd_una;
1039 
1040 		switch (tp->t_state) {
1041 
1042 		/*
1043 		 * In FIN_WAIT_1 STATE in addition to the processing
1044 		 * for the ESTABLISHED state if our FIN is now acknowledged
1045 		 * then enter FIN_WAIT_2.
1046 		 */
1047 		case TCPS_FIN_WAIT_1:
1048 			if (ourfinisacked) {
1049 				/*
1050 				 * If we can't receive any more
1051 				 * data, then closing user can proceed.
1052 				 * Starting the timer is contrary to the
1053 				 * specification, but if we don't get a FIN
1054 				 * we'll hang forever.
1055 				 */
1056 				if (so->so_state & SS_CANTRCVMORE) {
1057 					soisdisconnected(so);
1058 					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1059 				}
1060 				tp->t_state = TCPS_FIN_WAIT_2;
1061 			}
1062 			break;
1063 
1064 	 	/*
1065 		 * In CLOSING STATE in addition to the processing for
1066 		 * the ESTABLISHED state if the ACK acknowledges our FIN
1067 		 * then enter the TIME-WAIT state, otherwise ignore
1068 		 * the segment.
1069 		 */
1070 		case TCPS_CLOSING:
1071 			if (ourfinisacked) {
1072 				tp->t_state = TCPS_TIME_WAIT;
1073 				tcp_canceltimers(tp);
1074 				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1075 				soisdisconnected(so);
1076 			}
1077 			break;
1078 
1079 		/*
1080 		 * In LAST_ACK, we may still be waiting for data to drain
1081 		 * and/or to be acked, as well as for the ack of our FIN.
1082 		 * If our FIN is now acknowledged, delete the TCB,
1083 		 * enter the closed state and return.
1084 		 */
1085 		case TCPS_LAST_ACK:
1086 			if (ourfinisacked) {
1087 				tp = tcp_close(tp);
1088 				goto drop;
1089 			}
1090 			break;
1091 
1092 		/*
1093 		 * In TIME_WAIT state the only thing that should arrive
1094 		 * is a retransmission of the remote FIN.  Acknowledge
1095 		 * it and restart the finack timer.
1096 		 */
1097 		case TCPS_TIME_WAIT:
1098 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1099 			goto dropafterack;
1100 		}
1101 	}
1102 
1103 step6:
1104 	/*
1105 	 * Update window information.
1106 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1107 	 */
1108 	if ((tiflags & TH_ACK) &&
1109 	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq &&
1110 	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1111 	     tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) {
1112 		/* keep track of pure window updates */
1113 		if (ti->ti_len == 0 &&
1114 		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1115 			tcpstat.tcps_rcvwinupd++;
1116 		tp->snd_wnd = tiwin;
1117 		tp->snd_wl1 = ti->ti_seq;
1118 		tp->snd_wl2 = ti->ti_ack;
1119 		if (tp->snd_wnd > tp->max_sndwnd)
1120 			tp->max_sndwnd = tp->snd_wnd;
1121 		needoutput = 1;
1122 	}
1123 
1124 	/*
1125 	 * Process segments with URG.
1126 	 */
1127 	if ((tiflags & TH_URG) && ti->ti_urp &&
1128 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1129 		/*
1130 		 * This is a kludge, but if we receive and accept
1131 		 * random urgent pointers, we'll crash in
1132 		 * soreceive.  It's hard to imagine someone
1133 		 * actually wanting to send this much urgent data.
1134 		 */
1135 		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1136 			ti->ti_urp = 0;			/* XXX */
1137 			tiflags &= ~TH_URG;		/* XXX */
1138 			goto dodata;			/* XXX */
1139 		}
1140 		/*
1141 		 * If this segment advances the known urgent pointer,
1142 		 * then mark the data stream.  This should not happen
1143 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1144 		 * a FIN has been received from the remote side.
1145 		 * In these states we ignore the URG.
1146 		 *
1147 		 * According to RFC961 (Assigned Protocols),
1148 		 * the urgent pointer points to the last octet
1149 		 * of urgent data.  We continue, however,
1150 		 * to consider it to indicate the first octet
1151 		 * of data past the urgent section as the original
1152 		 * spec states (in one of two places).
1153 		 */
1154 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1155 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1156 			so->so_oobmark = so->so_rcv.sb_cc +
1157 			    (tp->rcv_up - tp->rcv_nxt) - 1;
1158 			if (so->so_oobmark == 0)
1159 				so->so_state |= SS_RCVATMARK;
1160 			sohasoutofband(so);
1161 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1162 		}
1163 		/*
1164 		 * Remove out of band data so doesn't get presented to user.
1165 		 * This can happen independent of advancing the URG pointer,
1166 		 * but if two URG's are pending at once, some out-of-band
1167 		 * data may creep in... ick.
1168 		 */
1169 		if (ti->ti_urp <= ti->ti_len
1170 #ifdef SO_OOBINLINE
1171 		     && (so->so_options & SO_OOBINLINE) == 0
1172 #endif
1173 		     )
1174 			tcp_pulloutofband(so, ti, m);
1175 	} else
1176 		/*
1177 		 * If no out of band data is expected,
1178 		 * pull receive urgent pointer along
1179 		 * with the receive window.
1180 		 */
1181 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1182 			tp->rcv_up = tp->rcv_nxt;
1183 dodata:							/* XXX */
1184 
1185 	/*
1186 	 * Process the segment text, merging it into the TCP sequencing queue,
1187 	 * and arranging for acknowledgment of receipt if necessary.
1188 	 * This process logically involves adjusting tp->rcv_wnd as data
1189 	 * is presented to the user (this happens in tcp_usrreq.c,
1190 	 * case PRU_RCVD).  If a FIN has already been received on this
1191 	 * connection then we just ignore the text.
1192 	 */
1193 	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1194 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1195 		TCP_REASS(tp, ti, m, so, tiflags);
1196 		/*
1197 		 * Note the amount of data that peer has sent into
1198 		 * our window, in order to estimate the sender's
1199 		 * buffer size.
1200 		 */
1201 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1202 	} else {
1203 		m_freem(m);
1204 		tiflags &= ~TH_FIN;
1205 	}
1206 
1207 	/*
1208 	 * If FIN is received ACK the FIN and let the user know
1209 	 * that the connection is closing.
1210 	 */
1211 	if (tiflags & TH_FIN) {
1212 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1213 			socantrcvmore(so);
1214 			tp->t_flags |= TF_ACKNOW;
1215 			tp->rcv_nxt++;
1216 		}
1217 		switch (tp->t_state) {
1218 
1219 	 	/*
1220 		 * In SYN_RECEIVED and ESTABLISHED STATES
1221 		 * enter the CLOSE_WAIT state.
1222 		 */
1223 		case TCPS_SYN_RECEIVED:
1224 		case TCPS_ESTABLISHED:
1225 			tp->t_state = TCPS_CLOSE_WAIT;
1226 			break;
1227 
1228 	 	/*
1229 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1230 		 * enter the CLOSING state.
1231 		 */
1232 		case TCPS_FIN_WAIT_1:
1233 			tp->t_state = TCPS_CLOSING;
1234 			break;
1235 
1236 	 	/*
1237 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1238 		 * starting the time-wait timer, turning off the other
1239 		 * standard timers.
1240 		 */
1241 		case TCPS_FIN_WAIT_2:
1242 			tp->t_state = TCPS_TIME_WAIT;
1243 			tcp_canceltimers(tp);
1244 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1245 			soisdisconnected(so);
1246 			break;
1247 
1248 		/*
1249 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1250 		 */
1251 		case TCPS_TIME_WAIT:
1252 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1253 			break;
1254 		}
1255 	}
1256 	if (so->so_options & SO_DEBUG)
1257 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1258 
1259 	/*
1260 	 * Return any desired output.
1261 	 */
1262 	if (needoutput || (tp->t_flags & TF_ACKNOW))
1263 		(void) tcp_output(tp);
1264 	return;
1265 
1266 dropafterack:
1267 	/*
1268 	 * Generate an ACK dropping incoming segment if it occupies
1269 	 * sequence space, where the ACK reflects our state.
1270 	 */
1271 	if (tiflags & TH_RST)
1272 		goto drop;
1273 	m_freem(m);
1274 	tp->t_flags |= TF_ACKNOW;
1275 	(void) tcp_output(tp);
1276 	return;
1277 
1278 dropwithreset:
1279 	/*
1280 	 * Generate a RST, dropping incoming segment.
1281 	 * Make ACK acceptable to originator of segment.
1282 	 * Don't bother to respond if destination was broadcast/multicast.
1283 	 */
1284 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1285 	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1286 		goto drop;
1287 	if (tiflags & TH_ACK)
1288 		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1289 	else {
1290 		if (tiflags & TH_SYN)
1291 			ti->ti_len++;
1292 		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1293 		    TH_RST|TH_ACK);
1294 	}
1295 	/* destroy temporarily created socket */
1296 	if (dropsocket)
1297 		(void) soabort(so);
1298 	return;
1299 
1300 drop:
1301 	/*
1302 	 * Drop space held by incoming segment and return.
1303 	 */
1304 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1305 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1306 	m_freem(m);
1307 	/* destroy temporarily created socket */
1308 	if (dropsocket)
1309 		(void) soabort(so);
1310 	return;
1311 #ifndef TUBA_INCLUDE
1312 }
1313 
1314 void
1315 tcp_dooptions(tp, cp, cnt, ti, ts_present, ts_val, ts_ecr)
1316 	struct tcpcb *tp;
1317 	u_char *cp;
1318 	int cnt;
1319 	struct tcpiphdr *ti;
1320 	int *ts_present;
1321 	u_int32_t *ts_val, *ts_ecr;
1322 {
1323 	u_int16_t mss;
1324 	int opt, optlen;
1325 
1326 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1327 		opt = cp[0];
1328 		if (opt == TCPOPT_EOL)
1329 			break;
1330 		if (opt == TCPOPT_NOP)
1331 			optlen = 1;
1332 		else {
1333 			optlen = cp[1];
1334 			if (optlen <= 0)
1335 				break;
1336 		}
1337 		switch (opt) {
1338 
1339 		default:
1340 			continue;
1341 
1342 		case TCPOPT_MAXSEG:
1343 			if (optlen != TCPOLEN_MAXSEG)
1344 				continue;
1345 			if (!(ti->ti_flags & TH_SYN))
1346 				continue;
1347 			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1348 			NTOHS(mss);
1349 			(void) tcp_mss(tp, mss);	/* sets t_maxseg */
1350 			break;
1351 
1352 		case TCPOPT_WINDOW:
1353 			if (optlen != TCPOLEN_WINDOW)
1354 				continue;
1355 			if (!(ti->ti_flags & TH_SYN))
1356 				continue;
1357 			tp->t_flags |= TF_RCVD_SCALE;
1358 			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1359 			break;
1360 
1361 		case TCPOPT_TIMESTAMP:
1362 			if (optlen != TCPOLEN_TIMESTAMP)
1363 				continue;
1364 			*ts_present = 1;
1365 			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
1366 			NTOHL(*ts_val);
1367 			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
1368 			NTOHL(*ts_ecr);
1369 
1370 			/*
1371 			 * A timestamp received in a SYN makes
1372 			 * it ok to send timestamp requests and replies.
1373 			 */
1374 			if (ti->ti_flags & TH_SYN) {
1375 				tp->t_flags |= TF_RCVD_TSTMP;
1376 				tp->ts_recent = *ts_val;
1377 				tp->ts_recent_age = tcp_now;
1378 			}
1379 			break;
1380 		}
1381 	}
1382 }
1383 
1384 /*
1385  * Pull out of band byte out of a segment so
1386  * it doesn't appear in the user's data queue.
1387  * It is still reflected in the segment length for
1388  * sequencing purposes.
1389  */
1390 void
1391 tcp_pulloutofband(so, ti, m)
1392 	struct socket *so;
1393 	struct tcpiphdr *ti;
1394 	register struct mbuf *m;
1395 {
1396 	int cnt = ti->ti_urp - 1;
1397 
1398 	while (cnt >= 0) {
1399 		if (m->m_len > cnt) {
1400 			char *cp = mtod(m, caddr_t) + cnt;
1401 			struct tcpcb *tp = sototcpcb(so);
1402 
1403 			tp->t_iobc = *cp;
1404 			tp->t_oobflags |= TCPOOB_HAVEDATA;
1405 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1406 			m->m_len--;
1407 			return;
1408 		}
1409 		cnt -= m->m_len;
1410 		m = m->m_next;
1411 		if (m == 0)
1412 			break;
1413 	}
1414 	panic("tcp_pulloutofband");
1415 }
1416 
1417 /*
1418  * Collect new round-trip time estimate
1419  * and update averages and current timeout.
1420  */
1421 void
1422 tcp_xmit_timer(tp, rtt)
1423 	register struct tcpcb *tp;
1424 	short rtt;
1425 {
1426 	register short delta;
1427 
1428 	tcpstat.tcps_rttupdated++;
1429 	if (tp->t_srtt != 0) {
1430 		/*
1431 		 * srtt is stored as fixed point with 3 bits after the
1432 		 * binary point (i.e., scaled by 8).  The following magic
1433 		 * is equivalent to the smoothing algorithm in rfc793 with
1434 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1435 		 * point).  Adjust rtt to origin 0.
1436 		 */
1437 		delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1438 		if ((tp->t_srtt += delta) <= 0)
1439 			tp->t_srtt = 1;
1440 		/*
1441 		 * We accumulate a smoothed rtt variance (actually, a
1442 		 * smoothed mean difference), then set the retransmit
1443 		 * timer to smoothed rtt + 4 times the smoothed variance.
1444 		 * rttvar is stored as fixed point with 2 bits after the
1445 		 * binary point (scaled by 4).  The following is
1446 		 * equivalent to rfc793 smoothing with an alpha of .75
1447 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1448 		 * rfc793's wired-in beta.
1449 		 */
1450 		if (delta < 0)
1451 			delta = -delta;
1452 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1453 		if ((tp->t_rttvar += delta) <= 0)
1454 			tp->t_rttvar = 1;
1455 	} else {
1456 		/*
1457 		 * No rtt measurement yet - use the unsmoothed rtt.
1458 		 * Set the variance to half the rtt (so our first
1459 		 * retransmit happens at 3*rtt).
1460 		 */
1461 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
1462 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1463 	}
1464 	tp->t_rtt = 0;
1465 	tp->t_rxtshift = 0;
1466 
1467 	/*
1468 	 * the retransmit should happen at rtt + 4 * rttvar.
1469 	 * Because of the way we do the smoothing, srtt and rttvar
1470 	 * will each average +1/2 tick of bias.  When we compute
1471 	 * the retransmit timer, we want 1/2 tick of rounding and
1472 	 * 1 extra tick because of +-1/2 tick uncertainty in the
1473 	 * firing of the timer.  The bias will give us exactly the
1474 	 * 1.5 tick we need.  But, because the bias is
1475 	 * statistical, we have to test that we don't drop below
1476 	 * the minimum feasible timer (which is 2 ticks).
1477 	 */
1478 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1479 	    tp->t_rttmin, TCPTV_REXMTMAX);
1480 
1481 	/*
1482 	 * We received an ack for a packet that wasn't retransmitted;
1483 	 * it is probably safe to discard any error indications we've
1484 	 * received recently.  This isn't quite right, but close enough
1485 	 * for now (a route might have failed after we sent a segment,
1486 	 * and the return path might not be symmetrical).
1487 	 */
1488 	tp->t_softerror = 0;
1489 }
1490 
1491 /*
1492  * Determine a reasonable value for maxseg size.
1493  * If the route is known, check route for mtu.
1494  * If none, use an mss that can be handled on the outgoing
1495  * interface without forcing IP to fragment; if bigger than
1496  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1497  * to utilize large mbufs.  If no route is found, route has no mtu,
1498  * or the destination isn't local, use a default, hopefully conservative
1499  * size (usually 512 or the default IP max size, but no more than the mtu
1500  * of the interface), as we can't discover anything about intervening
1501  * gateways or networks.  We also initialize the congestion/slow start
1502  * window to be a single segment if the destination isn't local.
1503  * While looking at the routing entry, we also initialize other path-dependent
1504  * parameters from pre-set or cached values in the routing entry.
1505  */
1506 int
1507 tcp_mss(tp, offer)
1508 	register struct tcpcb *tp;
1509 	u_int offer;
1510 {
1511 	struct route *ro;
1512 	register struct rtentry *rt;
1513 	struct ifnet *ifp;
1514 	register int rtt, mss;
1515 	u_long bufsize;
1516 	struct inpcb *inp;
1517 	struct socket *so;
1518 	extern int tcp_mssdflt;
1519 
1520 	inp = tp->t_inpcb;
1521 	ro = &inp->inp_route;
1522 
1523 	if ((rt = ro->ro_rt) == (struct rtentry *)0) {
1524 		/* No route yet, so try to acquire one */
1525 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1526 			ro->ro_dst.sa_family = AF_INET;
1527 			ro->ro_dst.sa_len = sizeof(ro->ro_dst);
1528 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1529 				inp->inp_faddr;
1530 			rtalloc(ro);
1531 		}
1532 		if ((rt = ro->ro_rt) == (struct rtentry *)0)
1533 			return (tcp_mssdflt);
1534 	}
1535 	ifp = rt->rt_ifp;
1536 	so = inp->inp_socket;
1537 
1538 #ifdef RTV_MTU	/* if route characteristics exist ... */
1539 	/*
1540 	 * While we're here, check if there's an initial rtt
1541 	 * or rttvar.  Convert from the route-table units
1542 	 * to scaled multiples of the slow timeout timer.
1543 	 */
1544 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1545 		/*
1546 		 * XXX the lock bit for MTU indicates that the value
1547 		 * is also a minimum value; this is subject to time.
1548 		 */
1549 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1550 			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
1551 		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
1552 		if (rt->rt_rmx.rmx_rttvar)
1553 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1554 			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
1555 		else
1556 			/* default variation is +- 1 rtt */
1557 			tp->t_rttvar =
1558 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
1559 		TCPT_RANGESET(tp->t_rxtcur,
1560 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
1561 		    tp->t_rttmin, TCPTV_REXMTMAX);
1562 	}
1563 	/*
1564 	 * if there's an mtu associated with the route, use it
1565 	 */
1566 	if (rt->rt_rmx.rmx_mtu)
1567 		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
1568 	else
1569 #endif /* RTV_MTU */
1570 	{
1571 		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
1572 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1573 		if (mss > MCLBYTES)
1574 			mss &= ~(MCLBYTES-1);
1575 #else
1576 		if (mss > MCLBYTES)
1577 			mss = mss / MCLBYTES * MCLBYTES;
1578 #endif
1579 		if (!in_localaddr(inp->inp_faddr))
1580 			mss = min(mss, tcp_mssdflt);
1581 	}
1582 	/*
1583 	 * The current mss, t_maxseg, is initialized to the default value.
1584 	 * If we compute a smaller value, reduce the current mss.
1585 	 * If we compute a larger value, return it for use in sending
1586 	 * a max seg size option, but don't store it for use
1587 	 * unless we received an offer at least that large from peer.
1588 	 * However, do not accept offers under 32 bytes.
1589 	 */
1590 	if (offer)
1591 		mss = min(mss, offer);
1592 	mss = max(mss, 32);		/* sanity */
1593 	if (mss < tp->t_maxseg || offer != 0) {
1594 		/*
1595 		 * If there's a pipesize, change the socket buffer
1596 		 * to that size.  Make the socket buffers an integral
1597 		 * number of mss units; if the mss is larger than
1598 		 * the socket buffer, decrease the mss.
1599 		 */
1600 #ifdef RTV_SPIPE
1601 		if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
1602 #endif
1603 			bufsize = so->so_snd.sb_hiwat;
1604 		if (bufsize < mss)
1605 			mss = bufsize;
1606 		else {
1607 			bufsize = roundup(bufsize, mss);
1608 			if (bufsize > sb_max)
1609 				bufsize = sb_max;
1610 			(void)sbreserve(&so->so_snd, bufsize);
1611 		}
1612 		tp->t_maxseg = mss;
1613 
1614 #ifdef RTV_RPIPE
1615 		if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
1616 #endif
1617 			bufsize = so->so_rcv.sb_hiwat;
1618 		if (bufsize > mss) {
1619 			bufsize = roundup(bufsize, mss);
1620 			if (bufsize > sb_max)
1621 				bufsize = sb_max;
1622 			(void)sbreserve(&so->so_rcv, bufsize);
1623 		}
1624 	}
1625 	tp->snd_cwnd = mss;
1626 
1627 #ifdef RTV_SSTHRESH
1628 	if (rt->rt_rmx.rmx_ssthresh) {
1629 		/*
1630 		 * There's some sort of gateway or interface
1631 		 * buffer limit on the path.  Use this to set
1632 		 * the slow start threshhold, but set the
1633 		 * threshold to no less than 2*mss.
1634 		 */
1635 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1636 	}
1637 #endif /* RTV_MTU */
1638 	return (mss);
1639 }
1640 #endif /* TUBA_INCLUDE */
1641