xref: /original-bsd/sys/netinet/tcp_input.c (revision 135ce860)
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.26 (Berkeley) 01/14/92
8  */
9 
10 #include "param.h"
11 #include "systm.h"
12 #include "malloc.h"
13 #include "mbuf.h"
14 #include "protosw.h"
15 #include "socket.h"
16 #include "socketvar.h"
17 #include "errno.h"
18 
19 #include "../net/if.h"
20 #include "../net/route.h"
21 
22 #include "in.h"
23 #include "in_systm.h"
24 #include "ip.h"
25 #include "in_pcb.h"
26 #include "ip_var.h"
27 #include "tcp.h"
28 #include "tcp_fsm.h"
29 #include "tcp_seq.h"
30 #include "tcp_timer.h"
31 #include "tcp_var.h"
32 #include "tcpip.h"
33 #include "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 		laddr = inp->inp_laddr;
481 		if (inp->inp_laddr.s_addr == INADDR_ANY)
482 			inp->inp_laddr = ti->ti_dst;
483 		if (in_pcbconnect(inp, am)) {
484 			inp->inp_laddr = laddr;
485 			(void) m_free(am);
486 			goto drop;
487 		}
488 		(void) m_free(am);
489 		tp->t_template = tcp_template(tp);
490 		if (tp->t_template == 0) {
491 			tp = tcp_drop(tp, ENOBUFS);
492 			dropsocket = 0;		/* socket is already gone */
493 			goto drop;
494 		}
495 		if (om) {
496 			tcp_dooptions(tp, om, ti);
497 			om = 0;
498 		}
499 		if (iss)
500 			tp->iss = iss;
501 		else
502 			tp->iss = tcp_iss;
503 		tcp_iss += TCP_ISSINCR/2;
504 		tp->irs = ti->ti_seq;
505 		tcp_sendseqinit(tp);
506 		tcp_rcvseqinit(tp);
507 		tp->t_flags |= TF_ACKNOW;
508 		tp->t_state = TCPS_SYN_RECEIVED;
509 		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
510 		dropsocket = 0;		/* committed to socket */
511 		tcpstat.tcps_accepts++;
512 		goto trimthenstep6;
513 		}
514 
515 	/*
516 	 * If the state is SYN_SENT:
517 	 *	if seg contains an ACK, but not for our SYN, drop the input.
518 	 *	if seg contains a RST, then drop the connection.
519 	 *	if seg does not contain SYN, then drop it.
520 	 * Otherwise this is an acceptable SYN segment
521 	 *	initialize tp->rcv_nxt and tp->irs
522 	 *	if seg contains ack then advance tp->snd_una
523 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
524 	 *	arrange for segment to be acked (eventually)
525 	 *	continue processing rest of data/controls, beginning with URG
526 	 */
527 	case TCPS_SYN_SENT:
528 		if ((tiflags & TH_ACK) &&
529 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
530 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
531 			goto dropwithreset;
532 		if (tiflags & TH_RST) {
533 			if (tiflags & TH_ACK)
534 				tp = tcp_drop(tp, ECONNREFUSED);
535 			goto drop;
536 		}
537 		if ((tiflags & TH_SYN) == 0)
538 			goto drop;
539 		if (tiflags & TH_ACK) {
540 			tp->snd_una = ti->ti_ack;
541 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
542 				tp->snd_nxt = tp->snd_una;
543 		}
544 		tp->t_timer[TCPT_REXMT] = 0;
545 		tp->irs = ti->ti_seq;
546 		tcp_rcvseqinit(tp);
547 		tp->t_flags |= TF_ACKNOW;
548 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
549 			tcpstat.tcps_connects++;
550 			soisconnected(so);
551 			tp->t_state = TCPS_ESTABLISHED;
552 			(void) tcp_reass(tp, (struct tcpiphdr *)0,
553 				(struct mbuf *)0);
554 			/*
555 			 * if we didn't have to retransmit the SYN,
556 			 * use its rtt as our initial srtt & rtt var.
557 			 */
558 			if (tp->t_rtt)
559 				tcp_xmit_timer(tp);
560 		} else
561 			tp->t_state = TCPS_SYN_RECEIVED;
562 
563 trimthenstep6:
564 		/*
565 		 * Advance ti->ti_seq to correspond to first data byte.
566 		 * If data, trim to stay within window,
567 		 * dropping FIN if necessary.
568 		 */
569 		ti->ti_seq++;
570 		if (ti->ti_len > tp->rcv_wnd) {
571 			todrop = ti->ti_len - tp->rcv_wnd;
572 			m_adj(m, -todrop);
573 			ti->ti_len = tp->rcv_wnd;
574 			tiflags &= ~TH_FIN;
575 			tcpstat.tcps_rcvpackafterwin++;
576 			tcpstat.tcps_rcvbyteafterwin += todrop;
577 		}
578 		tp->snd_wl1 = ti->ti_seq - 1;
579 		tp->rcv_up = ti->ti_seq;
580 		goto step6;
581 	}
582 
583 	/*
584 	 * States other than LISTEN or SYN_SENT.
585 	 * First check that at least some bytes of segment are within
586 	 * receive window.  If segment begins before rcv_nxt,
587 	 * drop leading data (and SYN); if nothing left, just ack.
588 	 */
589 	todrop = tp->rcv_nxt - ti->ti_seq;
590 	if (todrop > 0) {
591 		if (tiflags & TH_SYN) {
592 			tiflags &= ~TH_SYN;
593 			ti->ti_seq++;
594 			if (ti->ti_urp > 1)
595 				ti->ti_urp--;
596 			else
597 				tiflags &= ~TH_URG;
598 			todrop--;
599 		}
600 		if (todrop > ti->ti_len ||
601 		    todrop == ti->ti_len && (tiflags&TH_FIN) == 0) {
602 			tcpstat.tcps_rcvduppack++;
603 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
604 			/*
605 			 * If segment is just one to the left of the window,
606 			 * check two special cases:
607 			 * 1. Don't toss RST in response to 4.2-style keepalive.
608 			 * 2. If the only thing to drop is a FIN, we can drop
609 			 *    it, but check the ACK or we will get into FIN
610 			 *    wars if our FINs crossed (both CLOSING).
611 			 * In either case, send ACK to resynchronize,
612 			 * but keep on processing for RST or ACK.
613 			 */
614 			if ((tiflags & TH_FIN && todrop == ti->ti_len + 1)
615 #ifdef TCP_COMPAT_42
616 			  || (tiflags & TH_RST && ti->ti_seq == tp->rcv_nxt - 1)
617 #endif
618 			   ) {
619 				todrop = ti->ti_len;
620 				tiflags &= ~TH_FIN;
621 				tp->t_flags |= TF_ACKNOW;
622 			} else
623 				goto dropafterack;
624 		} else {
625 			tcpstat.tcps_rcvpartduppack++;
626 			tcpstat.tcps_rcvpartdupbyte += todrop;
627 		}
628 		m_adj(m, todrop);
629 		ti->ti_seq += todrop;
630 		ti->ti_len -= todrop;
631 		if (ti->ti_urp > todrop)
632 			ti->ti_urp -= todrop;
633 		else {
634 			tiflags &= ~TH_URG;
635 			ti->ti_urp = 0;
636 		}
637 	}
638 
639 	/*
640 	 * If new data are received on a connection after the
641 	 * user processes are gone, then RST the other end.
642 	 */
643 	if ((so->so_state & SS_NOFDREF) &&
644 	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
645 		tp = tcp_close(tp);
646 		tcpstat.tcps_rcvafterclose++;
647 		goto dropwithreset;
648 	}
649 
650 	/*
651 	 * If segment ends after window, drop trailing data
652 	 * (and PUSH and FIN); if nothing left, just ACK.
653 	 */
654 	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
655 	if (todrop > 0) {
656 		tcpstat.tcps_rcvpackafterwin++;
657 		if (todrop >= ti->ti_len) {
658 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
659 			/*
660 			 * If a new connection request is received
661 			 * while in TIME_WAIT, drop the old connection
662 			 * and start over if the sequence numbers
663 			 * are above the previous ones.
664 			 */
665 			if (tiflags & TH_SYN &&
666 			    tp->t_state == TCPS_TIME_WAIT &&
667 			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
668 				iss = tp->rcv_nxt + TCP_ISSINCR;
669 				tp = tcp_close(tp);
670 				goto findpcb;
671 			}
672 			/*
673 			 * If window is closed can only take segments at
674 			 * window edge, and have to drop data and PUSH from
675 			 * incoming segments.  Continue processing, but
676 			 * remember to ack.  Otherwise, drop segment
677 			 * and ack.
678 			 */
679 			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
680 				tp->t_flags |= TF_ACKNOW;
681 				tcpstat.tcps_rcvwinprobe++;
682 			} else
683 				goto dropafterack;
684 		} else
685 			tcpstat.tcps_rcvbyteafterwin += todrop;
686 		m_adj(m, -todrop);
687 		ti->ti_len -= todrop;
688 		tiflags &= ~(TH_PUSH|TH_FIN);
689 	}
690 
691 	/*
692 	 * If the RST bit is set examine the state:
693 	 *    SYN_RECEIVED STATE:
694 	 *	If passive open, return to LISTEN state.
695 	 *	If active open, inform user that connection was refused.
696 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
697 	 *	Inform user that connection was reset, and close tcb.
698 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
699 	 *	Close the tcb.
700 	 */
701 	if (tiflags&TH_RST) switch (tp->t_state) {
702 
703 	case TCPS_SYN_RECEIVED:
704 		so->so_error = ECONNREFUSED;
705 		goto close;
706 
707 	case TCPS_ESTABLISHED:
708 	case TCPS_FIN_WAIT_1:
709 	case TCPS_FIN_WAIT_2:
710 	case TCPS_CLOSE_WAIT:
711 		so->so_error = ECONNRESET;
712 	close:
713 		tp->t_state = TCPS_CLOSED;
714 		tcpstat.tcps_drops++;
715 		tp = tcp_close(tp);
716 		goto drop;
717 
718 	case TCPS_CLOSING:
719 	case TCPS_LAST_ACK:
720 	case TCPS_TIME_WAIT:
721 		tp = tcp_close(tp);
722 		goto drop;
723 	}
724 
725 	/*
726 	 * If a SYN is in the window, then this is an
727 	 * error and we send an RST and drop the connection.
728 	 */
729 	if (tiflags & TH_SYN) {
730 		tp = tcp_drop(tp, ECONNRESET);
731 		goto dropwithreset;
732 	}
733 
734 	/*
735 	 * If the ACK bit is off we drop the segment and return.
736 	 */
737 	if ((tiflags & TH_ACK) == 0)
738 		goto drop;
739 
740 	/*
741 	 * Ack processing.
742 	 */
743 	switch (tp->t_state) {
744 
745 	/*
746 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
747 	 * ESTABLISHED state and continue processing, otherwise
748 	 * send an RST.
749 	 */
750 	case TCPS_SYN_RECEIVED:
751 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
752 		    SEQ_GT(ti->ti_ack, tp->snd_max))
753 			goto dropwithreset;
754 		tcpstat.tcps_connects++;
755 		soisconnected(so);
756 		tp->t_state = TCPS_ESTABLISHED;
757 		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
758 		tp->snd_wl1 = ti->ti_seq - 1;
759 		/* fall into ... */
760 
761 	/*
762 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
763 	 * ACKs.  If the ack is in the range
764 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
765 	 * then advance tp->snd_una to ti->ti_ack and drop
766 	 * data from the retransmission queue.  If this ACK reflects
767 	 * more up to date window information we update our window information.
768 	 */
769 	case TCPS_ESTABLISHED:
770 	case TCPS_FIN_WAIT_1:
771 	case TCPS_FIN_WAIT_2:
772 	case TCPS_CLOSE_WAIT:
773 	case TCPS_CLOSING:
774 	case TCPS_LAST_ACK:
775 	case TCPS_TIME_WAIT:
776 
777 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
778 			if (ti->ti_len == 0 && ti->ti_win == tp->snd_wnd) {
779 				tcpstat.tcps_rcvdupack++;
780 				/*
781 				 * If we have outstanding data (other than
782 				 * a window probe), this is a completely
783 				 * duplicate ack (ie, window info didn't
784 				 * change), the ack is the biggest we've
785 				 * seen and we've seen exactly our rexmt
786 				 * threshhold of them, assume a packet
787 				 * has been dropped and retransmit it.
788 				 * Kludge snd_nxt & the congestion
789 				 * window so we send only this one
790 				 * packet.
791 				 *
792 				 * We know we're losing at the current
793 				 * window size so do congestion avoidance
794 				 * (set ssthresh to half the current window
795 				 * and pull our congestion window back to
796 				 * the new ssthresh).
797 				 *
798 				 * Dup acks mean that packets have left the
799 				 * network (they're now cached at the receiver)
800 				 * so bump cwnd by the amount in the receiver
801 				 * to keep a constant cwnd packets in the
802 				 * network.
803 				 */
804 				if (tp->t_timer[TCPT_REXMT] == 0 ||
805 				    ti->ti_ack != tp->snd_una)
806 					tp->t_dupacks = 0;
807 				else if (++tp->t_dupacks == tcprexmtthresh) {
808 					tcp_seq onxt = tp->snd_nxt;
809 					u_int win =
810 					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
811 						tp->t_maxseg;
812 
813 					if (win < 2)
814 						win = 2;
815 					tp->snd_ssthresh = win * tp->t_maxseg;
816 					tp->t_timer[TCPT_REXMT] = 0;
817 					tp->t_rtt = 0;
818 					tp->snd_nxt = ti->ti_ack;
819 					tp->snd_cwnd = tp->t_maxseg;
820 					(void) tcp_output(tp);
821 					tp->snd_cwnd = tp->snd_ssthresh +
822 					       tp->t_maxseg * tp->t_dupacks;
823 					if (SEQ_GT(onxt, tp->snd_nxt))
824 						tp->snd_nxt = onxt;
825 					goto drop;
826 				} else if (tp->t_dupacks > tcprexmtthresh) {
827 					tp->snd_cwnd += tp->t_maxseg;
828 					(void) tcp_output(tp);
829 					goto drop;
830 				}
831 			} else
832 				tp->t_dupacks = 0;
833 			break;
834 		}
835 		/*
836 		 * If the congestion window was inflated to account
837 		 * for the other side's cached packets, retract it.
838 		 */
839 		if (tp->t_dupacks > tcprexmtthresh &&
840 		    tp->snd_cwnd > tp->snd_ssthresh)
841 			tp->snd_cwnd = tp->snd_ssthresh;
842 		tp->t_dupacks = 0;
843 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
844 			tcpstat.tcps_rcvacktoomuch++;
845 			goto dropafterack;
846 		}
847 		acked = ti->ti_ack - tp->snd_una;
848 		tcpstat.tcps_rcvackpack++;
849 		tcpstat.tcps_rcvackbyte += acked;
850 
851 		/*
852 		 * If transmit timer is running and timed sequence
853 		 * number was acked, update smoothed round trip time.
854 		 * Since we now have an rtt measurement, cancel the
855 		 * timer backoff (cf., Phil Karn's retransmit alg.).
856 		 * Recompute the initial retransmit timer.
857 		 */
858 		if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
859 			tcp_xmit_timer(tp);
860 
861 		/*
862 		 * If all outstanding data is acked, stop retransmit
863 		 * timer and remember to restart (more output or persist).
864 		 * If there is more data to be acked, restart retransmit
865 		 * timer, using current (possibly backed-off) value.
866 		 */
867 		if (ti->ti_ack == tp->snd_max) {
868 			tp->t_timer[TCPT_REXMT] = 0;
869 			needoutput = 1;
870 		} else if (tp->t_timer[TCPT_PERSIST] == 0)
871 			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
872 		/*
873 		 * When new data is acked, open the congestion window.
874 		 * If the window gives us less than ssthresh packets
875 		 * in flight, open exponentially (maxseg per packet).
876 		 * Otherwise open linearly: maxseg per window
877 		 * (maxseg^2 / cwnd per packet), plus a constant
878 		 * fraction of a packet (maxseg/8) to help larger windows
879 		 * open quickly enough.
880 		 */
881 		{
882 		register u_int cw = tp->snd_cwnd;
883 		register u_int incr = tp->t_maxseg;
884 
885 		if (cw > tp->snd_ssthresh)
886 			incr = incr * incr / cw + incr / 8;
887 		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN);
888 		}
889 		if (acked > so->so_snd.sb_cc) {
890 			tp->snd_wnd -= so->so_snd.sb_cc;
891 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
892 			ourfinisacked = 1;
893 		} else {
894 			sbdrop(&so->so_snd, acked);
895 			tp->snd_wnd -= acked;
896 			ourfinisacked = 0;
897 		}
898 		if (so->so_snd.sb_flags & SB_NOTIFY)
899 			sowwakeup(so);
900 		tp->snd_una = ti->ti_ack;
901 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
902 			tp->snd_nxt = tp->snd_una;
903 
904 		switch (tp->t_state) {
905 
906 		/*
907 		 * In FIN_WAIT_1 STATE in addition to the processing
908 		 * for the ESTABLISHED state if our FIN is now acknowledged
909 		 * then enter FIN_WAIT_2.
910 		 */
911 		case TCPS_FIN_WAIT_1:
912 			if (ourfinisacked) {
913 				/*
914 				 * If we can't receive any more
915 				 * data, then closing user can proceed.
916 				 * Starting the timer is contrary to the
917 				 * specification, but if we don't get a FIN
918 				 * we'll hang forever.
919 				 */
920 				if (so->so_state & SS_CANTRCVMORE) {
921 					soisdisconnected(so);
922 					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
923 				}
924 				tp->t_state = TCPS_FIN_WAIT_2;
925 			}
926 			break;
927 
928 	 	/*
929 		 * In CLOSING STATE in addition to the processing for
930 		 * the ESTABLISHED state if the ACK acknowledges our FIN
931 		 * then enter the TIME-WAIT state, otherwise ignore
932 		 * the segment.
933 		 */
934 		case TCPS_CLOSING:
935 			if (ourfinisacked) {
936 				tp->t_state = TCPS_TIME_WAIT;
937 				tcp_canceltimers(tp);
938 				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
939 				soisdisconnected(so);
940 			}
941 			break;
942 
943 		/*
944 		 * In LAST_ACK, we may still be waiting for data to drain
945 		 * and/or to be acked, as well as for the ack of our FIN.
946 		 * If our FIN is now acknowledged, delete the TCB,
947 		 * enter the closed state and return.
948 		 */
949 		case TCPS_LAST_ACK:
950 			if (ourfinisacked) {
951 				tp = tcp_close(tp);
952 				goto drop;
953 			}
954 			break;
955 
956 		/*
957 		 * In TIME_WAIT state the only thing that should arrive
958 		 * is a retransmission of the remote FIN.  Acknowledge
959 		 * it and restart the finack timer.
960 		 */
961 		case TCPS_TIME_WAIT:
962 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
963 			goto dropafterack;
964 		}
965 	}
966 
967 step6:
968 	/*
969 	 * Update window information.
970 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
971 	 */
972 	if ((tiflags & TH_ACK) &&
973 	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq &&
974 	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
975 	     tp->snd_wl2 == ti->ti_ack && ti->ti_win > tp->snd_wnd))) {
976 		/* keep track of pure window updates */
977 		if (ti->ti_len == 0 &&
978 		    tp->snd_wl2 == ti->ti_ack && ti->ti_win > tp->snd_wnd)
979 			tcpstat.tcps_rcvwinupd++;
980 		tp->snd_wnd = ti->ti_win;
981 		tp->snd_wl1 = ti->ti_seq;
982 		tp->snd_wl2 = ti->ti_ack;
983 		if (tp->snd_wnd > tp->max_sndwnd)
984 			tp->max_sndwnd = tp->snd_wnd;
985 		needoutput = 1;
986 	}
987 
988 	/*
989 	 * Process segments with URG.
990 	 */
991 	if ((tiflags & TH_URG) && ti->ti_urp &&
992 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
993 		/*
994 		 * This is a kludge, but if we receive and accept
995 		 * random urgent pointers, we'll crash in
996 		 * soreceive.  It's hard to imagine someone
997 		 * actually wanting to send this much urgent data.
998 		 */
999 		if (ti->ti_urp + so->so_rcv.sb_cc > SB_MAX) {
1000 			ti->ti_urp = 0;			/* XXX */
1001 			tiflags &= ~TH_URG;		/* XXX */
1002 			goto dodata;			/* XXX */
1003 		}
1004 		/*
1005 		 * If this segment advances the known urgent pointer,
1006 		 * then mark the data stream.  This should not happen
1007 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1008 		 * a FIN has been received from the remote side.
1009 		 * In these states we ignore the URG.
1010 		 *
1011 		 * According to RFC961 (Assigned Protocols),
1012 		 * the urgent pointer points to the last octet
1013 		 * of urgent data.  We continue, however,
1014 		 * to consider it to indicate the first octet
1015 		 * of data past the urgent section as the original
1016 		 * spec states (in one of two places).
1017 		 */
1018 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1019 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1020 			so->so_oobmark = so->so_rcv.sb_cc +
1021 			    (tp->rcv_up - tp->rcv_nxt) - 1;
1022 			if (so->so_oobmark == 0)
1023 				so->so_state |= SS_RCVATMARK;
1024 			sohasoutofband(so);
1025 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1026 		}
1027 		/*
1028 		 * Remove out of band data so doesn't get presented to user.
1029 		 * This can happen independent of advancing the URG pointer,
1030 		 * but if two URG's are pending at once, some out-of-band
1031 		 * data may creep in... ick.
1032 		 */
1033 		if (ti->ti_urp <= ti->ti_len
1034 #ifdef SO_OOBINLINE
1035 		     && (so->so_options & SO_OOBINLINE) == 0
1036 #endif
1037 		     )
1038 			tcp_pulloutofband(so, ti, m);
1039 	} else
1040 		/*
1041 		 * If no out of band data is expected,
1042 		 * pull receive urgent pointer along
1043 		 * with the receive window.
1044 		 */
1045 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1046 			tp->rcv_up = tp->rcv_nxt;
1047 dodata:							/* XXX */
1048 
1049 	/*
1050 	 * Process the segment text, merging it into the TCP sequencing queue,
1051 	 * and arranging for acknowledgment of receipt if necessary.
1052 	 * This process logically involves adjusting tp->rcv_wnd as data
1053 	 * is presented to the user (this happens in tcp_usrreq.c,
1054 	 * case PRU_RCVD).  If a FIN has already been received on this
1055 	 * connection then we just ignore the text.
1056 	 */
1057 	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1058 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1059 		TCP_REASS(tp, ti, m, so, tiflags);
1060 		/*
1061 		 * Note the amount of data that peer has sent into
1062 		 * our window, in order to estimate the sender's
1063 		 * buffer size.
1064 		 */
1065 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1066 	} else {
1067 		m_freem(m);
1068 		tiflags &= ~TH_FIN;
1069 	}
1070 
1071 	/*
1072 	 * If FIN is received ACK the FIN and let the user know
1073 	 * that the connection is closing.
1074 	 */
1075 	if (tiflags & TH_FIN) {
1076 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1077 			socantrcvmore(so);
1078 			tp->t_flags |= TF_ACKNOW;
1079 			tp->rcv_nxt++;
1080 		}
1081 		switch (tp->t_state) {
1082 
1083 	 	/*
1084 		 * In SYN_RECEIVED and ESTABLISHED STATES
1085 		 * enter the CLOSE_WAIT state.
1086 		 */
1087 		case TCPS_SYN_RECEIVED:
1088 		case TCPS_ESTABLISHED:
1089 			tp->t_state = TCPS_CLOSE_WAIT;
1090 			break;
1091 
1092 	 	/*
1093 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1094 		 * enter the CLOSING state.
1095 		 */
1096 		case TCPS_FIN_WAIT_1:
1097 			tp->t_state = TCPS_CLOSING;
1098 			break;
1099 
1100 	 	/*
1101 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1102 		 * starting the time-wait timer, turning off the other
1103 		 * standard timers.
1104 		 */
1105 		case TCPS_FIN_WAIT_2:
1106 			tp->t_state = TCPS_TIME_WAIT;
1107 			tcp_canceltimers(tp);
1108 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1109 			soisdisconnected(so);
1110 			break;
1111 
1112 		/*
1113 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1114 		 */
1115 		case TCPS_TIME_WAIT:
1116 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1117 			break;
1118 		}
1119 	}
1120 	if (so->so_options & SO_DEBUG)
1121 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1122 
1123 	/*
1124 	 * Return any desired output.
1125 	 */
1126 	if (needoutput || (tp->t_flags & TF_ACKNOW))
1127 		(void) tcp_output(tp);
1128 	return;
1129 
1130 dropafterack:
1131 	/*
1132 	 * Generate an ACK dropping incoming segment if it occupies
1133 	 * sequence space, where the ACK reflects our state.
1134 	 */
1135 	if (tiflags & TH_RST)
1136 		goto drop;
1137 	m_freem(m);
1138 	tp->t_flags |= TF_ACKNOW;
1139 	(void) tcp_output(tp);
1140 	return;
1141 
1142 dropwithreset:
1143 	if (om) {
1144 		(void) m_free(om);
1145 		om = 0;
1146 	}
1147 	/*
1148 	 * Generate a RST, dropping incoming segment.
1149 	 * Make ACK acceptable to originator of segment.
1150 	 * Don't bother to respond if destination was broadcast.
1151 	 */
1152 	if ((tiflags & TH_RST) || m->m_flags & M_BCAST)
1153 		goto drop;
1154 	if (tiflags & TH_ACK)
1155 		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1156 	else {
1157 		if (tiflags & TH_SYN)
1158 			ti->ti_len++;
1159 		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1160 		    TH_RST|TH_ACK);
1161 	}
1162 	/* destroy temporarily created socket */
1163 	if (dropsocket)
1164 		(void) soabort(so);
1165 	return;
1166 
1167 drop:
1168 	if (om)
1169 		(void) m_free(om);
1170 	/*
1171 	 * Drop space held by incoming segment and return.
1172 	 */
1173 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1174 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1175 	m_freem(m);
1176 	/* destroy temporarily created socket */
1177 	if (dropsocket)
1178 		(void) soabort(so);
1179 	return;
1180 }
1181 
1182 tcp_dooptions(tp, om, ti)
1183 	struct tcpcb *tp;
1184 	struct mbuf *om;
1185 	struct tcpiphdr *ti;
1186 {
1187 	register u_char *cp;
1188 	u_short mss;
1189 	int opt, optlen, cnt;
1190 
1191 	cp = mtod(om, u_char *);
1192 	cnt = om->m_len;
1193 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1194 		opt = cp[0];
1195 		if (opt == TCPOPT_EOL)
1196 			break;
1197 		if (opt == TCPOPT_NOP)
1198 			optlen = 1;
1199 		else {
1200 			optlen = cp[1];
1201 			if (optlen <= 0)
1202 				break;
1203 		}
1204 		switch (opt) {
1205 
1206 		default:
1207 			continue;
1208 
1209 		case TCPOPT_MAXSEG:
1210 			if (optlen != 4)
1211 				continue;
1212 			if (!(ti->ti_flags & TH_SYN))
1213 				continue;
1214 			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1215 			NTOHS(mss);
1216 			(void) tcp_mss(tp, mss);	/* sets t_maxseg */
1217 			break;
1218 		}
1219 	}
1220 	(void) m_free(om);
1221 }
1222 
1223 /*
1224  * Pull out of band byte out of a segment so
1225  * it doesn't appear in the user's data queue.
1226  * It is still reflected in the segment length for
1227  * sequencing purposes.
1228  */
1229 tcp_pulloutofband(so, ti, m)
1230 	struct socket *so;
1231 	struct tcpiphdr *ti;
1232 	register struct mbuf *m;
1233 {
1234 	int cnt = ti->ti_urp - 1;
1235 
1236 	while (cnt >= 0) {
1237 		if (m->m_len > cnt) {
1238 			char *cp = mtod(m, caddr_t) + cnt;
1239 			struct tcpcb *tp = sototcpcb(so);
1240 
1241 			tp->t_iobc = *cp;
1242 			tp->t_oobflags |= TCPOOB_HAVEDATA;
1243 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1244 			m->m_len--;
1245 			return;
1246 		}
1247 		cnt -= m->m_len;
1248 		m = m->m_next;
1249 		if (m == 0)
1250 			break;
1251 	}
1252 	panic("tcp_pulloutofband");
1253 }
1254 
1255 /*
1256  * Collect new round-trip time estimate
1257  * and update averages and current timeout.
1258  */
1259 tcp_xmit_timer(tp)
1260 	register struct tcpcb *tp;
1261 {
1262 	register short delta;
1263 
1264 	tcpstat.tcps_rttupdated++;
1265 	if (tp->t_srtt != 0) {
1266 		/*
1267 		 * srtt is stored as fixed point with 3 bits after the
1268 		 * binary point (i.e., scaled by 8).  The following magic
1269 		 * is equivalent to the smoothing algorithm in rfc793 with
1270 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1271 		 * point).  Adjust t_rtt to origin 0.
1272 		 */
1273 		delta = tp->t_rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1274 		if ((tp->t_srtt += delta) <= 0)
1275 			tp->t_srtt = 1;
1276 		/*
1277 		 * We accumulate a smoothed rtt variance (actually, a
1278 		 * smoothed mean difference), then set the retransmit
1279 		 * timer to smoothed rtt + 4 times the smoothed variance.
1280 		 * rttvar is stored as fixed point with 2 bits after the
1281 		 * binary point (scaled by 4).  The following is
1282 		 * equivalent to rfc793 smoothing with an alpha of .75
1283 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1284 		 * rfc793's wired-in beta.
1285 		 */
1286 		if (delta < 0)
1287 			delta = -delta;
1288 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1289 		if ((tp->t_rttvar += delta) <= 0)
1290 			tp->t_rttvar = 1;
1291 	} else {
1292 		/*
1293 		 * No rtt measurement yet - use the unsmoothed rtt.
1294 		 * Set the variance to half the rtt (so our first
1295 		 * retransmit happens at 3*rtt).
1296 		 */
1297 		tp->t_srtt = tp->t_rtt << TCP_RTT_SHIFT;
1298 		tp->t_rttvar = tp->t_rtt << (TCP_RTTVAR_SHIFT - 1);
1299 	}
1300 	tp->t_rtt = 0;
1301 	tp->t_rxtshift = 0;
1302 
1303 	/*
1304 	 * the retransmit should happen at rtt + 4 * rttvar.
1305 	 * Because of the way we do the smoothing, srtt and rttvar
1306 	 * will each average +1/2 tick of bias.  When we compute
1307 	 * the retransmit timer, we want 1/2 tick of rounding and
1308 	 * 1 extra tick because of +-1/2 tick uncertainty in the
1309 	 * firing of the timer.  The bias will give us exactly the
1310 	 * 1.5 tick we need.  But, because the bias is
1311 	 * statistical, we have to test that we don't drop below
1312 	 * the minimum feasible timer (which is 2 ticks).
1313 	 */
1314 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1315 	    tp->t_rttmin, TCPTV_REXMTMAX);
1316 
1317 	/*
1318 	 * We received an ack for a packet that wasn't retransmitted;
1319 	 * it is probably safe to discard any error indications we've
1320 	 * received recently.  This isn't quite right, but close enough
1321 	 * for now (a route might have failed after we sent a segment,
1322 	 * and the return path might not be symmetrical).
1323 	 */
1324 	tp->t_softerror = 0;
1325 }
1326 
1327 /*
1328  * Determine a reasonable value for maxseg size.
1329  * If the route is known, check route for mtu.
1330  * If none, use an mss that can be handled on the outgoing
1331  * interface without forcing IP to fragment; if bigger than
1332  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1333  * to utilize large mbufs.  If no route is found, route has no mtu,
1334  * or the destination isn't local, use a default, hopefully conservative
1335  * size (usually 512 or the default IP max size, but no more than the mtu
1336  * of the interface), as we can't discover anything about intervening
1337  * gateways or networks.  We also initialize the congestion/slow start
1338  * window to be a single segment if the destination isn't local.
1339  * While looking at the routing entry, we also initialize other path-dependent
1340  * parameters from pre-set or cached values in the routing entry.
1341  */
1342 
1343 tcp_mss(tp, offer)
1344 	register struct tcpcb *tp;
1345 	u_short offer;
1346 {
1347 	struct route *ro;
1348 	register struct rtentry *rt;
1349 	struct ifnet *ifp;
1350 	register int rtt, mss;
1351 	u_long bufsize;
1352 	struct inpcb *inp;
1353 	struct socket *so;
1354 	extern int tcp_mssdflt, tcp_rttdflt;
1355 
1356 	inp = tp->t_inpcb;
1357 	ro = &inp->inp_route;
1358 
1359 	if ((rt = ro->ro_rt) == (struct rtentry *)0) {
1360 		/* No route yet, so try to acquire one */
1361 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1362 			ro->ro_dst.sa_family = AF_INET;
1363 			ro->ro_dst.sa_len = sizeof(ro->ro_dst);
1364 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1365 				inp->inp_faddr;
1366 			rtalloc(ro);
1367 		}
1368 		if ((rt = ro->ro_rt) == (struct rtentry *)0)
1369 			return (tcp_mssdflt);
1370 	}
1371 	ifp = rt->rt_ifp;
1372 	so = inp->inp_socket;
1373 
1374 #ifdef RTV_MTU	/* if route characteristics exist ... */
1375 	/*
1376 	 * While we're here, check if there's an initial rtt
1377 	 * or rttvar.  Convert from the route-table units
1378 	 * to scaled multiples of the slow timeout timer.
1379 	 */
1380 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1381 		/*
1382 		 * XXX the lock bit for MTU indicates that the value
1383 		 * is also a minimum value; this is subject to time.
1384 		 */
1385 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1386 			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
1387 		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
1388 		if (rt->rt_rmx.rmx_rttvar)
1389 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1390 			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
1391 		else
1392 			/* default variation is +- 1 rtt */
1393 			tp->t_rttvar =
1394 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
1395 		TCPT_RANGESET(tp->t_rxtcur,
1396 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
1397 		    tp->t_rttmin, TCPTV_REXMTMAX);
1398 	}
1399 	/*
1400 	 * if there's an mtu associated with the route, use it
1401 	 */
1402 	if (rt->rt_rmx.rmx_mtu)
1403 		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
1404 	else
1405 #endif /* RTV_MTU */
1406 	{
1407 		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
1408 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1409 		if (mss > MCLBYTES)
1410 			mss &= ~(MCLBYTES-1);
1411 #else
1412 		if (mss > MCLBYTES)
1413 			mss = mss / MCLBYTES * MCLBYTES;
1414 #endif
1415 		if (!in_localaddr(inp->inp_faddr))
1416 			mss = min(mss, tcp_mssdflt);
1417 	}
1418 	/*
1419 	 * The current mss, t_maxseg, is initialized to the default value.
1420 	 * If we compute a smaller value, reduce the current mss.
1421 	 * If we compute a larger value, return it for use in sending
1422 	 * a max seg size option, but don't store it for use
1423 	 * unless we received an offer at least that large from peer.
1424 	 * However, do not accept offers under 32 bytes.
1425 	 */
1426 	if (offer)
1427 		mss = min(mss, offer);
1428 	mss = max(mss, 32);		/* sanity */
1429 	if (mss < tp->t_maxseg || offer != 0) {
1430 		/*
1431 		 * If there's a pipesize, change the socket buffer
1432 		 * to that size.  Make the socket buffers an integral
1433 		 * number of mss units; if the mss is larger than
1434 		 * the socket buffer, decrease the mss.
1435 		 */
1436 #ifdef RTV_SPIPE
1437 		if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
1438 #endif
1439 			bufsize = so->so_snd.sb_hiwat;
1440 		if (bufsize < mss)
1441 			mss = bufsize;
1442 		else {
1443 			bufsize = min(bufsize, SB_MAX) / mss * mss;
1444 			(void) sbreserve(&so->so_snd, bufsize);
1445 		}
1446 		tp->t_maxseg = mss;
1447 
1448 #ifdef RTV_RPIPE
1449 		if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
1450 #endif
1451 			bufsize = so->so_rcv.sb_hiwat;
1452 		if (bufsize > mss) {
1453 			bufsize = min(bufsize, SB_MAX) / mss * mss;
1454 			(void) sbreserve(&so->so_rcv, bufsize);
1455 		}
1456 	}
1457 	tp->snd_cwnd = mss;
1458 
1459 #ifdef RTV_SSTHRESH
1460 	if (rt->rt_rmx.rmx_ssthresh) {
1461 		/*
1462 		 * There's some sort of gateway or interface
1463 		 * buffer limit on the path.  Use this to set
1464 		 * the slow start threshhold, but set the
1465 		 * threshold to no less than 2*mss.
1466 		 */
1467 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1468 	}
1469 #endif /* RTV_MTU */
1470 	return (mss);
1471 }
1472