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