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