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