Revert part of the previous commit.
[dragonfly.git] / sys / netinet / tcp_input.c
CommitLineData
984263bc 1/*
66d6c637
JH
2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
95b22adf 4 *
66d6c637
JH
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
95b22adf 7 *
66d6c637
JH
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
95b22adf 19 *
66d6c637
JH
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
66d6c637 34/*
984263bc
MD
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
36 * The Regents of the University of California. All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64 * SUCH DAMAGE.
65 *
66 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
67 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
5de23090 68 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.68 2008/08/22 09:14:17 sephe Exp $
984263bc
MD
69 */
70
71#include "opt_ipfw.h" /* for ipfw_fwd */
b1992928 72#include "opt_inet.h"
984263bc
MD
73#include "opt_inet6.h"
74#include "opt_ipsec.h"
75#include "opt_tcpdebug.h"
76#include "opt_tcp_input.h"
77
78#include <sys/param.h>
79#include <sys/systm.h>
80#include <sys/kernel.h>
81#include <sys/sysctl.h>
82#include <sys/malloc.h>
83#include <sys/mbuf.h>
84#include <sys/proc.h> /* for proc0 declaration */
85#include <sys/protosw.h>
86#include <sys/socket.h>
87#include <sys/socketvar.h>
88#include <sys/syslog.h>
3f9db7f8 89#include <sys/in_cksum.h>
984263bc 90
6cef7136
MD
91#include <sys/socketvar2.h>
92
984263bc 93#include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
a00138cb 94#include <machine/stdarg.h>
984263bc
MD
95
96#include <net/if.h>
97#include <net/route.h>
98
99#include <netinet/in.h>
100#include <netinet/in_systm.h>
101#include <netinet/ip.h>
95b22adf 102#include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
984263bc 103#include <netinet/in_var.h>
95b22adf 104#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
984263bc
MD
105#include <netinet/in_pcb.h>
106#include <netinet/ip_var.h>
107#include <netinet/ip6.h>
108#include <netinet/icmp6.h>
109#include <netinet6/nd6.h>
110#include <netinet6/ip6_var.h>
111#include <netinet6/in6_pcb.h>
112#include <netinet/tcp.h>
113#include <netinet/tcp_fsm.h>
114#include <netinet/tcp_seq.h>
115#include <netinet/tcp_timer.h>
a48c5dd5 116#include <netinet/tcp_timer2.h>
984263bc
MD
117#include <netinet/tcp_var.h>
118#include <netinet6/tcp6_var.h>
119#include <netinet/tcpip.h>
95b22adf 120
984263bc
MD
121#ifdef TCPDEBUG
122#include <netinet/tcp_debug.h>
123
95b22adf 124u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
984263bc 125struct tcphdr tcp_savetcp;
95b22adf 126#endif
984263bc
MD
127
128#ifdef FAST_IPSEC
bf844ffa
JH
129#include <netproto/ipsec/ipsec.h>
130#include <netproto/ipsec/ipsec6.h>
984263bc
MD
131#endif
132
133#ifdef IPSEC
134#include <netinet6/ipsec.h>
135#include <netinet6/ipsec6.h>
d2438d69 136#include <netproto/key/key.h>
95b22adf 137#endif
984263bc 138
984263bc
MD
139MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
140
984263bc 141static int log_in_vain = 0;
d24ce1dc 142SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
984263bc
MD
143 &log_in_vain, 0, "Log all incoming TCP connections");
144
145static int blackhole = 0;
146SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
147 &blackhole, 0, "Do not send RST when dropping refused connections");
148
149int tcp_delack_enabled = 1;
d24ce1dc
JH
150SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
151 &tcp_delack_enabled, 0,
984263bc
MD
152 "Delay ACK to try and piggyback it onto a data packet");
153
154#ifdef TCP_DROP_SYNFIN
155static int drop_synfin = 0;
156SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
157 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
158#endif
159
33abdd1c
MD
160static int tcp_do_limitedtransmit = 1;
161SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
162 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
163
91489f6b 164static int tcp_do_early_retransmit = 1;
8819433a
JH
165SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
166 &tcp_do_early_retransmit, 0, "Early retransmit");
167
8acdb67c 168int tcp_aggregate_acks = 1;
72b37eeb
MD
169SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
170 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
171
8d573eef 172int tcp_do_rfc3390 = 1;
4b52d5ee
JH
173SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
174 &tcp_do_rfc3390, 0,
175 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
176
efd4b327
JH
177static int tcp_do_eifel_detect = 1;
178SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
179 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
180
8acdb67c
JH
181static int tcp_do_abc = 1;
182SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
183 &tcp_do_abc, 0,
184 "TCP Appropriate Byte Counting (RFC 3465)");
185
91489f6b
JH
186/*
187 * Define as tunable for easy testing with SACK on and off.
188 * Warning: do not change setting in the middle of an existing active TCP flow,
189 * else strange things might happen to that flow.
190 */
6e5bbdda 191int tcp_do_sack = 1;
91489f6b
JH
192SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
193 &tcp_do_sack, 0, "Enable SACK Algorithms");
194
195int tcp_do_smartsack = 1;
196SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
197 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
198
3edf7c37
RG
199SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
200 "TCP Segment Reassembly Queue");
201
202int tcp_reass_maxseg = 0;
203SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
204 &tcp_reass_maxseg, 0,
205 "Global maximum number of TCP Segments in Reassembly Queue");
206
207int tcp_reass_qsize = 0;
208SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
209 &tcp_reass_qsize, 0,
210 "Global number of TCP Segments currently in Reassembly Queue");
211
212static int tcp_reass_overflows = 0;
213SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
214 &tcp_reass_overflows, 0,
215 "Global number of TCP Segment Reassembly Queue Overflows");
216
5b0b9fa5
PA
217int tcp_do_autorcvbuf = 1;
218SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
219 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
220
221int tcp_autorcvbuf_inc = 16*1024;
222SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
223 &tcp_autorcvbuf_inc, 0,
224 "Incrementor step size of automatic receive buffer");
225
46e92930 226int tcp_autorcvbuf_max = 2*1024*1024;
5b0b9fa5
PA
227SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
228 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
229
230
95b22adf 231static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
984263bc
MD
232static void tcp_pulloutofband(struct socket *,
233 struct tcphdr *, struct mbuf *, int);
234static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
235 struct mbuf *);
236static void tcp_xmit_timer(struct tcpcb *, int);
91489f6b
JH
237static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
238static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
984263bc
MD
239
240/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
241#ifdef INET6
242#define ND6_HINT(tp) \
243do { \
244 if ((tp) && (tp)->t_inpcb && \
61896e3c 245 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
984263bc
MD
246 (tp)->t_inpcb->in6p_route.ro_rt) \
247 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
248} while (0)
249#else
250#define ND6_HINT(tp)
251#endif
252
253/*
254 * Indicate whether this ack should be delayed. We can delay the ack if
255 * - delayed acks are enabled and
256 * - there is no delayed ack timer in progress and
257 * - our last ack wasn't a 0-sized window. We never want to delay
258 * the ack that opens up a 0-sized window.
259 */
260#define DELAY_ACK(tp) \
a48c5dd5 261 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
61896e3c 262 !(tp->t_flags & TF_RXWIN0SENT))
984263bc 263
df9d7670
JH
264#define acceptable_window_update(tp, th, tiwin) \
265 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
266 (tp->snd_wl1 == th->th_seq && \
267 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
268 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
269
984263bc 270static int
95b22adf 271tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
984263bc
MD
272{
273 struct tseg_qent *q;
274 struct tseg_qent *p = NULL;
984263bc
MD
275 struct tseg_qent *te;
276 struct socket *so = tp->t_inpcb->inp_socket;
277 int flags;
278
279 /*
61896e3c 280 * Call with th == NULL after become established to
984263bc
MD
281 * force pre-ESTABLISHED data up to user socket.
282 */
61896e3c 283 if (th == NULL)
984263bc
MD
284 goto present;
285
3edf7c37
RG
286 /*
287 * Limit the number of segments in the reassembly queue to prevent
288 * holding on to too many segments (and thus running out of mbufs).
289 * Make sure to let the missing segment through which caused this
290 * queue. Always keep one global queue entry spare to be able to
291 * process the missing segment.
292 */
293 if (th->th_seq != tp->rcv_nxt &&
294 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
295 tcp_reass_overflows++;
296 tcpstat.tcps_rcvmemdrop++;
297 m_freem(m);
91489f6b
JH
298 /* no SACK block to report */
299 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
3edf7c37
RG
300 return (0);
301 }
302
ba4e3dbe 303 /* Allocate a new queue entry. */
984263bc 304 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
ba4e3dbe 305 M_INTWAIT | M_NULLOK);
984263bc
MD
306 if (te == NULL) {
307 tcpstat.tcps_rcvmemdrop++;
308 m_freem(m);
91489f6b
JH
309 /* no SACK block to report */
310 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
984263bc
MD
311 return (0);
312 }
2d23a8be 313 atomic_add_int(&tcp_reass_qsize, 1);
984263bc
MD
314
315 /*
316 * Find a segment which begins after this one does.
317 */
318 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
319 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
320 break;
321 p = q;
322 }
323
324 /*
325 * If there is a preceding segment, it may provide some of
326 * our data already. If so, drop the data from the incoming
327 * segment. If it provides all of our data, drop us.
328 */
329 if (p != NULL) {
76cf5e41 330 tcp_seq_diff_t i;
91489f6b 331
984263bc
MD
332 /* conversion to int (in i) handles seq wraparound */
333 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
91489f6b
JH
334 if (i > 0) { /* overlaps preceding segment */
335 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
336 /* enclosing block starts w/ preceding segment */
337 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
984263bc 338 if (i >= *tlenp) {
91489f6b
JH
339 /* preceding encloses incoming segment */
340 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
341 p->tqe_len;
984263bc
MD
342 tcpstat.tcps_rcvduppack++;
343 tcpstat.tcps_rcvdupbyte += *tlenp;
344 m_freem(m);
efda3bd0 345 kfree(te, M_TSEGQ);
2d23a8be 346 atomic_add_int(&tcp_reass_qsize, -1);
984263bc
MD
347 /*
348 * Try to present any queued data
349 * at the left window edge to the user.
350 * This is needed after the 3-WHS
351 * completes.
352 */
353 goto present; /* ??? */
354 }
355 m_adj(m, i);
356 *tlenp -= i;
357 th->th_seq += i;
91489f6b
JH
358 /* incoming segment end is enclosing block end */
359 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
360 ((th->th_flags & TH_FIN) != 0);
361 /* trim end of reported D-SACK block */
362 tp->reportblk.rblk_end = th->th_seq;
984263bc
MD
363 }
364 }
365 tcpstat.tcps_rcvoopack++;
366 tcpstat.tcps_rcvoobyte += *tlenp;
367
368 /*
369 * While we overlap succeeding segments trim them or,
370 * if they are completely covered, dequeue them.
371 */
372 while (q) {
76cf5e41 373 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
91489f6b
JH
374 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
375 struct tseg_qent *nq;
376
984263bc
MD
377 if (i <= 0)
378 break;
91489f6b
JH
379 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
380 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
381 tp->encloseblk = tp->reportblk;
382 /* report trailing duplicate D-SACK segment */
383 tp->reportblk.rblk_start = q->tqe_th->th_seq;
384 }
385 if ((tp->t_flags & TF_ENCLOSESEG) &&
386 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
387 /* extend enclosing block if one exists */
388 tp->encloseblk.rblk_end = qend;
389 }
984263bc
MD
390 if (i < q->tqe_len) {
391 q->tqe_th->th_seq += i;
392 q->tqe_len -= i;
393 m_adj(q->tqe_m, i);
394 break;
395 }
396
397 nq = LIST_NEXT(q, tqe_q);
398 LIST_REMOVE(q, tqe_q);
399 m_freem(q->tqe_m);
efda3bd0 400 kfree(q, M_TSEGQ);
2d23a8be 401 atomic_add_int(&tcp_reass_qsize, -1);
984263bc
MD
402 q = nq;
403 }
404
405 /* Insert the new segment queue entry into place. */
406 te->tqe_m = m;
407 te->tqe_th = th;
408 te->tqe_len = *tlenp;
409
91489f6b
JH
410 /* check if can coalesce with following segment */
411 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
412 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
413
414 te->tqe_len += q->tqe_len;
a174690a 415 if (q->tqe_th->th_flags & TH_FIN)
f16f8cc3 416 te->tqe_th->th_flags |= TH_FIN;
91489f6b
JH
417 m_cat(te->tqe_m, q->tqe_m);
418 tp->encloseblk.rblk_end = tend;
419 /*
420 * When not reporting a duplicate segment, use
421 * the larger enclosing block as the SACK block.
422 */
423 if (!(tp->t_flags & TF_DUPSEG))
424 tp->reportblk.rblk_end = tend;
425 LIST_REMOVE(q, tqe_q);
efda3bd0 426 kfree(q, M_TSEGQ);
2d23a8be 427 atomic_add_int(&tcp_reass_qsize, -1);
91489f6b
JH
428 }
429
984263bc
MD
430 if (p == NULL) {
431 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
432 } else {
91489f6b
JH
433 /* check if can coalesce with preceding segment */
434 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
a174690a
JH
435 p->tqe_len += te->tqe_len;
436 m_cat(p->tqe_m, te->tqe_m);
91489f6b
JH
437 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
438 /*
439 * When not reporting a duplicate segment, use
440 * the larger enclosing block as the SACK block.
441 */
442 if (!(tp->t_flags & TF_DUPSEG))
443 tp->reportblk.rblk_start = p->tqe_th->th_seq;
efda3bd0 444 kfree(te, M_TSEGQ);
2d23a8be
MD
445 atomic_add_int(&tcp_reass_qsize, -1);
446 } else {
91489f6b 447 LIST_INSERT_AFTER(p, te, tqe_q);
2d23a8be 448 }
984263bc
MD
449 }
450
451present:
452 /*
453 * Present data to user, advancing rcv_nxt through
454 * completed sequence space.
455 */
456 if (!TCPS_HAVEESTABLISHED(tp->t_state))
457 return (0);
458 q = LIST_FIRST(&tp->t_segq);
61896e3c 459 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
984263bc 460 return (0);
91489f6b
JH
461 tp->rcv_nxt += q->tqe_len;
462 if (!(tp->t_flags & TF_DUPSEG)) {
463 /* no SACK block to report since ACK advanced */
464 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
465 }
466 /* no enclosing block to report since ACK advanced */
467 tp->t_flags &= ~TF_ENCLOSESEG;
468 flags = q->tqe_th->th_flags & TH_FIN;
469 LIST_REMOVE(q, tqe_q);
470 KASSERT(LIST_EMPTY(&tp->t_segq) ||
471 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
472 ("segment not coalesced"));
6cef7136 473 if (so->so_state & SS_CANTRCVMORE) {
91489f6b 474 m_freem(q->tqe_m);
6cef7136
MD
475 } else {
476 lwkt_gettoken(&so->so_rcv.ssb_token);
6d49aa6f 477 ssb_appendstream(&so->so_rcv, q->tqe_m);
6cef7136
MD
478 lwkt_reltoken(&so->so_rcv.ssb_token);
479 }
efda3bd0 480 kfree(q, M_TSEGQ);
2d23a8be 481 atomic_add_int(&tcp_reass_qsize, -1);
984263bc
MD
482 ND6_HINT(tp);
483 sorwakeup(so);
484 return (flags);
485}
486
487/*
488 * TCP input routine, follows pages 65-76 of the
489 * protocol specification dated September, 1981 very closely.
490 */
491#ifdef INET6
492int
95b22adf 493tcp6_input(struct mbuf **mp, int *offp, int proto)
984263bc 494{
2256ba69 495 struct mbuf *m = *mp;
984263bc
MD
496 struct in6_ifaddr *ia6;
497
498 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
499
500 /*
501 * draft-itojun-ipv6-tcp-to-anycast
502 * better place to put this in?
503 */
504 ia6 = ip6_getdstifaddr(m);
d24ce1dc 505 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
984263bc
MD
506 struct ip6_hdr *ip6;
507
508 ip6 = mtod(m, struct ip6_hdr *);
509 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
f23061d4 510 offsetof(struct ip6_hdr, ip6_dst));
d24ce1dc 511 return (IPPROTO_DONE);
984263bc
MD
512 }
513
002c1265 514 tcp_input(mp, offp, proto);
d24ce1dc 515 return (IPPROTO_DONE);
984263bc
MD
516}
517#endif
518
002c1265
MD
519int
520tcp_input(struct mbuf **mp, int *offp, int proto)
984263bc 521{
002c1265 522 int off0;
2256ba69
RG
523 struct tcphdr *th;
524 struct ip *ip = NULL;
525 struct ipovly *ipov;
526 struct inpcb *inp = NULL;
984263bc
MD
527 u_char *optp = NULL;
528 int optlen = 0;
b1992928
MD
529 int tlen, off;
530 int len = 0;
984263bc 531 int drop_hdrlen;
2256ba69
RG
532 struct tcpcb *tp = NULL;
533 int thflags;
984263bc 534 struct socket *so = 0;
61896e3c
JH
535 int todrop, acked;
536 boolean_t ourfinisacked, needoutput = FALSE;
984263bc 537 u_long tiwin;
61896e3c 538 int recvwin;
984263bc 539 struct tcpopt to; /* options in this segment */
984263bc
MD
540 struct sockaddr_in *next_hop = NULL;
541 int rstreason; /* For badport_bandlim accounting purposes */
d371a63a 542 int cpu;
984263bc 543 struct ip6_hdr *ip6 = NULL;
002c1265 544 struct mbuf *m;
984263bc 545#ifdef INET6
d24ce1dc 546 boolean_t isipv6;
984263bc 547#else
d24ce1dc 548 const boolean_t isipv6 = FALSE;
984263bc
MD
549#endif
550#ifdef TCPDEBUG
551 short ostate = 0;
552#endif
553
002c1265
MD
554 off0 = *offp;
555 m = *mp;
556 *mp = NULL;
a00138cb 557
d24ce1dc
JH
558 tcpstat.tcps_rcvtotal++;
559
5de23090
SZ
560 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
561 struct m_tag *mtag;
562
563 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
564 KKASSERT(mtag != NULL);
565 next_hop = m_tag_data(mtag);
984263bc 566 }
d24ce1dc 567
984263bc 568#ifdef INET6
d24ce1dc 569 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
984263bc 570#endif
984263bc
MD
571
572 if (isipv6) {
573 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
574 ip6 = mtod(m, struct ip6_hdr *);
407e896e 575 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
984263bc
MD
576 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
577 tcpstat.tcps_rcvbadsum++;
578 goto drop;
579 }
580 th = (struct tcphdr *)((caddr_t)ip6 + off0);
581
582 /*
583 * Be proactive about unspecified IPv6 address in source.
584 * As we use all-zero to indicate unbounded/unconnected pcb,
585 * unspecified IPv6 address can be used to confuse us.
586 *
587 * Note that packets with unspecified IPv6 destination is
588 * already dropped in ip6_input.
589 */
590 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
591 /* XXX stat */
592 goto drop;
593 }
594 } else {
595 /*
596 * Get IP and TCP header together in first mbuf.
597 * Note: IP leaves IP header in first mbuf.
598 */
599 if (off0 > sizeof(struct ip)) {
bddf0751 600 ip_stripoptions(m);
984263bc
MD
601 off0 = sizeof(struct ip);
602 }
55d829f8
JH
603 /* already checked and pulled up in ip_demux() */
604 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
61896e3c 605 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
984263bc
MD
606 ip = mtod(m, struct ip *);
607 ipov = (struct ipovly *)ip;
608 th = (struct tcphdr *)((caddr_t)ip + off0);
609 tlen = ip->ip_len;
610
611 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
612 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
613 th->th_sum = m->m_pkthdr.csum_data;
614 else
615 th->th_sum = in_pseudo(ip->ip_src.s_addr,
616 ip->ip_dst.s_addr,
617 htonl(m->m_pkthdr.csum_data +
618 ip->ip_len +
619 IPPROTO_TCP));
620 th->th_sum ^= 0xffff;
621 } else {
622 /*
623 * Checksum extended TCP header and data.
624 */
625 len = sizeof(struct ip) + tlen;
407e896e 626 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
984263bc
MD
627 ipov->ih_len = (u_short)tlen;
628 ipov->ih_len = htons(ipov->ih_len);
629 th->th_sum = in_cksum(m, len);
630 }
631 if (th->th_sum) {
632 tcpstat.tcps_rcvbadsum++;
633 goto drop;
634 }
635#ifdef INET6
636 /* Re-initialization for later version check */
637 ip->ip_v = IPVERSION;
638#endif
639 }
640
641 /*
642 * Check that TCP offset makes sense,
643 * pull out TCP options and adjust length. XXX
644 */
645 off = th->th_off << 2;
55d829f8
JH
646 /* already checked and pulled up in ip_demux() */
647 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
61896e3c 648 ("bad TCP data offset %d (tlen %d)", off, tlen));
984263bc
MD
649 tlen -= off; /* tlen is used instead of ti->ti_len */
650 if (off > sizeof(struct tcphdr)) {
651 if (isipv6) {
002c1265 652 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
984263bc
MD
653 ip6 = mtod(m, struct ip6_hdr *);
654 th = (struct tcphdr *)((caddr_t)ip6 + off0);
655 } else {
55d829f8
JH
656 /* already pulled up in ip_demux() */
657 KASSERT(m->m_len >= sizeof(struct ip) + off,
61896e3c
JH
658 ("TCP header and options not in one mbuf: "
659 "m_len %d, off %d", m->m_len, off));
984263bc
MD
660 }
661 optlen = off - sizeof(struct tcphdr);
662 optp = (u_char *)(th + 1);
663 }
664 thflags = th->th_flags;
665
666#ifdef TCP_DROP_SYNFIN
667 /*
668 * If the drop_synfin option is enabled, drop all packets with
669 * both the SYN and FIN bits set. This prevents e.g. nmap from
670 * identifying the TCP/IP stack.
671 *
672 * This is a violation of the TCP specification.
673 */
61896e3c 674 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
984263bc
MD
675 goto drop;
676#endif
677
678 /*
679 * Convert TCP protocol specific fields to host format.
680 */
681 th->th_seq = ntohl(th->th_seq);
682 th->th_ack = ntohl(th->th_ack);
683 th->th_win = ntohs(th->th_win);
684 th->th_urp = ntohs(th->th_urp);
685
686 /*
d24ce1dc 687 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
984263bc
MD
688 * until after ip6_savecontrol() is called and before other functions
689 * which don't want those proto headers.
690 * Because ip6_savecontrol() is going to parse the mbuf to
691 * search for data to be passed up to user-land, it wants mbuf
692 * parameters to be unchanged.
693 * XXX: the call of ip6_savecontrol() has been obsoleted based on
694 * latest version of the advanced API (20020110).
695 */
696 drop_hdrlen = off0 + off;
697
698 /*
699 * Locate pcb for segment.
700 */
701findpcb:
702 /* IPFIREWALL_FORWARD section */
d24ce1dc 703 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
984263bc
MD
704 /*
705 * Transparently forwarded. Pretend to be the destination.
d24ce1dc 706 * already got one like this?
984263bc 707 */
6ca1a1cd 708 cpu = mycpu->gd_cpuid;
6ca1a1cd 709 inp = in_pcblookup_hash(&tcbinfo[cpu],
d371a63a 710 ip->ip_src, th->th_sport,
984263bc
MD
711 ip->ip_dst, th->th_dport,
712 0, m->m_pkthdr.rcvif);
713 if (!inp) {
83be63fe
JH
714 /*
715 * It's new. Try to find the ambushing socket.
716 */
717
718 /*
719 * The rest of the ipfw code stores the port in
720 * host order. XXX
721 * (The IP address is still in network order.)
722 */
723 in_port_t dport = next_hop->sin_port ?
724 htons(next_hop->sin_port) :
725 th->th_dport;
726
d371a63a 727 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
83be63fe 728 next_hop->sin_addr.s_addr, dport);
d371a63a 729 inp = in_pcblookup_hash(&tcbinfo[cpu],
984263bc 730 ip->ip_src, th->th_sport,
83be63fe 731 next_hop->sin_addr, dport,
984263bc
MD
732 1, m->m_pkthdr.rcvif);
733 }
734 } else {
6ca1a1cd 735 if (isipv6) {
d371a63a 736 inp = in6_pcblookup_hash(&tcbinfo[0],
984263bc
MD
737 &ip6->ip6_src, th->th_sport,
738 &ip6->ip6_dst, th->th_dport,
739 1, m->m_pkthdr.rcvif);
6ca1a1cd 740 } else {
6ca1a1cd 741 cpu = mycpu->gd_cpuid;
6ca1a1cd 742 inp = in_pcblookup_hash(&tcbinfo[cpu],
984263bc
MD
743 ip->ip_src, th->th_sport,
744 ip->ip_dst, th->th_dport,
745 1, m->m_pkthdr.rcvif);
6ca1a1cd 746 }
984263bc 747 }
984263bc
MD
748
749 /*
750 * If the state is CLOSED (i.e., TCB does not exist) then
751 * all data in the incoming segment is discarded.
752 * If the TCB exists but is in CLOSED state, it is embryonic,
753 * but should either do a listen or a connect soon.
754 */
755 if (inp == NULL) {
756 if (log_in_vain) {
757#ifdef INET6
758 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
759#else
1141eb20
JH
760 char dbuf[sizeof "aaa.bbb.ccc.ddd"];
761 char sbuf[sizeof "aaa.bbb.ccc.ddd"];
984263bc
MD
762#endif
763 if (isipv6) {
764 strcpy(dbuf, "[");
984263bc 765 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
984263bc 766 strcat(dbuf, "]");
95b22adf
JH
767 strcpy(sbuf, "[");
768 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
984263bc
MD
769 strcat(sbuf, "]");
770 } else {
771 strcpy(dbuf, inet_ntoa(ip->ip_dst));
772 strcpy(sbuf, inet_ntoa(ip->ip_src));
773 }
774 switch (log_in_vain) {
775 case 1:
61896e3c 776 if (!(thflags & TH_SYN))
984263bc
MD
777 break;
778 case 2:
779 log(LOG_INFO,
780 "Connection attempt to TCP %s:%d "
781 "from %s:%d flags:0x%02x\n",
782 dbuf, ntohs(th->th_dport), sbuf,
783 ntohs(th->th_sport), thflags);
784 break;
785 default:
786 break;
787 }
788 }
d24ce1dc 789 if (blackhole) {
984263bc
MD
790 switch (blackhole) {
791 case 1:
792 if (thflags & TH_SYN)
793 goto drop;
794 break;
795 case 2:
796 goto drop;
797 default:
798 goto drop;
799 }
800 }
801 rstreason = BANDLIM_RST_CLOSEDPORT;
802 goto dropwithreset;
803 }
61896e3c
JH
804
805#ifdef IPSEC
806 if (isipv6) {
807 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
808 ipsec6stat.in_polvio++;
809 goto drop;
810 }
811 } else {
812 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
813 ipsecstat.in_polvio++;
814 goto drop;
815 }
816 }
817#endif
818#ifdef FAST_IPSEC
819 if (isipv6) {
820 if (ipsec6_in_reject(m, inp))
821 goto drop;
822 } else {
823 if (ipsec4_in_reject(m, inp))
824 goto drop;
825 }
826#endif
95926362
MD
827 /* Check the minimum TTL for socket. */
828#ifdef INET6
829 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
830 goto drop;
831#endif
61896e3c 832
984263bc
MD
833 tp = intotcpcb(inp);
834 if (tp == NULL) {
835 rstreason = BANDLIM_RST_CLOSEDPORT;
836 goto dropwithreset;
837 }
eb594563 838 if (tp->t_state <= TCPS_CLOSED)
984263bc
MD
839 goto drop;
840
841 /* Unscale the window into a 32-bit value. */
95b22adf 842 if (!(thflags & TH_SYN))
984263bc
MD
843 tiwin = th->th_win << tp->snd_scale;
844 else
845 tiwin = th->th_win;
846
847 so = inp->inp_socket;
47654766 848
984263bc 849#ifdef TCPDEBUG
47654766
JH
850 if (so->so_options & SO_DEBUG) {
851 ostate = tp->t_state;
852 if (isipv6)
95b22adf 853 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
47654766 854 else
95b22adf 855 bcopy(ip, tcp_saveipgen, sizeof(*ip));
47654766
JH
856 tcp_savetcp = *th;
857 }
984263bc 858#endif
47654766 859
407e896e 860 bzero(&to, sizeof to);
d24ce1dc 861
47654766
JH
862 if (so->so_options & SO_ACCEPTCONN) {
863 struct in_conninfo inc;
864
984263bc 865#ifdef INET6
d24ce1dc 866 inc.inc_isipv6 = (isipv6 == TRUE);
984263bc
MD
867#endif
868 if (isipv6) {
869 inc.inc6_faddr = ip6->ip6_src;
870 inc.inc6_laddr = ip6->ip6_dst;
871 inc.inc6_route.ro_rt = NULL; /* XXX */
872 } else {
873 inc.inc_faddr = ip->ip_src;
874 inc.inc_laddr = ip->ip_dst;
875 inc.inc_route.ro_rt = NULL; /* XXX */
876 }
877 inc.inc_fport = th->th_sport;
878 inc.inc_lport = th->th_dport;
879
61896e3c
JH
880 /*
881 * If the state is LISTEN then ignore segment if it contains
984263bc
MD
882 * a RST. If the segment contains an ACK then it is bad and
883 * send a RST. If it does not contain a SYN then it is not
884 * interesting; drop it.
885 *
886 * If the state is SYN_RECEIVED (syncache) and seg contains
887 * an ACK, but not for our SYN/ACK, send a RST. If the seg
888 * contains a RST, check the sequence number to see if it
889 * is a valid reset segment.
890 */
61896e3c
JH
891 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
892 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
984263bc
MD
893 if (!syncache_expand(&inc, th, &so, m)) {
894 /*
895 * No syncache entry, or ACK was not
896 * for our SYN/ACK. Send a RST.
897 */
898 tcpstat.tcps_badsyn++;
899 rstreason = BANDLIM_RST_OPENPORT;
900 goto dropwithreset;
901 }
2d23a8be
MD
902
903 /*
904 * Could not complete 3-way handshake,
905 * connection is being closed down, and
906 * syncache will free mbuf.
907 */
984263bc 908 if (so == NULL)
002c1265 909 return(IPPROTO_DONE);
2d23a8be
MD
910
911 /*
912 * We must be in the correct protocol thread
913 * for this connection.
914 */
915 KKASSERT(so->so_port == &curthread->td_msgport);
916
984263bc
MD
917 /*
918 * Socket is created in state SYN_RECEIVED.
919 * Continue processing segment.
920 */
ed894f8c 921 inp = so->so_pcb;
984263bc
MD
922 tp = intotcpcb(inp);
923 /*
924 * This is what would have happened in
925 * tcp_output() when the SYN,ACK was sent.
926 */
927 tp->snd_up = tp->snd_una;
928 tp->snd_max = tp->snd_nxt = tp->iss + 1;
929 tp->last_ack_sent = tp->rcv_nxt;
930/*
931 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
932 * until the _second_ ACK is received:
933 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
934 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
61896e3c 935 * move to ESTAB, set snd_wnd to tiwin.
d24ce1dc 936 */
984263bc
MD
937 tp->snd_wnd = tiwin; /* unscaled */
938 goto after_listen;
939 }
940 if (thflags & TH_RST) {
941 syncache_chkrst(&inc, th);
942 goto drop;
943 }
944 if (thflags & TH_ACK) {
945 syncache_badack(&inc);
946 tcpstat.tcps_badsyn++;
947 rstreason = BANDLIM_RST_OPENPORT;
948 goto dropwithreset;
949 }
950 goto drop;
951 }
952
953 /*
61896e3c 954 * Segment's flags are (SYN) or (SYN | FIN).
984263bc
MD
955 */
956#ifdef INET6
957 /*
958 * If deprecated address is forbidden,
959 * we do not accept SYN to deprecated interface
960 * address to prevent any new inbound connection from
961 * getting established.
962 * When we do not accept SYN, we send a TCP RST,
963 * with deprecated source address (instead of dropping
964 * it). We compromise it as it is much better for peer
965 * to send a RST, and RST will be the final packet
966 * for the exchange.
967 *
968 * If we do not forbid deprecated addresses, we accept
969 * the SYN packet. RFC2462 does not suggest dropping
970 * SYN in this case.
971 * If we decipher RFC2462 5.5.4, it says like this:
972 * 1. use of deprecated addr with existing
973 * communication is okay - "SHOULD continue to be
974 * used"
975 * 2. use of it with new communication:
976 * (2a) "SHOULD NOT be used if alternate address
61896e3c 977 * with sufficient scope is available"
984263bc
MD
978 * (2b) nothing mentioned otherwise.
979 * Here we fall into (2b) case as we have no choice in
980 * our source address selection - we must obey the peer.
981 *
982 * The wording in RFC2462 is confusing, and there are
983 * multiple description text for deprecated address
984 * handling - worse, they are not exactly the same.
985 * I believe 5.5.4 is the best one, so we follow 5.5.4.
986 */
987 if (isipv6 && !ip6_use_deprecated) {
988 struct in6_ifaddr *ia6;
989
990 if ((ia6 = ip6_getdstifaddr(m)) &&
991 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
992 tp = NULL;
993 rstreason = BANDLIM_RST_OPENPORT;
994 goto dropwithreset;
995 }
996 }
997#endif
998 /*
999 * If it is from this socket, drop it, it must be forged.
1000 * Don't bother responding if the destination was a broadcast.
1001 */
1002 if (th->th_dport == th->th_sport) {
1003 if (isipv6) {
1004 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1005 &ip6->ip6_src))
1006 goto drop;
1007 } else {
1008 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1009 goto drop;
1010 }
1011 }
1012 /*
1013 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1014 *
1015 * Note that it is quite possible to receive unicast
1016 * link-layer packets with a broadcast IP address. Use
1017 * in_broadcast() to find them.
1018 */
61896e3c 1019 if (m->m_flags & (M_BCAST | M_MCAST))
984263bc
MD
1020 goto drop;
1021 if (isipv6) {
1022 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1023 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1024 goto drop;
1025 } else {
1026 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1027 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1028 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1029 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1030 goto drop;
1031 }
1032 /*
1033 * SYN appears to be valid; create compressed TCP state
1034 * for syncache, or perform t/tcp connection.
1035 */
1036 if (so->so_qlen <= so->so_qlimit) {
95b22adf 1037 tcp_dooptions(&to, optp, optlen, TRUE);
984263bc
MD
1038 if (!syncache_add(&inc, &to, th, &so, m))
1039 goto drop;
2d23a8be
MD
1040
1041 /*
1042 * Entry added to syncache, mbuf used to
1043 * send SYN,ACK packet.
1044 */
984263bc 1045 if (so == NULL)
002c1265 1046 return(IPPROTO_DONE);
2d23a8be
MD
1047
1048 /*
1049 * We must be in the correct protocol thread for
1050 * this connection.
1051 */
1052 KKASSERT(so->so_port == &curthread->td_msgport);
1053
ed894f8c 1054 inp = so->so_pcb;
984263bc
MD
1055 tp = intotcpcb(inp);
1056 tp->snd_wnd = tiwin;
1057 tp->t_starttime = ticks;
1058 tp->t_state = TCPS_ESTABLISHED;
1059
1060 /*
1061 * If there is a FIN, or if there is data and the
1062 * connection is local, then delay SYN,ACK(SYN) in
1063 * the hope of piggy-backing it on a response
1064 * segment. Otherwise must send ACK now in case
1065 * the other side is slow starting.
1066 */
1067 if (DELAY_ACK(tp) &&
1068 ((thflags & TH_FIN) ||
1069 (tlen != 0 &&
1070 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1071 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
a48c5dd5
SZ
1072 tcp_callout_reset(tp, tp->tt_delack,
1073 tcp_delacktime, tcp_timer_delack);
984263bc 1074 tp->t_flags |= TF_NEEDSYN;
a48c5dd5 1075 } else {
984263bc 1076 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
a48c5dd5 1077 }
984263bc
MD
1078
1079 tcpstat.tcps_connects++;
1080 soisconnected(so);
1081 goto trimthenstep6;
1082 }
1083 goto drop;
1084 }
984263bc 1085
2d23a8be
MD
1086after_listen:
1087 /*
1088 * Should not happen - syncache should pick up these connections.
1089 *
1090 * Once we are past handling listen sockets we must be in the
1091 * correct protocol processing thread.
1092 */
61896e3c 1093 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
2d23a8be 1094 KKASSERT(so->so_port == &curthread->td_msgport);
984263bc 1095
5b0b9fa5
PA
1096 /*
1097 * This is the second part of the MSS DoS prevention code (after
1098 * minmss on the sending side) and it deals with too many too small
1099 * tcp packets in a too short timeframe (1 second).
1100 *
153d34ac
MD
1101 * XXX Removed. This code was crap. It does not scale to network
1102 * speed, and default values break NFS. Gone.
5b0b9fa5 1103 */
153d34ac 1104 /* REMOVED */
5b0b9fa5 1105
984263bc
MD
1106 /*
1107 * Segment received on connection.
efca2b8e
MD
1108 *
1109 * Reset idle time and keep-alive timer. Don't waste time if less
1110 * then a second has elapsed. Only update t_rcvtime for non-SYN
1111 * packets.
1112 *
1113 * Handle the case where one side thinks the connection is established
1114 * but the other side has, say, rebooted without cleaning out the
1115 * connection. The SYNs could be construed as an attack and wind
1116 * up ignored, but in case it isn't an attack we can validate the
1117 * connection by forcing a keepalive.
984263bc 1118 */
efca2b8e
MD
1119 if (TCPS_HAVEESTABLISHED(tp->t_state) && (ticks - tp->t_rcvtime) > hz) {
1120 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
1121 tp->t_flags |= TF_KEEPALIVE;
1122 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
1123 tcp_timer_keep);
1124 } else {
1125 tp->t_rcvtime = ticks;
1126 tp->t_flags &= ~TF_KEEPALIVE;
2a0c7c52
MD
1127 tcp_callout_reset(tp, tp->tt_keep,
1128 tcp_getkeepidle(tp),
efca2b8e
MD
1129 tcp_timer_keep);
1130 }
a48c5dd5 1131 }
984263bc
MD
1132
1133 /*
1134 * Process options.
1135 * XXX this is tradtitional behavior, may need to be cleaned up.
1136 */
95b22adf 1137 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
ad0af98b 1138 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
984263bc
MD
1139 if (to.to_flags & TOF_SCALE) {
1140 tp->t_flags |= TF_RCVD_SCALE;
1141 tp->requested_s_scale = to.to_requested_s_scale;
1142 }
1143 if (to.to_flags & TOF_TS) {
1144 tp->t_flags |= TF_RCVD_TSTMP;
1145 tp->ts_recent = to.to_tsval;
1146 tp->ts_recent_age = ticks;
1147 }
984263bc
MD
1148 if (to.to_flags & TOF_MSS)
1149 tcp_mss(tp, to.to_mss);
91489f6b
JH
1150 /*
1151 * Only set the TF_SACK_PERMITTED per-connection flag
1152 * if we got a SACK_PERMITTED option from the other side
1153 * and the global tcp_do_sack variable is true.
1154 */
1155 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1156 tp->t_flags |= TF_SACK_PERMITTED;
984263bc
MD
1157 }
1158
1159 /*
1160 * Header prediction: check for the two common cases
1161 * of a uni-directional data xfer. If the packet has
1162 * no control flags, is in-sequence, the window didn't
1163 * change and we're not retransmitting, it's a
1164 * candidate. If the length is zero and the ack moved
1165 * forward, we're the sender side of the xfer. Just
1166 * free the data acked & wake any higher level process
1167 * that was blocked waiting for space. If the length
1168 * is non-zero and the ack didn't move, we're the
1169 * receiver side. If we're getting packets in-order
1170 * (the reassembly queue is empty), add the data to
1171 * the socket buffer and note that we need a delayed ack.
1172 * Make sure that the hidden state-flags are also off.
1173 * Since we check for TCPS_ESTABLISHED above, it can only
1174 * be TH_NEEDSYN.
1175 */
1176 if (tp->t_state == TCPS_ESTABLISHED &&
1177 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
61896e3c
JH
1178 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1179 (!(to.to_flags & TOF_TS) ||
984263bc 1180 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
984263bc 1181 th->th_seq == tp->rcv_nxt &&
984263bc
MD
1182 tp->snd_nxt == tp->snd_max) {
1183
1184 /*
1185 * If last ACK falls within this segment's sequence numbers,
1186 * record the timestamp.
1187 * NOTE that the test is modified according to the latest
1188 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1189 */
61896e3c 1190 if ((to.to_flags & TOF_TS) &&
984263bc
MD
1191 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1192 tp->ts_recent_age = ticks;
1193 tp->ts_recent = to.to_tsval;
1194 }
1195
1196 if (tlen == 0) {
1197 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1198 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1199 tp->snd_cwnd >= tp->snd_wnd &&
95b22adf 1200 !IN_FASTRECOVERY(tp)) {
984263bc 1201 /*
be23faf1 1202 * This is a pure ack for outstanding data.
984263bc
MD
1203 */
1204 ++tcpstat.tcps_predack;
1205 /*
1206 * "bad retransmit" recovery
bfdb979e
JH
1207 *
1208 * If Eifel detection applies, then
1209 * it is deterministic, so use it
1210 * unconditionally over the old heuristic.
1211 * Otherwise, fall back to the old heuristic.
984263bc 1212 */
bfdb979e
JH
1213 if (tcp_do_eifel_detect &&
1214 (to.to_flags & TOF_TS) && to.to_tsecr &&
1215 (tp->t_flags & TF_FIRSTACCACK)) {
1216 /* Eifel detection applicable. */
1217 if (to.to_tsecr < tp->t_rexmtTS) {
1218 tcp_revert_congestion_state(tp);
1219 ++tcpstat.tcps_eifeldetected;
1220 }
1221 } else if (tp->t_rxtshift == 1 &&
1222 ticks < tp->t_badrxtwin) {
1223 tcp_revert_congestion_state(tp);
1224 ++tcpstat.tcps_rttdetected;
984263bc 1225 }
8819433a
JH
1226 tp->t_flags &= ~(TF_FIRSTACCACK |
1227 TF_FASTREXMT | TF_EARLYREXMT);
984263bc
MD
1228 /*
1229 * Recalculate the retransmit timer / rtt.
1230 *
d24ce1dc 1231 * Some machines (certain windows boxes)
984263bc
MD
1232 * send broken timestamp replies during the
1233 * SYN+ACK phase, ignore timestamps of 0.
1234 */
95b22adf 1235 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
984263bc 1236 tcp_xmit_timer(tp,
95b22adf 1237 ticks - to.to_tsecr + 1);
984263bc 1238 } else if (tp->t_rtttime &&
95b22adf 1239 SEQ_GT(th->th_ack, tp->t_rtseq)) {
984263bc
MD
1240 tcp_xmit_timer(tp,
1241 ticks - tp->t_rtttime);
1242 }
1243 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1244 acked = th->th_ack - tp->snd_una;
1245 tcpstat.tcps_rcvackpack++;
1246 tcpstat.tcps_rcvackbyte += acked;
6d49aa6f 1247 sbdrop(&so->so_snd.sb, acked);
cfb3f3f4 1248 tp->snd_recover = th->th_ack - 1;
9845754e 1249 tp->snd_una = th->th_ack;
984263bc 1250 tp->t_dupacks = 0;
df9d7670
JH
1251 /*
1252 * Update window information.
1253 */
1254 if (tiwin != tp->snd_wnd &&
1255 acceptable_window_update(tp, th, tiwin)) {
1256 /* keep track of pure window updates */
1257 if (tp->snd_wl2 == th->th_ack &&
1258 tiwin > tp->snd_wnd)
1259 tcpstat.tcps_rcvwinupd++;
1260 tp->snd_wnd = tiwin;
1261 tp->snd_wl1 = th->th_seq;
1262 tp->snd_wl2 = th->th_ack;
1263 if (tp->snd_wnd > tp->max_sndwnd)
1264 tp->max_sndwnd = tp->snd_wnd;
1265 }
984263bc
MD
1266 m_freem(m);
1267 ND6_HINT(tp); /* some progress has been done */
984263bc
MD
1268 /*
1269 * If all outstanding data are acked, stop
1270 * retransmit timer, otherwise restart timer
1271 * using current (possibly backed-off) value.
1272 * If process is waiting for space,
1273 * wakeup/selwakeup/signal. If data
1274 * are ready to send, let tcp_output
1275 * decide between more output or persist.
1276 */
a48c5dd5
SZ
1277 if (tp->snd_una == tp->snd_max) {
1278 tcp_callout_stop(tp, tp->tt_rexmt);
1279 } else if (!tcp_callout_active(tp,
1280 tp->tt_persist)) {
1281 tcp_callout_reset(tp, tp->tt_rexmt,
1282 tp->t_rxtcur, tcp_timer_rexmt);
1283 }
984263bc 1284 sowwakeup(so);
6d49aa6f 1285 if (so->so_snd.ssb_cc > 0)
f23061d4 1286 tcp_output(tp);
002c1265 1287 return(IPPROTO_DONE);
984263bc 1288 }
df9d7670
JH
1289 } else if (tiwin == tp->snd_wnd &&
1290 th->th_ack == tp->snd_una &&
984263bc 1291 LIST_EMPTY(&tp->t_segq) &&
6d49aa6f 1292 tlen <= ssb_space(&so->so_rcv)) {
46e92930 1293 u_long newsize = 0; /* automatic sockbuf scaling */
984263bc 1294 /*
be23faf1 1295 * This is a pure, in-sequence data packet
984263bc
MD
1296 * with nothing on the reassembly queue and
1297 * we have enough buffer space to take it.
1298 */
1299 ++tcpstat.tcps_preddat;
1300 tp->rcv_nxt += tlen;
1301 tcpstat.tcps_rcvpack++;
1302 tcpstat.tcps_rcvbyte += tlen;
1303 ND6_HINT(tp); /* some progress has been done */
5b0b9fa5
PA
1304 /*
1305 * Automatic sizing of receive socket buffer. Often the send
1306 * buffer size is not optimally adjusted to the actual network
1307 * conditions at hand (delay bandwidth product). Setting the
1308 * buffer size too small limits throughput on links with high
1309 * bandwidth and high delay (eg. trans-continental/oceanic links).
1310 *
1311 * On the receive side the socket buffer memory is only rarely
1312 * used to any significant extent. This allows us to be much
1313 * more aggressive in scaling the receive socket buffer. For
1314 * the case that the buffer space is actually used to a large
1315 * extent and we run out of kernel memory we can simply drop
1316 * the new segments; TCP on the sender will just retransmit it
1317 * later. Setting the buffer size too big may only consume too
1318 * much kernel memory if the application doesn't read() from
1319 * the socket or packet loss or reordering makes use of the
1320 * reassembly queue.
1321 *
1322 * The criteria to step up the receive buffer one notch are:
1323 * 1. the number of bytes received during the time it takes
1324 * one timestamp to be reflected back to us (the RTT);
1325 * 2. received bytes per RTT is within seven eighth of the
1326 * current socket buffer size;
1327 * 3. receive buffer size has not hit maximal automatic size;
1328 *
1329 * This algorithm does one step per RTT at most and only if
1330 * we receive a bulk stream w/o packet losses or reorderings.
1331 * Shrinking the buffer during idle times is not necessary as
1332 * it doesn't consume any memory when idle.
1333 *
1334 * TODO: Only step up if the application is actually serving
1335 * the buffer to better manage the socket buffer resources.
1336 */
1337 if (tcp_do_autorcvbuf &&
1338 to.to_tsecr &&
1339 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1340 if (to.to_tsecr > tp->rfbuf_ts &&
1341 to.to_tsecr - tp->rfbuf_ts < hz) {
1342 if (tp->rfbuf_cnt >
1343 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1344 so->so_rcv.ssb_hiwat <
1345 tcp_autorcvbuf_max) {
1346 newsize =
46e92930
MD
1347 ulmin(so->so_rcv.ssb_hiwat +
1348 tcp_autorcvbuf_inc,
1349 tcp_autorcvbuf_max);
5b0b9fa5
PA
1350 }
1351 /* Start over with next RTT. */
1352 tp->rfbuf_ts = 0;
1353 tp->rfbuf_cnt = 0;
1354 } else
1355 tp->rfbuf_cnt += tlen; /* add up */
1356 }
984263bc
MD
1357 /*
1358 * Add data to socket buffer.
1359 */
1360 if (so->so_state & SS_CANTRCVMORE) {
1361 m_freem(m);
1362 } else {
5b0b9fa5 1363 /*
46e92930
MD
1364 * Set new socket buffer size, give up when
1365 * limit is reached.
1366 *
1367 * Adjusting the size can mess up ACK
1368 * sequencing when pure window updates are
1369 * being avoided (which is the default),
1370 * so force an ack.
5b0b9fa5 1371 */
6cef7136 1372 lwkt_gettoken(&so->so_rcv.ssb_token);
46e92930
MD
1373 if (newsize) {
1374 tp->t_flags |= TF_RXRESIZED;
5b0b9fa5 1375 if (!ssb_reserve(&so->so_rcv, newsize,
46e92930 1376 so, NULL)) {
14343ad3 1377 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
46e92930
MD
1378 }
1379 if (newsize >=
1380 (TCP_MAXWIN << tp->rcv_scale)) {
14343ad3 1381 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
46e92930
MD
1382 }
1383 }
09cf73e0 1384 m_adj(m, drop_hdrlen); /* delayed header drop */
6d49aa6f 1385 ssb_appendstream(&so->so_rcv, m);
6cef7136 1386 lwkt_reltoken(&so->so_rcv.ssb_token);
984263bc
MD
1387 }
1388 sorwakeup(so);
2b1ce38a
MD
1389 /*
1390 * This code is responsible for most of the ACKs
1391 * the TCP stack sends back after receiving a data
1392 * packet. Note that the DELAY_ACK check fails if
1393 * the delack timer is already running, which results
1394 * in an ack being sent every other packet (which is
1395 * what we want).
72b37eeb
MD
1396 *
1397 * We then further aggregate acks by not actually
1398 * sending one until the protocol thread has completed
1399 * processing the current backlog of packets. This
1400 * does not delay the ack any further, but allows us
1401 * to take advantage of the packet aggregation that
1402 * high speed NICs do (usually blocks of 8-10 packets)
1403 * to send a single ack rather then four or five acks,
1404 * greatly reducing the ack rate, the return channel
1405 * bandwidth, and the protocol overhead on both ends.
1406 *
1407 * Since this also has the effect of slowing down
1408 * the exponential slow-start ramp-up, systems with
1409 * very large bandwidth-delay products might want
1410 * to turn the feature off.
2b1ce38a 1411 */
984263bc 1412 if (DELAY_ACK(tp)) {
a48c5dd5
SZ
1413 tcp_callout_reset(tp, tp->tt_delack,
1414 tcp_delacktime, tcp_timer_delack);
72b37eeb 1415 } else if (tcp_aggregate_acks) {
984263bc 1416 tp->t_flags |= TF_ACKNOW;
61896e3c 1417 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
2b1ce38a
MD
1418 tp->t_flags |= TF_ONOUTPUTQ;
1419 tp->tt_cpu = mycpu->gd_cpuid;
1420 TAILQ_INSERT_TAIL(
1421 &tcpcbackq[tp->tt_cpu],
1422 tp, t_outputq);
1423 }
72b37eeb
MD
1424 } else {
1425 tp->t_flags |= TF_ACKNOW;
1426 tcp_output(tp);
984263bc 1427 }
002c1265 1428 return(IPPROTO_DONE);
984263bc
MD
1429 }
1430 }
1431
1432 /*
1433 * Calculate amount of space in receive window,
1434 * and then do TCP input processing.
1435 * Receive window is amount of space in rcv queue,
1436 * but not less than advertised window.
1437 */
6d49aa6f 1438 recvwin = ssb_space(&so->so_rcv);
61896e3c
JH
1439 if (recvwin < 0)
1440 recvwin = 0;
1441 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
984263bc 1442
5b0b9fa5
PA
1443 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1444 tp->rfbuf_ts = 0;
1445 tp->rfbuf_cnt = 0;
1446
984263bc 1447 switch (tp->t_state) {
984263bc
MD
1448 /*
1449 * If the state is SYN_RECEIVED:
1450 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1451 */
1452 case TCPS_SYN_RECEIVED:
1453 if ((thflags & TH_ACK) &&
1454 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1455 SEQ_GT(th->th_ack, tp->snd_max))) {
1456 rstreason = BANDLIM_RST_OPENPORT;
1457 goto dropwithreset;
1458 }
1459 break;
1460
1461 /*
1462 * If the state is SYN_SENT:
1463 * if seg contains an ACK, but not for our SYN, drop the input.
1464 * if seg contains a RST, then drop the connection.
1465 * if seg does not contain SYN, then drop it.
1466 * Otherwise this is an acceptable SYN segment
1467 * initialize tp->rcv_nxt and tp->irs
1468 * if seg contains ack then advance tp->snd_una
1469 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1470 * arrange for segment to be acked (eventually)
1471 * continue processing rest of data/controls, beginning with URG
1472 */
1473 case TCPS_SYN_SENT:
984263bc
MD
1474 if ((thflags & TH_ACK) &&
1475 (SEQ_LEQ(th->th_ack, tp->iss) ||
1476 SEQ_GT(th->th_ack, tp->snd_max))) {
27b8aee3
AE
1477 rstreason = BANDLIM_UNLIMITED;
1478 goto dropwithreset;
984263bc
MD
1479 }
1480 if (thflags & TH_RST) {
1481 if (thflags & TH_ACK)
1482 tp = tcp_drop(tp, ECONNREFUSED);
1483 goto drop;
1484 }
61896e3c 1485 if (!(thflags & TH_SYN))
984263bc
MD
1486 goto drop;
1487 tp->snd_wnd = th->th_win; /* initial send window */
984263bc
MD
1488
1489 tp->irs = th->th_seq;
1490 tcp_rcvseqinit(tp);
1491 if (thflags & TH_ACK) {
27b8aee3 1492 /* Our SYN was acked. */
984263bc
MD
1493 tcpstat.tcps_connects++;
1494 soisconnected(so);
1495 /* Do window scaling on this connection? */
61896e3c 1496 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
b5572302 1497 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
984263bc
MD
1498 tp->snd_scale = tp->requested_s_scale;
1499 tp->rcv_scale = tp->request_r_scale;
1500 }
984263bc
MD
1501 tp->rcv_adv += tp->rcv_wnd;
1502 tp->snd_una++; /* SYN is acked */
a48c5dd5 1503 tcp_callout_stop(tp, tp->tt_rexmt);
984263bc
MD
1504 /*
1505 * If there's data, delay ACK; if there's also a FIN
1506 * ACKNOW will be turned on later.
1507 */
a48c5dd5
SZ
1508 if (DELAY_ACK(tp) && tlen != 0) {
1509 tcp_callout_reset(tp, tp->tt_delack,
1510 tcp_delacktime, tcp_timer_delack);
1511 } else {
984263bc 1512 tp->t_flags |= TF_ACKNOW;
a48c5dd5 1513 }
984263bc
MD
1514 /*
1515 * Received <SYN,ACK> in SYN_SENT[*] state.
1516 * Transitions:
1517 * SYN_SENT --> ESTABLISHED
1518 * SYN_SENT* --> FIN_WAIT_1
1519 */
1520 tp->t_starttime = ticks;
1521 if (tp->t_flags & TF_NEEDFIN) {
1522 tp->t_state = TCPS_FIN_WAIT_1;
1523 tp->t_flags &= ~TF_NEEDFIN;
1524 thflags &= ~TH_SYN;
1525 } else {
1526 tp->t_state = TCPS_ESTABLISHED;
2a0c7c52
MD
1527 tcp_callout_reset(tp, tp->tt_keep,
1528 tcp_getkeepidle(tp),
1529 tcp_timer_keep);
984263bc
MD
1530 }
1531 } else {
1532 /*
95b22adf 1533 * Received initial SYN in SYN-SENT[*] state =>
27b8aee3
AE
1534 * simultaneous open.
1535 * Do 3-way handshake:
61896e3c
JH
1536 * SYN-SENT -> SYN-RECEIVED
1537 * SYN-SENT* -> SYN-RECEIVED*
95b22adf 1538 */
984263bc 1539 tp->t_flags |= TF_ACKNOW;
a48c5dd5 1540 tcp_callout_stop(tp, tp->tt_rexmt);
27b8aee3 1541 tp->t_state = TCPS_SYN_RECEIVED;
984263bc
MD
1542 }
1543
1544trimthenstep6:
1545 /*
1546 * Advance th->th_seq to correspond to first data byte.
1547 * If data, trim to stay within window,
1548 * dropping FIN if necessary.
1549 */
1550 th->th_seq++;
1551 if (tlen > tp->rcv_wnd) {
1552 todrop = tlen - tp->rcv_wnd;
1553 m_adj(m, -todrop);
1554 tlen = tp->rcv_wnd;
1555 thflags &= ~TH_FIN;
1556 tcpstat.tcps_rcvpackafterwin++;
1557 tcpstat.tcps_rcvbyteafterwin += todrop;
1558 }
1559 tp->snd_wl1 = th->th_seq - 1;
1560 tp->rcv_up = th->th_seq;
1561 /*
1562 * Client side of transaction: already sent SYN and data.
1563 * If the remote host used T/TCP to validate the SYN,
1564 * our data will be ACK'd; if so, enter normal data segment
1565 * processing in the middle of step 5, ack processing.
1566 * Otherwise, goto step 6.
1567 */
95b22adf 1568 if (thflags & TH_ACK)
984263bc
MD
1569 goto process_ACK;
1570
1571 goto step6;
1572
1573 /*
1574 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
27b8aee3 1575 * do normal processing (we no longer bother with T/TCP).
984263bc
MD
1576 */
1577 case TCPS_LAST_ACK:
1578 case TCPS_CLOSING:
1579 case TCPS_TIME_WAIT:
95b22adf 1580 break; /* continue normal processing */
984263bc
MD
1581 }
1582
1583 /*
1584 * States other than LISTEN or SYN_SENT.
1585 * First check the RST flag and sequence number since reset segments
1586 * are exempt from the timestamp and connection count tests. This
1587 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1588 * below which allowed reset segments in half the sequence space
1589 * to fall though and be processed (which gives forged reset
1590 * segments with a random sequence number a 50 percent chance of
1591 * killing a connection).
1592 * Then check timestamp, if present.
1593 * Then check the connection count, if present.
1594 * Then check that at least some bytes of segment are within
1595 * receive window. If segment begins before rcv_nxt,
1596 * drop leading data (and SYN); if nothing left, just ack.
1597 *
1598 *
1599 * If the RST bit is set, check the sequence number to see
1600 * if this is a valid reset segment.
1601 * RFC 793 page 37:
1602 * In all states except SYN-SENT, all reset (RST) segments
1603 * are validated by checking their SEQ-fields. A reset is
1604 * valid if its sequence number is in the window.
1605 * Note: this does not take into account delayed ACKs, so
1606 * we should test against last_ack_sent instead of rcv_nxt.
1607 * The sequence number in the reset segment is normally an
91489f6b 1608 * echo of our outgoing acknowledgement numbers, but some hosts
984263bc
MD
1609 * send a reset with the sequence number at the rightmost edge
1610 * of our receive window, and we have to handle this case.
1611 * If we have multiple segments in flight, the intial reset
1612 * segment sequence numbers will be to the left of last_ack_sent,
1613 * but they will eventually catch up.
1614 * In any case, it never made sense to trim reset segments to
1615 * fit the receive window since RFC 1122 says:
1616 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1617 *
1618 * A TCP SHOULD allow a received RST segment to include data.
1619 *
1620 * DISCUSSION
61896e3c
JH
1621 * It has been suggested that a RST segment could contain
1622 * ASCII text that encoded and explained the cause of the
91489f6b 1623 * RST. No standard has yet been established for such
61896e3c 1624 * data.
984263bc
MD
1625 *
1626 * If the reset segment passes the sequence number test examine
1627 * the state:
1628 * SYN_RECEIVED STATE:
1629 * If passive open, return to LISTEN state.
1630 * If active open, inform user that connection was refused.
1631 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1632 * Inform user that connection was reset, and close tcb.
1633 * CLOSING, LAST_ACK STATES:
1634 * Close the tcb.
1635 * TIME_WAIT STATE:
1636 * Drop the segment - see Stevens, vol. 2, p. 964 and
61896e3c 1637 * RFC 1337.
984263bc
MD
1638 */
1639 if (thflags & TH_RST) {
1640 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
d4dbb5be 1641 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
984263bc
MD
1642 switch (tp->t_state) {
1643
1644 case TCPS_SYN_RECEIVED:
1645 so->so_error = ECONNREFUSED;
1646 goto close;
1647
1648 case TCPS_ESTABLISHED:
1649 case TCPS_FIN_WAIT_1:
1650 case TCPS_FIN_WAIT_2:
1651 case TCPS_CLOSE_WAIT:
1652 so->so_error = ECONNRESET;
1653 close:
1654 tp->t_state = TCPS_CLOSED;
1655 tcpstat.tcps_drops++;
1656 tp = tcp_close(tp);
1657 break;
1658
1659 case TCPS_CLOSING:
1660 case TCPS_LAST_ACK:
1661 tp = tcp_close(tp);
1662 break;
1663
1664 case TCPS_TIME_WAIT:
1665 break;
1666 }
1667 }
1668 goto drop;
1669 }
1670
1671 /*
1672 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1673 * and it's less than ts_recent, drop it.
1674 */
61896e3c 1675 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
984263bc
MD
1676 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1677
1678 /* Check to see if ts_recent is over 24 days old. */
1679 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1680 /*
1681 * Invalidate ts_recent. If this segment updates
1682 * ts_recent, the age will be reset later and ts_recent
1683 * will get a valid value. If it does not, setting
1684 * ts_recent to zero will at least satisfy the
1685 * requirement that zero be placed in the timestamp
1686 * echo reply when ts_recent isn't valid. The
1687 * age isn't reset until we get a valid ts_recent
1688 * because we don't want out-of-order segments to be
1689 * dropped when ts_recent is old.
1690 */
1691 tp->ts_recent = 0;
1692 } else {
1693 tcpstat.tcps_rcvduppack++;
1694 tcpstat.tcps_rcvdupbyte += tlen;
1695 tcpstat.tcps_pawsdrop++;
1696 if (tlen)
1697 goto dropafterack;
1698 goto drop;
1699 }
1700 }
1701
984263bc
MD
1702 /*
1703 * In the SYN-RECEIVED state, validate that the packet belongs to
1704 * this connection before trimming the data to fit the receive
1705 * window. Check the sequence number versus IRS since we know
1706 * the sequence numbers haven't wrapped. This is a partial fix
1707 * for the "LAND" DoS attack.
1708 */
1709 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1710 rstreason = BANDLIM_RST_OPENPORT;
1711 goto dropwithreset;
1712 }
1713
1714 todrop = tp->rcv_nxt - th->th_seq;
1715 if (todrop > 0) {
91489f6b
JH
1716 if (TCP_DO_SACK(tp)) {
1717 /* Report duplicate segment at head of packet. */
1718 tp->reportblk.rblk_start = th->th_seq;
1719 tp->reportblk.rblk_end = th->th_seq + tlen;
1720 if (thflags & TH_FIN)
1721 ++tp->reportblk.rblk_end;
1722 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1723 tp->reportblk.rblk_end = tp->rcv_nxt;
1724 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1725 }
984263bc
MD
1726 if (thflags & TH_SYN) {
1727 thflags &= ~TH_SYN;
1728 th->th_seq++;
1729 if (th->th_urp > 1)
1730 th->th_urp--;
1731 else
1732 thflags &= ~TH_URG;
1733 todrop--;
1734 }
1735 /*
1736 * Following if statement from Stevens, vol. 2, p. 960.
1737 */
61896e3c
JH
1738 if (todrop > tlen ||
1739 (todrop == tlen && !(thflags & TH_FIN))) {
984263bc
MD
1740 /*
1741 * Any valid FIN must be to the left of the window.
1742 * At this point the FIN must be a duplicate or out
1743 * of sequence; drop it.
1744 */
1745 thflags &= ~TH_FIN;
1746
1747 /*
1748 * Send an ACK to resynchronize and drop any data.
1749 * But keep on processing for RST or ACK.
1750 */
1751 tp->t_flags |= TF_ACKNOW;
1752 todrop = tlen;
1753 tcpstat.tcps_rcvduppack++;
1754 tcpstat.tcps_rcvdupbyte += todrop;
1755 } else {
1756 tcpstat.tcps_rcvpartduppack++;
1757 tcpstat.tcps_rcvpartdupbyte += todrop;
1758 }
1759 drop_hdrlen += todrop; /* drop from the top afterwards */
1760 th->th_seq += todrop;
1761 tlen -= todrop;
1762 if (th->th_urp > todrop)
1763 th->th_urp -= todrop;
1764 else {
1765 thflags &= ~TH_URG;
1766 th->th_urp = 0;
1767 }
1768 }
1769
1770 /*
1771 * If new data are received on a connection after the
1772 * user processes are gone, then RST the other end.
1773 */
1774 if ((so->so_state & SS_NOFDREF) &&
1775 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1776 tp = tcp_close(tp);
1777 tcpstat.tcps_rcvafterclose++;
1778 rstreason = BANDLIM_UNLIMITED;
1779 goto dropwithreset;
1780 }
1781
1782 /*
1783 * If segment ends after window, drop trailing data
1784 * (and PUSH and FIN); if nothing left, just ACK.
1785 */
61896e3c 1786 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
984263bc
MD
1787 if (todrop > 0) {
1788 tcpstat.tcps_rcvpackafterwin++;
1789 if (todrop >= tlen) {
1790 tcpstat.tcps_rcvbyteafterwin += tlen;
1791 /*
1792 * If a new connection request is received
1793 * while in TIME_WAIT, drop the old connection
1794 * and start over if the sequence numbers
1795 * are above the previous ones.
1796 */
1797 if (thflags & TH_SYN &&
1798 tp->t_state == TCPS_TIME_WAIT &&
1799 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1800 tp = tcp_close(tp);
1801 goto findpcb;
1802 }
1803 /*
1804 * If window is closed can only take segments at
1805 * window edge, and have to drop data and PUSH from
1806 * incoming segments. Continue processing, but
1807 * remember to ack. Otherwise, drop segment
1808 * and ack.
1809 */
1810 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1811 tp->t_flags |= TF_ACKNOW;
1812 tcpstat.tcps_rcvwinprobe++;
1813 } else
1814 goto dropafterack;
1815 } else
1816 tcpstat.tcps_rcvbyteafterwin += todrop;
1817 m_adj(m, -todrop);
1818 tlen -= todrop;
61896e3c 1819 thflags &= ~(TH_PUSH | TH_FIN);
984263bc
MD
1820 }
1821
1822 /*
1823 * If last ACK falls within this segment's sequence numbers,
1824 * record its timestamp.
ad0af98b
ND
1825 * NOTE:
1826 * 1) That the test incorporates suggestions from the latest
1827 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1828 * 2) That updating only on newer timestamps interferes with
1829 * our earlier PAWS tests, so this check should be solely
1830 * predicated on the sequence space of this segment.
1831 * 3) That we modify the segment boundary check to be
1832 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1833 * instead of RFC1323's
1834 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1835 * This modified check allows us to overcome RFC1323's
1836 * limitations as described in Stevens TCP/IP Illustrated
1837 * Vol. 2 p.869. In such cases, we can still calculate the
1838 * RTT correctly when RCV.NXT == Last.ACK.Sent.
984263bc 1839 */
ad0af98b
ND
1840 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1841 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1842 + ((thflags & TH_SYN) != 0)
1843 + ((thflags & TH_FIN) != 0)))) {
984263bc
MD
1844 tp->ts_recent_age = ticks;
1845 tp->ts_recent = to.to_tsval;
1846 }
1847
1848 /*
1849 * If a SYN is in the window, then this is an
1850 * error and we send an RST and drop the connection.
1851 */
1852 if (thflags & TH_SYN) {
1853 tp = tcp_drop(tp, ECONNRESET);
1854 rstreason = BANDLIM_UNLIMITED;
1855 goto dropwithreset;
1856 }
1857
1858 /*
1859 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1860 * flag is on (half-synchronized state), then queue data for
1861 * later processing; else drop segment and return.
1862 */
61896e3c 1863 if (!(thflags & TH_ACK)) {
984263bc
MD
1864 if (tp->t_state == TCPS_SYN_RECEIVED ||
1865 (tp->t_flags & TF_NEEDSYN))
1866 goto step6;
1867 else
1868 goto drop;
1869 }
1870
1871 /*
1872 * Ack processing.
1873 */
1874 switch (tp->t_state) {
984263bc 1875 /*
91489f6b 1876 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
984263bc
MD
1877 * ESTABLISHED state and continue processing.
1878 * The ACK was checked above.
1879 */
1880 case TCPS_SYN_RECEIVED:
1881
1882 tcpstat.tcps_connects++;
1883 soisconnected(so);
1884 /* Do window scaling? */
61896e3c 1885 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
b5572302 1886 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
984263bc
MD
1887 tp->snd_scale = tp->requested_s_scale;
1888 tp->rcv_scale = tp->request_r_scale;
1889 }
984263bc
MD
1890 /*
1891 * Make transitions:
1892 * SYN-RECEIVED -> ESTABLISHED
1893 * SYN-RECEIVED* -> FIN-WAIT-1
1894 */
1895 tp->t_starttime = ticks;
1896 if (tp->t_flags & TF_NEEDFIN) {
1897 tp->t_state = TCPS_FIN_WAIT_1;
1898 tp->t_flags &= ~TF_NEEDFIN;
1899 } else {
1900 tp->t_state = TCPS_ESTABLISHED;
2a0c7c52
MD
1901 tcp_callout_reset(tp, tp->tt_keep,
1902 tcp_getkeepidle(tp),
1903 tcp_timer_keep);
984263bc
MD
1904 }
1905 /*
1906 * If segment contains data or ACK, will call tcp_reass()
1907 * later; if not, do so now to pass queued data to user.
1908 */
61896e3c 1909 if (tlen == 0 && !(thflags & TH_FIN))
f23061d4 1910 tcp_reass(tp, NULL, NULL, NULL);
984263bc
MD
1911 /* fall into ... */
1912
1913 /*
1914 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1915 * ACKs. If the ack is in the range
1916 * tp->snd_una < th->th_ack <= tp->snd_max
1917 * then advance tp->snd_una to th->th_ack and drop
1918 * data from the retransmission queue. If this ACK reflects
1919 * more up to date window information we update our window information.
1920 */
1921 case TCPS_ESTABLISHED:
1922 case TCPS_FIN_WAIT_1:
1923 case TCPS_FIN_WAIT_2:
1924 case TCPS_CLOSE_WAIT:
1925 case TCPS_CLOSING:
1926 case TCPS_LAST_ACK:
1927 case TCPS_TIME_WAIT:
1928
1929 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
91489f6b
JH
1930 if (TCP_DO_SACK(tp))
1931 tcp_sack_update_scoreboard(tp, &to);
95b22adf
JH
1932 if (tlen != 0 || tiwin != tp->snd_wnd) {
1933 tp->t_dupacks = 0;
1934 break;
1935 }
1936 tcpstat.tcps_rcvdupack++;
a48c5dd5 1937 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
91489f6b
JH
1938 th->th_ack != tp->snd_una) {
1939 tp->t_dupacks = 0;
1940 break;
1941 }
95b22adf 1942 /*
91489f6b 1943 * We have outstanding data (other than
95b22adf
JH
1944 * a window probe), this is a completely
1945 * duplicate ack (ie, window info didn't
1946 * change), the ack is the biggest we've
1947 * seen and we've seen exactly our rexmt
91489f6b 1948 * threshhold of them, so assume a packet
95b22adf
JH
1949 * has been dropped and retransmit it.
1950 * Kludge snd_nxt & the congestion
1951 * window so we send only this one
1952 * packet.
95b22adf 1953 */
91489f6b
JH
1954 if (IN_FASTRECOVERY(tp)) {
1955 if (TCP_DO_SACK(tp)) {
1956 /* No artifical cwnd inflation. */
1957 tcp_sack_rexmt(tp, th);
1958 } else {
1959 /*
1960 * Dup acks mean that packets
1961 * have left the network
1962 * (they're now cached at the
1963 * receiver) so bump cwnd by
1964 * the amount in the receiver
1965 * to keep a constant cwnd
1966 * packets in the network.
1967 */
1968 tp->snd_cwnd += tp->t_maxseg;
f23061d4 1969 tcp_output(tp);
91489f6b
JH
1970 }
1971 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
95b22adf
JH
1972 tp->t_dupacks = 0;
1973 break;
95b22adf 1974 } else if (++tp->t_dupacks == tcprexmtthresh) {
91489f6b 1975 tcp_seq old_snd_nxt;
95b22adf
JH
1976 u_int win;
1977
8819433a 1978fastretransmit:
95b22adf
JH
1979 if (tcp_do_eifel_detect &&
1980 (tp->t_flags & TF_RCVD_TSTMP)) {
1981 tcp_save_congestion_state(tp);
1982 tp->t_flags |= TF_FASTREXMT;
1983 }
91489f6b
JH
1984 /*
1985 * We know we're losing at the current
1986 * window size, so do congestion avoidance:
1987 * set ssthresh to half the current window
1988 * and pull our congestion window back to the
1989 * new ssthresh.
1990 */
95b22adf
JH
1991 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1992 tp->t_maxseg;
1993 if (win < 2)
1994 win = 2;
1995 tp->snd_ssthresh = win * tp->t_maxseg;
1996 ENTER_FASTRECOVERY(tp);
1997 tp->snd_recover = tp->snd_max;
a48c5dd5 1998 tcp_callout_stop(tp, tp->tt_rexmt);
95b22adf 1999 tp->t_rtttime = 0;
91489f6b 2000 old_snd_nxt = tp->snd_nxt;
95b22adf
JH
2001 tp->snd_nxt = th->th_ack;
2002 tp->snd_cwnd = tp->t_maxseg;
f23061d4 2003 tcp_output(tp);
95b22adf 2004 ++tcpstat.tcps_sndfastrexmit;
91489f6b
JH
2005 tp->snd_cwnd = tp->snd_ssthresh;
2006 tp->rexmt_high = tp->snd_nxt;
2007 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
2008 tp->snd_nxt = old_snd_nxt;
95b22adf
JH
2009 KASSERT(tp->snd_limited <= 2,
2010 ("tp->snd_limited too big"));
91489f6b
JH
2011 if (TCP_DO_SACK(tp))
2012 tcp_sack_rexmt(tp, th);
2013 else
2014 tp->snd_cwnd += tp->t_maxseg *
2015 (tp->t_dupacks - tp->snd_limited);
95b22adf
JH
2016 } else if (tcp_do_limitedtransmit) {
2017 u_long oldcwnd = tp->snd_cwnd;
2018 tcp_seq oldsndmax = tp->snd_max;
9e707f76 2019 tcp_seq oldsndnxt = tp->snd_nxt;
95b22adf
JH
2020 /* outstanding data */
2021 uint32_t ownd = tp->snd_max - tp->snd_una;
2022 u_int sent;
ca94b4a6 2023
8819433a
JH
2024#define iceildiv(n, d) (((n)+(d)-1) / (d))
2025
95b22adf
JH
2026 KASSERT(tp->t_dupacks == 1 ||
2027 tp->t_dupacks == 2,
2028 ("dupacks not 1 or 2"));
2029 if (tp->t_dupacks == 1)
2030 tp->snd_limited = 0;
9e707f76 2031 tp->snd_nxt = tp->snd_max;
95b22adf
JH
2032 tp->snd_cwnd = ownd +
2033 (tp->t_dupacks - tp->snd_limited) *
2034 tp->t_maxseg;
f23061d4 2035 tcp_output(tp);
98cb2337
MD
2036
2037 /*
2038 * Other acks may have been processed,
2039 * snd_nxt cannot be reset to a value less
2040 * then snd_una.
2041 */
2042 if (SEQ_LT(oldsndnxt, oldsndmax)) {
2043 if (SEQ_GT(oldsndnxt, tp->snd_una))
6d08465d 2044 tp->snd_nxt = oldsndnxt;
98cb2337
MD
2045 else
2046 tp->snd_nxt = tp->snd_una;
2047 }
95b22adf
JH
2048 tp->snd_cwnd = oldcwnd;
2049 sent = tp->snd_max - oldsndmax;
2050 if (sent > tp->t_maxseg) {
2051 KASSERT((tp->t_dupacks == 2 &&
2052 tp->snd_limited == 0) ||
2053 (sent == tp->t_maxseg + 1 &&
2054 tp->t_flags & TF_SENTFIN),
2055 ("sent too much"));
2056 KASSERT(sent <= tp->t_maxseg * 2,
2057 ("sent too many segments"));
2058 tp->snd_limited = 2;
2059 tcpstat.tcps_sndlimited += 2;
2060 } else if (sent > 0) {
2061 ++tp->snd_limited;
2062 ++tcpstat.tcps_sndlimited;
2063 } else if (tcp_do_early_retransmit &&
2064 (tcp_do_eifel_detect &&
2065 (tp->t_flags & TF_RCVD_TSTMP)) &&
91489f6b 2066 ownd < 4 * tp->t_maxseg &&
95b22adf 2067 tp->t_dupacks + 1 >=
91489f6b
JH
2068 iceildiv(ownd, tp->t_maxseg) &&
2069 (!TCP_DO_SACK(tp) ||
f23061d4 2070 ownd <= tp->t_maxseg ||
91489f6b 2071 tcp_sack_has_sacked(&tp->scb,
f23061d4 2072 ownd - tp->t_maxseg))) {
95b22adf
JH
2073 ++tcpstat.tcps_sndearlyrexmit;
2074 tp->t_flags |= TF_EARLYREXMT;
2075 goto fastretransmit;
984263bc 2076 }
95b22adf
JH
2077 }
2078 goto drop;
984263bc
MD
2079 }
2080
2081 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
984263bc
MD
2082 tp->t_dupacks = 0;
2083 if (SEQ_GT(th->th_ack, tp->snd_max)) {
5a274421
JH
2084 /*
2085 * Detected optimistic ACK attack.
2086 * Force slow-start to de-synchronize attack.
2087 */
2088 tp->snd_cwnd = tp->t_maxseg;
8acdb67c 2089 tp->snd_wacked = 0;
5a274421 2090
984263bc
MD
2091 tcpstat.tcps_rcvacktoomuch++;
2092 goto dropafterack;
2093 }
2094 /*
2095 * If we reach this point, ACK is not a duplicate,
2096 * i.e., it ACKs something we sent.
2097 */
2098 if (tp->t_flags & TF_NEEDSYN) {
2099 /*
2100 * T/TCP: Connection was half-synchronized, and our
2101 * SYN has been ACK'd (so connection is now fully
2102 * synchronized). Go to non-starred state,
2103 * increment snd_una for ACK of SYN, and check if
2104 * we can do window scaling.
2105 */
2106 tp->t_flags &= ~TF_NEEDSYN;
2107 tp->snd_una++;
2108 /* Do window scaling? */
61896e3c
JH
2109 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2110 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
984263bc
MD
2111 tp->snd_scale = tp->requested_s_scale;
2112 tp->rcv_scale = tp->request_r_scale;
2113 }
2114 }
2115
2116process_ACK:
2117 acked = th->th_ack - tp->snd_una;
2118 tcpstat.tcps_rcvackpack++;
2119 tcpstat.tcps_rcvackbyte += acked;
2120
b5572302 2121 if (tcp_do_eifel_detect && acked > 0 &&
95b22adf 2122 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
bfdb979e
JH
2123 (tp->t_flags & TF_FIRSTACCACK)) {
2124 /* Eifel detection applicable. */
2125 if (to.to_tsecr < tp->t_rexmtTS) {
bfdb979e 2126 ++tcpstat.tcps_eifeldetected;
8819433a
JH
2127 tcp_revert_congestion_state(tp);
2128 if (tp->t_rxtshift == 1 &&
2129 ticks >= tp->t_badrxtwin)
2130 ++tcpstat.tcps_rttcantdetect;
bfdb979e
JH
2131 }
2132 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
b5572302
JH
2133 /*
2134 * If we just performed our first retransmit,
2135 * and the ACK arrives within our recovery window,
2136 * then it was a mistake to do the retransmit
91489f6b 2137 * in the first place. Recover our original cwnd
b5572302
JH
2138 * and ssthresh, and proceed to transmit where we
2139 * left off.
2140 */
bfdb979e
JH
2141 tcp_revert_congestion_state(tp);
2142 ++tcpstat.tcps_rttdetected;
984263bc
MD
2143 }
2144
2145 /*
2146 * If we have a timestamp reply, update smoothed
2147 * round trip time. If no timestamp is present but
2148 * transmit timer is running and timed sequence
2149 * number was acked, update smoothed round trip time.
2150 * Since we now have an rtt measurement, cancel the
2151 * timer backoff (cf., Phil Karn's retransmit alg.).
2152 * Recompute the initial retransmit timer.
2153 *
2154 * Some machines (certain windows boxes) send broken
d24ce1dc 2155 * timestamp replies during the SYN+ACK phase, ignore
984263bc
MD
2156 * timestamps of 0.
2157 */
95b22adf 2158 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
984263bc 2159 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
95b22adf 2160 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
984263bc 2161 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
984263bc
MD
2162 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2163
984263bc
MD
2164 /*
2165 * If no data (only SYN) was ACK'd,
2166 * skip rest of ACK processing.
2167 */
2168 if (acked == 0)
2169 goto step6;
2170
efd4b327 2171 /* Stop looking for an acceptable ACK since one was received. */
8819433a 2172 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
efd4b327 2173
6d49aa6f
MD
2174 if (acked > so->so_snd.ssb_cc) {
2175 tp->snd_wnd -= so->so_snd.ssb_cc;
2176 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
61896e3c 2177 ourfinisacked = TRUE;
984263bc 2178 } else {
6d49aa6f 2179 sbdrop(&so->so_snd.sb, acked);
984263bc 2180 tp->snd_wnd -= acked;
61896e3c 2181 ourfinisacked = FALSE;
984263bc
MD
2182 }
2183 sowwakeup(so);
91489f6b
JH
2184
2185 /*
2186 * Update window information.
2187 * Don't look at window if no ACK:
2188 * TAC's send garbage on first SYN.
2189 */
2190 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2191 (tp->snd_wl1 == th->th_seq &&
2192 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2193 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2194 /* keep track of pure window updates */
2195 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2196 tiwin > tp->snd_wnd)
2197 tcpstat.tcps_rcvwinupd++;
2198 tp->snd_wnd = tiwin;
2199 tp->snd_wl1 = th->th_seq;
2200 tp->snd_wl2 = th->th_ack;
2201 if (tp->snd_wnd > tp->max_sndwnd)
2202 tp->max_sndwnd = tp->snd_wnd;
2203 needoutput = TRUE;
2204 }
2205
2206 tp->snd_una = th->th_ack;
2207 if (TCP_DO_SACK(tp))
2208 tcp_sack_update_scoreboard(tp, &to);
95b22adf 2209 if (IN_FASTRECOVERY(tp)) {
91489f6b 2210 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
95b22adf 2211 EXIT_FASTRECOVERY(tp);
91489f6b
JH
2212 needoutput = TRUE;
2213 /*
2214 * If the congestion window was inflated
2215 * to account for the other side's
2216 * cached packets, retract it.
8acdb67c
JH
2217 */
2218 if (!TCP_DO_SACK(tp))
2219 tp->snd_cwnd = tp->snd_ssthresh;
2220
2221 /*
91489f6b
JH
2222 * Window inflation should have left us
2223 * with approximately snd_ssthresh outstanding
2224 * data. But, in case we would be inclined
2225 * to send a burst, better do it using
2226 * slow start.
2227 */
91489f6b
JH
2228 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2229 tp->snd_max + 2 * tp->t_maxseg))
2230 tp->snd_cwnd =
2231 (tp->snd_max - tp->snd_una) +
2232 2 * tp->t_maxseg;
8acdb67c
JH
2233
2234 tp->snd_wacked = 0;
91489f6b
JH
2235 } else {
2236 if (TCP_DO_SACK(tp)) {
2237 tp->snd_max_rexmt = tp->snd_max;
2238 tcp_sack_rexmt(tp, th);
2239 } else {
2240 tcp_newreno_partial_ack(tp, th, acked);
2241 }
2242 needoutput = FALSE;
2243 }
95b22adf 2244 } else {
91489f6b 2245 /*
8acdb67c
JH
2246 * Open the congestion window. When in slow-start,
2247 * open exponentially: maxseg per packet. Otherwise,
2248 * open linearly: maxseg per window.
91489f6b 2249 */
8acdb67c
JH
2250 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2251 u_int abc_sslimit =
2252 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2253 tp->t_maxseg : 2 * tp->t_maxseg);
2254
2255 /* slow-start */
2256 tp->snd_cwnd += tcp_do_abc ?
2257 min(acked, abc_sslimit) : tp->t_maxseg;
2258 } else {
2259 /* linear increase */
2260 tp->snd_wacked += tcp_do_abc ? acked :
2261 tp->t_maxseg;
2262 if (tp->snd_wacked >= tp->snd_cwnd) {
2263 tp->snd_wacked -= tp->snd_cwnd;
2264 tp->snd_cwnd += tp->t_maxseg;
2265 }
2266 }
2267 tp->snd_cwnd = min(tp->snd_cwnd,
2268 TCP_MAXWIN << tp->snd_scale);
95b22adf 2269 tp->snd_recover = th->th_ack - 1;
cfb3f3f4 2270 }
984263bc
MD
2271 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2272 tp->snd_nxt = tp->snd_una;
2273
91489f6b
JH
2274 /*
2275 * If all outstanding data is acked, stop retransmit
2276 * timer and remember to restart (more output or persist).
2277 * If there is more data to be acked, restart retransmit
2278 * timer, using current (possibly backed-off) value.
2279 */
2280 if (th->th_ack == tp->snd_max) {
a48c5dd5 2281 tcp_callout_stop(tp, tp->tt_rexmt);
91489f6b 2282 needoutput = TRUE;
a48c5dd5
SZ
2283 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2284 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2285 tcp_timer_rexmt);
2286 }
91489f6b 2287
984263bc 2288 switch (tp->t_state) {
984263bc
MD
2289 /*
2290 * In FIN_WAIT_1 STATE in addition to the processing
2291 * for the ESTABLISHED state if our FIN is now acknowledged
2292 * then enter FIN_WAIT_2.
2293 */
2294 case TCPS_FIN_WAIT_1:
2295 if (ourfinisacked) {
2296 /*
2297 * If we can't receive any more
2298 * data, then closing user can proceed.
2299 * Starting the timer is contrary to the
2300 * specification, but if we don't get a FIN
2301 * we'll hang forever.
2302 */
2303 if (so->so_state & SS_CANTRCVMORE) {
2304 soisdisconnected(so);
a48c5dd5
SZ
2305 tcp_callout_reset(tp, tp->tt_2msl,
2306 tcp_maxidle, tcp_timer_2msl);
984263bc
MD
2307 }
2308 tp->t_state = TCPS_FIN_WAIT_2;
2309 }
2310 break;
2311
95b22adf 2312 /*
984263bc
MD
2313 * In CLOSING STATE in addition to the processing for
2314 * the ESTABLISHED state if the ACK acknowledges our FIN
2315 * then enter the TIME-WAIT state, otherwise ignore
2316 * the segment.
2317 */
2318 case TCPS_CLOSING:
2319 if (ourfinisacked) {
2320 tp->t_state = TCPS_TIME_WAIT;
2321 tcp_canceltimers(tp);
27b8aee3 2322 tcp_callout_reset(tp, tp->tt_2msl,
a48c5dd5 2323 2 * tcp_msl, tcp_timer_2msl);
984263bc
MD
2324 soisdisconnected(so);
2325 }
2326 break;
2327
2328 /*
2329 * In LAST_ACK, we may still be waiting for data to drain
2330 * and/or to be acked, as well as for the ack of our FIN.
2331 * If our FIN is now acknowledged, delete the TCB,
2332 * enter the closed state and return.
2333 */
2334 case TCPS_LAST_ACK:
2335 if (ourfinisacked) {
2336 tp = tcp_close(tp);
2337 goto drop;
2338 }
2339 break;
2340
2341 /*
2342 * In TIME_WAIT state the only thing that should arrive
2343 * is a retransmission of the remote FIN. Acknowledge
2344 * it and restart the finack timer.
2345 */
2346 case TCPS_TIME_WAIT:
a48c5dd5
SZ
2347 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2348 tcp_timer_2msl);
984263bc
MD
2349 goto dropafterack;
2350 }
2351 }
2352
2353step6:
2354 /*
2355 * Update window information.
2356 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2357 */
2358 if ((thflags & TH_ACK) &&
df9d7670 2359 acceptable_window_update(tp, th, tiwin)) {
984263bc 2360 /* keep track of pure window updates */
b5572302
JH
2361 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2362 tiwin > tp->snd_wnd)
984263bc
MD
2363 tcpstat.tcps_rcvwinupd++;
2364 tp->snd_wnd = tiwin;
2365 tp->snd_wl1 = th->th_seq;
2366 tp->snd_wl2 = th->th_ack;
2367 if (tp->snd_wnd > tp->max_sndwnd)
2368 tp->max_sndwnd = tp->snd_wnd;
61896e3c 2369 needoutput = TRUE;
984263bc
MD
2370 }
2371
2372 /*
2373 * Process segments with URG.
2374 */
2375 if ((thflags & TH_URG) && th->th_urp &&
95b22adf 2376 !TCPS_HAVERCVDFIN(tp->t_state)) {
984263bc
MD
2377 /*
2378 * This is a kludge, but if we receive and accept
2379 * random urgent pointers, we'll crash in
2380 * soreceive. It's hard to imagine someone
2381 * actually wanting to send this much urgent data.
2382 */
6d49aa6f 2383 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
984263bc
MD
2384 th->th_urp = 0; /* XXX */
2385 thflags &= ~TH_URG; /* XXX */
2386 goto dodata; /* XXX */
2387 }
2388 /*
2389 * If this segment advances the known urgent pointer,
2390 * then mark the data stream. This should not happen
2391 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2392 * a FIN has been received from the remote side.
2393 * In these states we ignore the URG.
2394 *
2395 * According to RFC961 (Assigned Protocols),
2396 * the urgent pointer points to the last octet
2397 * of urgent data. We continue, however,
2398 * to consider it to indicate the first octet
2399 * of data past the urgent section as the original
2400 * spec states (in one of two places).
2401 */
61896e3c 2402 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
984263bc 2403 tp->rcv_up = th->th_seq + th->th_urp;
6d49aa6f 2404 so->so_oobmark = so->so_rcv.ssb_cc +
984263bc
MD
2405 (tp->rcv_up - tp->rcv_nxt) - 1;
2406 if (so->so_oobmark == 0)
6cef7136 2407 sosetstate(so, SS_RCVATMARK);
984263bc
MD
2408 sohasoutofband(so);
2409 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2410 }
2411 /*
2412 * Remove out of band data so doesn't get presented to user.
2413 * This can happen independent of advancing the URG pointer,
2414 * but if two URG's are pending at once, some out-of-band
2415 * data may creep in... ick.
2416 */
61896e3c
JH
2417 if (th->th_urp <= (u_long)tlen &&
2418 !(so->so_options & SO_OOBINLINE)) {
2419 /* hdr drop is delayed */
2420 tcp_pulloutofband(so, th, m, drop_hdrlen);
2421 }
984263bc
MD
2422 } else {
2423 /*
2424 * If no out of band data is expected,
2425 * pull receive urgent pointer along
2426 * with the receive window.
2427 */
2428 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2429 tp->rcv_up = tp->rcv_nxt;
2430 }
984263bc 2431
61896e3c 2432dodata: /* XXX */
984263bc
MD
2433 /*
2434 * Process the segment text, merging it into the TCP sequencing queue,
2435 * and arranging for acknowledgment of receipt if necessary.
2436 * This process logically involves adjusting tp->rcv_wnd as data
2437 * is presented to the user (this happens in tcp_usrreq.c,
2438 * case PRU_RCVD). If a FIN has already been received on this
2439 * connection then we just ignore the text.
2440 */
95b22adf 2441 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
984263bc
MD
2442 m_adj(m, drop_hdrlen); /* delayed header drop */
2443 /*
2444 * Insert segment which includes th into TCP reassembly queue
2445 * with control block tp. Set thflags to whether reassembly now
2446 * includes a segment with FIN. This handles the common case
2447 * inline (segment is the next to be received on an established
2448 * connection, and the queue is empty), avoiding linkage into
2449 * and removal from the queue and repetition of various
2450 * conversions.
2451 * Set DELACK for segments received in order, but ack
2452 * immediately when segments are out of order (so
2453 * fast retransmit can work).
2454 */
2455 if (th->th_seq == tp->rcv_nxt &&
2456 LIST_EMPTY(&tp->t_segq) &&
2457 TCPS_HAVEESTABLISHED(tp->t_state)) {
a48c5dd5
SZ
2458 if (DELAY_ACK(tp)) {
2459 tcp_callout_reset(tp, tp->tt_delack,
2460 tcp_delacktime, tcp_timer_delack);
2461 } else {
984263bc 2462 tp->t_flags |= TF_ACKNOW;
a48c5dd5 2463 }
984263bc
MD
2464 tp->rcv_nxt += tlen;
2465 thflags = th->th_flags & TH_FIN;
2466 tcpstat.tcps_rcvpack++;
2467 tcpstat.tcps_rcvbyte += tlen;
2468 ND6_HINT(tp);
6cef7136 2469 if (so->so_state & SS_CANTRCVMORE) {
984263bc 2470 m_freem(m);
6cef7136
MD
2471 } else {
2472 lwkt_gettoken(&so->so_rcv.ssb_token);
6d49aa6f 2473 ssb_appendstream(&so->so_rcv, m);
6cef7136
MD
2474 lwkt_reltoken(&so->so_rcv.ssb_token);
2475 }
984263bc
MD
2476 sorwakeup(so);
2477 } else {
91489f6b
JH
2478 if (!(tp->t_flags & TF_DUPSEG)) {
2479 /* Initialize SACK report block. */
2480 tp->reportblk.rblk_start = th->th_seq;
2481 tp->reportblk.rblk_end = th->th_seq + tlen +
2482 ((thflags & TH_FIN) != 0);
2483 }
984263bc
MD
2484 thflags = tcp_reass(tp, th, &tlen, m);
2485 tp->t_flags |= TF_ACKNOW;
2486 }
2487
2488 /*
2489 * Note the amount of data that peer has sent into
2490 * our window, in order to estimate the sender's
2491 * buffer size.
2492 */
6d49aa6f 2493 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
984263bc
MD
2494 } else {
2495 m_freem(m);
2496 thflags &= ~TH_FIN;
2497 }
2498
2499 /*
2500 * If FIN is received ACK the FIN and let the user know
2501 * that the connection is closing.
2502 */
2503 if (thflags & TH_FIN) {
95b22adf 2504 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
984263bc
MD
2505 socantrcvmore(so);
2506 /*
2507 * If connection is half-synchronized
2508 * (ie NEEDSYN flag on) then delay ACK,
2509 * so it may be piggybacked when SYN is sent.
2510 * Otherwise, since we received a FIN then no
2511 * more input can be expected, send ACK now.
2512 */
a48c5dd5
SZ
2513 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2514 tcp_callout_reset(tp, tp->tt_delack,
2515 tcp_delacktime, tcp_timer_delack);
2516 } else {
984263bc 2517 tp->t_flags |= TF_ACKNOW;
a48c5dd5 2518 }
984263bc
MD
2519 tp->rcv_nxt++;
2520 }
984263bc 2521
61896e3c 2522 switch (tp->t_state) {
95b22adf 2523 /*
984263bc
MD
2524 * In SYN_RECEIVED and ESTABLISHED STATES
2525 * enter the CLOSE_WAIT state.
2526 */
2527 case TCPS_SYN_RECEIVED:
2528 tp->t_starttime = ticks;
2529 /*FALLTHROUGH*/
2530 case TCPS_ESTABLISHED:
2531 tp->t_state = TCPS_CLOSE_WAIT;
2532 break;
2533
95b22adf 2534 /*
984263bc
MD
2535 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2536 * enter the CLOSING state.
2537 */
2538 case TCPS_FIN_WAIT_1:
2539 tp->t_state = TCPS_CLOSING;
2540 break;
2541
95b22adf 2542 /*
984263bc
MD
2543 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2544 * starting the time-wait timer, turning off the other
2545 * standard timers.
2546 */
2547 case TCPS_FIN_WAIT_2:
2548 tp->t_state = TCPS_TIME_WAIT;
2549 tcp_canceltimers(tp);
27b8aee3 2550 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
a48c5dd5 2551 tcp_timer_2msl);
984263bc
MD
2552 soisdisconnected(so);
2553 break;
2554
2555 /*
2556 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2557 */
2558 case TCPS_TIME_WAIT:
a48c5dd5
SZ
2559 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_msl,
2560 tcp_timer_2msl);
984263bc
MD
2561 break;
2562 }
2563 }
61896e3c 2564
984263bc
MD
2565#ifdef TCPDEBUG
2566 if (so->so_options & SO_DEBUG)
f23061d4 2567 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
984263bc
MD
2568#endif
2569
2570 /*
2571 * Return any desired output.
2572 */
2573 if (needoutput || (tp->t_flags & TF_ACKNOW))
f23061d4 2574 tcp_output(tp);
002c1265 2575 return(IPPROTO_DONE);
984263bc
MD
2576
2577dropafterack:
2578 /*
2579 * Generate an ACK dropping incoming segment if it occupies
2580 * sequence space, where the ACK reflects our state.
2581 *
2582 * We can now skip the test for the RST flag since all
2583 * paths to this code happen after packets containing
2584 * RST have been dropped.
2585 *
2586 * In the SYN-RECEIVED state, don't send an ACK unless the
2587 * segment we received passes the SYN-RECEIVED ACK test.
2588 * If it fails send a RST. This breaks the loop in the
2589 * "LAND" DoS attack, and also prevents an ACK storm
2590 * between two listening ports that have been sent forged
2591 * SYN segments, each with the source address of the other.
2592 */
2593 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2594 (SEQ_GT(tp->snd_una, th->th_ack) ||
2595 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2596 rstreason = BANDLIM_RST_OPENPORT;
2597 goto dropwithreset;
2598 }
2599#ifdef TCPDEBUG
2600 if (so->so_options & SO_DEBUG)
f23061d4 2601 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
984263bc
MD
2602#endif
2603 m_freem(m);
2604 tp->t_flags |= TF_ACKNOW;
f23061d4 2605 tcp_output(tp);
002c1265 2606 return(IPPROTO_DONE);
984263bc
MD
2607
2608dropwithreset:
2609 /*
2610 * Generate a RST, dropping incoming segment.
2611 * Make ACK acceptable to originator of segment.
2612 * Don't bother to respond if destination was broadcast/multicast.
2613 */
61896e3c 2614 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
984263bc
MD
2615 goto drop;
2616 if (isipv6) {
2617 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2618 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2619 goto drop;
2620 } else {
2621 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2622 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
95b22adf
JH
2623 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2624 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
984263bc
MD
2625 goto drop;
2626 }
2627 /* IPv6 anycast check is done at tcp6_input() */
2628
2629 /*
2630 * Perform bandwidth limiting.
2631 */
2632#ifdef ICMP_BANDLIM
2633 if (badport_bandlim(rstreason) < 0)
2634 goto drop;
2635#endif
2636
2637#ifdef TCPDEBUG
2638 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
f23061d4 2639 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
984263bc
MD
2640#endif
2641 if (thflags & TH_ACK)
2642 /* mtod() below is safe as long as hdr dropping is delayed */
2643 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2644 TH_RST);
2645 else {
2646 if (thflags & TH_SYN)
2647 tlen++;
2648 /* mtod() below is safe as long as hdr dropping is delayed */
61896e3c
JH
2649 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2650 (tcp_seq)0, TH_RST | TH_ACK);
984263bc 2651 }
002c1265 2652 return(IPPROTO_DONE);
984263bc
MD
2653
2654drop:
2655 /*
2656 * Drop space held by incoming segment and return.
2657 */
2658#ifdef TCPDEBUG
2659 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
f23061d4 2660 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
984263bc
MD
2661#endif
2662 m_freem(m);
002c1265 2663 return(IPPROTO_DONE);
984263bc
MD
2664}
2665
2666/*
2667 * Parse TCP options and place in tcpopt.
2668 */
2669static void
95b22adf 2670tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
984263bc 2671{
91489f6b 2672 int opt, optlen, i;
984263bc
MD
2673
2674 to->to_flags = 0;
2675 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2676 opt = cp[0];
2677 if (opt == TCPOPT_EOL)
2678 break;
2679 if (opt == TCPOPT_NOP)
2680 optlen = 1;
2681 else {
2682 if (cnt < 2)
2683 break;
2684 optlen = cp[1];
2685 if (optlen < 2 || optlen > cnt)
2686 break;
2687 }
2688 switch (opt) {
2689 case TCPOPT_MAXSEG:
2690 if (optlen != TCPOLEN_MAXSEG)
2691 continue;
2692 if (!is_syn)
2693 continue;
2694 to->to_flags |= TOF_MSS;
407e896e 2695 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
984263bc
MD
2696 to->to_mss = ntohs(to->to_mss);
2697 break;
2698 case TCPOPT_WINDOW:
2699 if (optlen != TCPOLEN_WINDOW)
2700 continue;
95b22adf 2701 if (!is_syn)
984263bc
MD
2702 continue;
2703 to->to_flags |= TOF_SCALE;
2704 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2705 break;
2706 case TCPOPT_TIMESTAMP:
2707 if (optlen != TCPOLEN_TIMESTAMP)
2708 continue;
2709 to->to_flags |= TOF_TS;
407e896e 2710 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
984263bc 2711 to->to_tsval = ntohl(to->to_tsval);
407e896e 2712 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
984263bc 2713 to->to_tsecr = ntohl(to->to_tsecr);
ad0af98b
ND
2714 /*
2715 * If echoed timestamp is later than the current time,
2716 * fall back to non RFC1323 RTT calculation.
2717 */
2718 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2719 to->to_tsecr = 0;
984263bc 2720 break;
91489f6b
JH
2721 case TCPOPT_SACK_PERMITTED:
2722 if (optlen != TCPOLEN_SACK_PERMITTED)
2723 continue;
2724 if (!is_syn)
2725 continue;
2726 to->to_flags |= TOF_SACK_PERMITTED;
2727 break;
2728 case TCPOPT_SACK:
2729 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2730 continue;
2731 to->to_nsackblocks = (optlen - 2) / 8;
2732 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2733 to->to_flags |= TOF_SACK;
2734 for (i = 0; i < to->to_nsackblocks; i++) {
2735 struct raw_sackblock *r = &to->to_sackblocks[i];
2736
2737 r->rblk_start = ntohl(r->rblk_start);
2738 r->rblk_end = ntohl(r->rblk_end);
2739 }
2740 break;
b1992928
MD
2741#ifdef TCP_SIGNATURE
2742 /*
2743 * XXX In order to reply to a host which has set the
2744 * TCP_SIGNATURE option in its initial SYN, we have to
2745 * record the fact that the option was observed here
2746 * for the syncache code to perform the correct response.
2747 */
2748 case TCPOPT_SIGNATURE:
2749 if (optlen != TCPOLEN_SIGNATURE)
2750 continue;
2751 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2752 break;
2753#endif /* TCP_SIGNATURE */
984263bc
MD
2754 default:
2755 continue;
2756 }
2757 }
2758}
2759
2760/*
2761 * Pull out of band byte out of a segment so
2762 * it doesn't appear in the user's data queue.
2763 * It is still reflected in the segment length for
2764 * sequencing purposes.
95b22adf 2765 * "off" is the delayed to be dropped hdrlen.
984263bc
MD
2766 */
2767static void
95b22adf 2768tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
984263bc
MD
2769{
2770 int cnt = off + th->th_urp - 1;
2771
2772 while (cnt >= 0) {
2773 if (m->m_len > cnt) {
2774 char *cp = mtod(m, caddr_t) + cnt;
2775 struct tcpcb *tp = sototcpcb(so);
2776
2777 tp->t_iobc = *cp;
2778 tp->t_oobflags |= TCPOOB_HAVEDATA;
95b22adf 2779 bcopy(cp + 1, cp, m->m_len - cnt - 1);
984263bc
MD
2780 m->m_len--;
2781 if (m->m_flags & M_PKTHDR)
2782 m->m_pkthdr.len--;
2783 return;
2784 }
2785 cnt -= m->m_len;
2786 m = m->m_next;
2787 if (m == 0)
2788 break;
2789 }
2790 panic("tcp_pulloutofband");
2791}
2792
2793/*
2794 * Collect new round-trip time estimate
2795 * and update averages and current timeout.
2796 */
2797static void
95b22adf 2798tcp_xmit_timer(struct tcpcb *tp, int rtt)
984263bc 2799{
2256ba69 2800 int delta;
984263bc
MD
2801
2802 tcpstat.tcps_rttupdated++;
2803 tp->t_rttupdated++;
2804 if (tp->t_srtt != 0) {
2805 /*
2806 * srtt is stored as fixed point with 5 bits after the
2807 * binary point (i.e., scaled by 8). The following magic
2808 * is equivalent to the smoothing algorithm in rfc793 with
2809 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2810 * point). Adjust rtt to origin 0.
2811 */
2812 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2813 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2814
2815 if ((tp->t_srtt += delta) <= 0)
2816 tp->t_srtt = 1;
2817
2818 /*
2819 * We accumulate a smoothed rtt variance (actually, a
2820 * smoothed mean difference), then set the retransmit
2821 * timer to smoothed rtt + 4 times the smoothed variance.
2822 * rttvar is stored as fixed point with 4 bits after the
2823 * binary point (scaled by 16). The following is
2824 * equivalent to rfc793 smoothing with an alpha of .75
2825 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2826 * rfc793's wired-in beta.
2827 */
2828 if (delta < 0)
2829 delta = -delta;
2830 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2831 if ((tp->t_rttvar += delta) <= 0)
2832 tp->t_rttvar = 1;
2833 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2834 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2835 } else {
2836 /*
2837 * No rtt measurement yet - use the unsmoothed rtt.
2838 * Set the variance to half the rtt (so our first
2839 * retransmit happens at 3*rtt).
2840 */
2841 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2842 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2843 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2844 }
2845 tp->t_rtttime = 0;
2846 tp->t_rxtshift = 0;
2847
2848 /*
2849 * the retransmit should happen at rtt + 4 * rttvar.
2850 * Because of the way we do the smoothing, srtt and rttvar
2851 * will each average +1/2 tick of bias. When we compute
2852 * the retransmit timer, we want 1/2 tick of rounding and
2853 * 1 extra tick because of +-1/2 tick uncertainty in the
2854 * firing of the timer. The bias will give us exactly the
2855 * 1.5 tick we need. But, because the bias is
2856 * statistical, we have to test that we don't drop below
2857 * the minimum feasible timer (which is 2 ticks).
2858 */
2859 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2860 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2861
2862 /*
2863 * We received an ack for a packet that wasn't retransmitted;
2864 * it is probably safe to discard any error indications we've
2865 * received recently. This isn't quite right, but close enough
2866 * for now (a route might have failed after we sent a segment,
2867 * and the return path might not be symmetrical).
2868 */
2869 tp->t_softerror = 0;
2870}
2871
2872/*
2873 * Determine a reasonable value for maxseg size.
2874 * If the route is known, check route for mtu.
2875 * If none, use an mss that can be handled on the outgoing
2876 * interface without forcing IP to fragment; if bigger than
2877 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2878 * to utilize large mbufs. If no route is found, route has no mtu,
2879 * or the destination isn't local, use a default, hopefully conservative
2880 * size (usually 512 or the default IP max size, but no more than the mtu
2881 * of the interface), as we can't discover anything about intervening
2882 * gateways or networks. We also initialize the congestion/slow start
2883 * window to be a single segment if the destination isn't local.
2884 * While looking at the routing entry, we also initialize other path-dependent
2885 * parameters from pre-set or cached values in the routing entry.
2886 *
2887 * Also take into account the space needed for options that we
2888 * send regularly. Make maxseg shorter by that amount to assure
2889 * that we can send maxseg amount of data even when the options
2890 * are present. Store the upper limit of the length of options plus
2891 * data in maxopd.
2892 *
2893 * NOTE that this routine is only called when we process an incoming
2894 * segment, for outgoing segments only tcp_mssopt is called.
984263bc
MD
2895 */
2896void
95b22adf 2897tcp_mss(struct tcpcb *tp, int offer)
984263bc 2898{
2256ba69 2899 struct rtentry *rt;
984263bc 2900 struct ifnet *ifp;
2256ba69 2901 int rtt, mss;
984263bc
MD
2902 u_long bufsize;
2903 struct inpcb *inp = tp->t_inpcb;
2904 struct socket *so;
984263bc 2905#ifdef INET6
d24ce1dc 2906 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
984263bc
MD
2907 size_t min_protoh = isipv6 ?
2908 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2909 sizeof(struct tcpiphdr);
2910#else
d24ce1dc 2911 const boolean_t isipv6 = FALSE;
984263bc
MD
2912 const size_t min_protoh = sizeof(struct tcpiphdr);
2913#endif
2914
2915 if (isipv6)
2916 rt = tcp_rtlookup6(&inp->inp_inc);
2917 else
2918 rt = tcp_rtlookup(&inp->inp_inc);
2919 if (rt == NULL) {
2920 tp->t_maxopd = tp->t_maxseg =
d24ce1dc 2921 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
984263bc
MD
2922 return;
2923 }
2924 ifp = rt->rt_ifp;
2925 so = inp->inp_socket;
2926
984263bc
MD
2927 /*
2928 * Offer == 0 means that there was no MSS on the SYN segment,
b235ad6d
MD
2929 * in this case we use either the interface mtu or tcp_mssdflt.
2930 *
2931 * An offer which is too large will be cut down later.
984263bc 2932 */
5b0b9fa5 2933 if (offer == 0) {
b235ad6d
MD
2934 if (isipv6) {
2935 if (in6_localaddr(&inp->in6p_faddr)) {
2936 offer = ND_IFINFO(rt->rt_ifp)->linkmtu -
2937 min_protoh;
2938 } else {
2939 offer = tcp_v6mssdflt;
2940 }
2941 } else {
2942 if (in_localaddr(inp->inp_faddr))
2943 offer = ifp->if_mtu - min_protoh;
2944 else
2945 offer = tcp_mssdflt;
2946 }
5b0b9fa5 2947 }
b235ad6d
MD
2948
2949 /*
2950 * Prevent DoS attack with too small MSS. Round up
2951 * to at least minmss.
2952 *
2953 * Sanity check: make sure that maxopd will be large
2954 * enough to allow some data on segments even is the
2955 * all the option space is used (40bytes). Otherwise
2956 * funny things may happen in tcp_output.
2957 */
2958 offer = max(offer, tcp_minmss);
2959 offer = max(offer, 64);
2960
27b8aee3 2961 rt->rt_rmx.rmx_mssopt = offer;
984263bc
MD
2962
2963 /*
2964 * While we're here, check if there's an initial rtt
2965 * or rttvar. Convert from the route-table units
2966 * to scaled multiples of the slow timeout timer.
2967 */
2968 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2969 /*
2970 * XXX the lock bit for RTT indicates that the value
2971 * is also a minimum value; this is subject to time.
2972 */
2973 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2974 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2975 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2976 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2977 tcpstat.tcps_usedrtt++;
2978 if (rt->rt_rmx.rmx_rttvar) {
2979 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2980 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2981 tcpstat.tcps_usedrttvar++;
2982 } else {
2983 /* default variation is +- 1 rtt */
2984 tp->t_rttvar =
2985 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2986 }
2987 TCPT_RANGESET(tp->t_rxtcur,
2988 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2989 tp->t_rttmin, TCPTV_REXMTMAX);
2990 }
b235ad6d 2991
984263bc
MD
2992 /*
2993 * if there's an mtu associated with the route, use it
b235ad6d
MD
2994 * else, use the link mtu. Take the smaller of mss or offer
2995 * as our final mss.
984263bc 2996 */
b235ad6d 2997 if (rt->rt_rmx.rmx_mtu) {
984263bc 2998 mss = rt->rt_rmx.rmx_mtu - min_protoh;
b235ad6d
MD
2999 } else {
3000 if (isipv6)
698ac46c 3001 mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
b235ad6d 3002 else
984263bc 3003 mss = ifp->if_mtu - min_protoh;
984263bc
MD
3004 }
3005 mss = min(mss, offer);
b235ad6d 3006
984263bc
MD
3007 /*
3008 * maxopd stores the maximum length of data AND options
3009 * in a segment; maxseg is the amount of data in a normal
3010 * segment. We need to store this value (maxopd) apart
3011 * from maxseg, because now every segment carries options
3012 * and thus we normally have somewhat less data in segments.
3013 */
3014 tp->t_maxopd = mss;
3015
61896e3c 3016 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
27b8aee3 3017 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
984263bc 3018 mss -= TCPOLEN_TSTAMP_APPA;
984263bc
MD
3019
3020#if (MCLBYTES & (MCLBYTES - 1)) == 0
3021 if (mss > MCLBYTES)
3022 mss &= ~(MCLBYTES-1);
3023#else
3024 if (mss > MCLBYTES)
3025 mss = mss / MCLBYTES * MCLBYTES;
3026#endif
3027 /*
3028 * If there's a pipesize, change the socket buffer
3029 * to that size. Make the socket buffers an integral
3030 * number of mss units; if the mss is larger than
3031 * the socket buffer, decrease the mss.
3032 */
3033#ifdef RTV_SPIPE
3034 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3035#endif
6d49aa6f 3036 bufsize = so->so_snd.ssb_hiwat;
984263bc
MD
3037 if (bufsize < mss)
3038 mss = bufsize;
3039 else {
3040 bufsize = roundup(bufsize, mss);
3041 if (bufsize > sb_max)
3042 bufsize = sb_max;
6d49aa6f
MD
3043 if (bufsize > so->so_snd.ssb_hiwat)
3044 ssb_reserve(&so->so_snd, bufsize, so, NULL);
984263bc
MD
3045 }
3046 tp->t_maxseg = mss;
3047
3048#ifdef RTV_RPIPE
3049 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3050#endif
6d49aa6f 3051 bufsize = so->so_rcv.ssb_hiwat;
984263bc
MD
3052 if (bufsize > mss) {
3053 bufsize = roundup(bufsize, mss);
3054 if (bufsize > sb_max)
3055 bufsize = sb_max;
6cef7136
MD
3056 if (bufsize > so->so_rcv.ssb_hiwat) {
3057 lwkt_gettoken(&so->so_rcv.ssb_token);
6d49aa6f 3058 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
6cef7136
MD
3059 lwkt_reltoken(&so->so_rcv.ssb_token);
3060 }
984263bc
MD
3061 }
3062
3063 /*
3064 * Set the slow-start flight size depending on whether this
3065 * is a local network or not.
3066 */
4b52d5ee
JH
3067 if (tcp_do_rfc3390)
3068 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
4b52d5ee 3069 else
cd149066 3070 tp->snd_cwnd = mss;
984263bc
MD
3071
3072 if (rt->rt_rmx.rmx_ssthresh) {
3073 /*
3074 * There's some sort of gateway or interface
3075 * buffer limit on the path. Use this to set
3076 * the slow start threshhold, but set the
3077 * threshold to no less than 2*mss.
3078 */
3079 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3080 tcpstat.tcps_usedssthresh++;
3081 }
3082}
3083
3084/*
3085 * Determine the MSS option to send on an outgoing SYN.
3086 */
3087int
95b22adf 3088tcp_mssopt(struct tcpcb *tp)
984263bc
MD
3089{
3090 struct rtentry *rt;
3091#ifdef INET6
d24ce1dc
JH
3092 boolean_t isipv6 =
3093 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
984263bc
MD
3094 int min_protoh = isipv6 ?
3095 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3096 sizeof(struct tcpiphdr);
3097#else
d24ce1dc 3098 const boolean_t isipv6 = FALSE;
984263bc
MD
3099 const size_t min_protoh = sizeof(struct tcpiphdr);
3100#endif
3101
3102 if (isipv6)
3103 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3104 else
3105 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3106 if (rt == NULL)
3107 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3108
3109 return (rt->rt_ifp->if_mtu - min_protoh);
3110}
3111
984263bc
MD
3112/*
3113 * When a partial ack arrives, force the retransmission of the
91489f6b
JH
3114 * next unacknowledged segment. Do not exit Fast Recovery.
3115 *
3116 * Implement the Slow-but-Steady variant of NewReno by restarting the
3117 * the retransmission timer. Turn it off here so it can be restarted
3118 * later in tcp_output().
984263bc
MD
3119 */
3120static void
91489f6b 3121tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
984263bc 3122{
91489f6b
JH
3123 tcp_seq old_snd_nxt = tp->snd_nxt;
3124 u_long ocwnd = tp->snd_cwnd;
984263bc 3125
a48c5dd5 3126 tcp_callout_stop(tp, tp->tt_rexmt);
984263bc
MD
3127 tp->t_rtttime = 0;
3128 tp->snd_nxt = th->th_ack;
91489f6b
JH
3129 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3130 tp->snd_cwnd = tp->t_maxseg;
984263bc 3131 tp->t_flags |= TF_ACKNOW;
f23061d4 3132 tcp_output(tp);
91489f6b
JH
3133 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3134 tp->snd_nxt = old_snd_nxt;
3135 /* partial window deflation */
68947d12
ND
3136 if (ocwnd > acked)
3137 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3138 else
3139 tp->snd_cwnd = tp->t_maxseg;
91489f6b
JH
3140}
3141
3142/*
3143 * In contrast to the Slow-but-Steady NewReno variant,
3144 * we do not reset the retransmission timer for SACK retransmissions,
3145 * except when retransmitting snd_una.
3146 */
3147static void
3148tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3149{
3150 uint32_t pipe, seglen;
3151 tcp_seq nextrexmt;
3152 boolean_t lostdup;
3153 tcp_seq old_snd_nxt = tp->snd_nxt;
3154 u_long ocwnd = tp->snd_cwnd;
3155 int nseg = 0; /* consecutive new segments */
3156#define MAXBURST 4 /* limit burst of new packets on partial ack */
3157
3158 tp->t_rtttime = 0;
3159 pipe = tcp_sack_compute_pipe(tp);
3160 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3161 (!tcp_do_smartsack || nseg < MAXBURST) &&
3162 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3163 uint32_t sent;
3164 tcp_seq old_snd_max;
3165 int error;
3166
98cb2337
MD
3167 if (nextrexmt == tp->snd_max)
3168 ++nseg;
91489f6b
JH
3169 tp->snd_nxt = nextrexmt;
3170 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3171 old_snd_max = tp->snd_max;
3172 if (nextrexmt == tp->snd_una)
a48c5dd5 3173 tcp_callout_stop(tp, tp->tt_rexmt);
91489f6b
JH
3174 error = tcp_output(tp);
3175 if (error != 0)
3176 break;
3177 sent = tp->snd_nxt - nextrexmt;
3178 if (sent <= 0)
3179 break;
3180 if (!lostdup)
3181 pipe += sent;
3182 tcpstat.tcps_sndsackpack++;
3183 tcpstat.tcps_sndsackbyte += sent;
3184 if (SEQ_LT(nextrexmt, old_snd_max) &&
3185 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3186 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3187 }
3188 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3189 tp->snd_nxt = old_snd_nxt;
984263bc 3190 tp->snd_cwnd = ocwnd;
984263bc 3191}