kernel - Fix rare pmap_scan_callback() panic
[dragonfly.git] / sys / netinet / tcp_input.c
blobbe34ebeef0d39971dd0e6778cc6e716bb6180894
1 /*
2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
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.
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.
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
36 * The Regents of the University of California. All rights reserved.
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. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
62 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
63 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68 #include "opt_tcpdebug.h"
69 #include "opt_tcp_input.h"
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/proc.h> /* for proc0 declaration */
78 #include <sys/protosw.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/syslog.h>
82 #include <sys/in_cksum.h>
84 #include <sys/socketvar2.h>
86 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
87 #include <machine/stdarg.h>
89 #include <net/if.h>
90 #include <net/route.h>
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
96 #include <netinet/in_var.h>
97 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
98 #include <netinet/in_pcb.h>
99 #include <netinet/ip_var.h>
100 #include <netinet/ip6.h>
101 #include <netinet/icmp6.h>
102 #include <netinet6/nd6.h>
103 #include <netinet6/ip6_var.h>
104 #include <netinet6/in6_pcb.h>
105 #include <netinet/tcp.h>
106 #include <netinet/tcp_fsm.h>
107 #include <netinet/tcp_seq.h>
108 #include <netinet/tcp_timer.h>
109 #include <netinet/tcp_timer2.h>
110 #include <netinet/tcp_var.h>
111 #include <netinet6/tcp6_var.h>
112 #include <netinet/tcpip.h>
114 #ifdef TCPDEBUG
115 #include <netinet/tcp_debug.h>
117 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
118 struct tcphdr tcp_savetcp;
119 #endif
122 * Limit burst of new packets during SACK based fast recovery
123 * or extended limited transmit.
125 #define TCP_SACK_MAXBURST 4
127 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
129 static int log_in_vain = 0;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
131 &log_in_vain, 0, "Log all incoming TCP connections");
133 static int blackhole = 0;
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
135 &blackhole, 0, "Do not send RST when dropping refused connections");
137 int tcp_delack_enabled = 1;
138 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
139 &tcp_delack_enabled, 0,
140 "Delay ACK to try and piggyback it onto a data packet");
142 #ifdef TCP_DROP_SYNFIN
143 static int drop_synfin = 0;
144 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
145 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
146 #endif
148 static int tcp_do_limitedtransmit = 1;
149 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
150 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
152 static int tcp_do_early_retransmit = 1;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
154 &tcp_do_early_retransmit, 0, "Early retransmit");
156 int tcp_aggregate_acks = 1;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, aggregate_acks, CTLFLAG_RW,
158 &tcp_aggregate_acks, 0, "Aggregate built-up acks into one ack");
160 static int tcp_do_eifel_detect = 1;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
162 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
164 static int tcp_do_abc = 1;
165 SYSCTL_INT(_net_inet_tcp, OID_AUTO, abc, CTLFLAG_RW,
166 &tcp_do_abc, 0,
167 "TCP Appropriate Byte Counting (RFC 3465)");
170 * The following value actually takes range [25ms, 250ms],
171 * given that most modern systems use 1ms ~ 10ms as the unit
172 * of timestamp option.
174 static u_int tcp_paws_tolerance = 25;
175 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, paws_tolerance, CTLFLAG_RW,
176 &tcp_paws_tolerance, 0, "RFC1323 PAWS tolerance");
179 * Define as tunable for easy testing with SACK on and off.
180 * Warning: do not change setting in the middle of an existing active TCP flow,
181 * else strange things might happen to that flow.
183 int tcp_do_sack = 1;
184 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
185 &tcp_do_sack, 0, "Enable SACK Algorithms");
187 int tcp_do_smartsack = 1;
188 SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
189 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
191 int tcp_do_rescuesack = 1;
192 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rescuesack, CTLFLAG_RW,
193 &tcp_do_rescuesack, 0, "Rescue retransmission for SACK");
195 int tcp_aggressive_rescuesack = 0;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rescuesack_agg, CTLFLAG_RW,
197 &tcp_aggressive_rescuesack, 0, "Aggressive rescue retransmission for SACK");
199 static int tcp_force_sackrxt = 1;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, force_sackrxt, CTLFLAG_RW,
201 &tcp_force_sackrxt, 0, "Allowed forced SACK retransmit burst");
203 int tcp_do_rfc6675 = 1;
204 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675, CTLFLAG_RW,
205 &tcp_do_rfc6675, 0, "Enable RFC6675");
207 int tcp_rfc6675_rxt = 0;
208 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc6675_rxt, CTLFLAG_RW,
209 &tcp_rfc6675_rxt, 0, "Enable RFC6675 retransmit");
211 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
212 "TCP Segment Reassembly Queue");
214 int tcp_reass_maxseg = 0;
215 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
216 &tcp_reass_maxseg, 0,
217 "Global maximum number of TCP Segments in Reassembly Queue");
219 int tcp_reass_qsize = 0;
220 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
221 &tcp_reass_qsize, 0,
222 "Global number of TCP Segments currently in Reassembly Queue");
224 static int tcp_reass_overflows = 0;
225 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
226 &tcp_reass_overflows, 0,
227 "Global number of TCP Segment Reassembly Queue Overflows");
229 int tcp_do_autorcvbuf = 1;
230 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
231 &tcp_do_autorcvbuf, 0, "Enable automatic receive buffer sizing");
233 int tcp_autorcvbuf_inc = 16*1024;
234 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
235 &tcp_autorcvbuf_inc, 0,
236 "Incrementor step size of automatic receive buffer");
238 int tcp_autorcvbuf_max = 2*1024*1024;
239 SYSCTL_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
240 &tcp_autorcvbuf_max, 0, "Max size of automatic receive buffer");
242 int tcp_sosend_agglim = 2;
243 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_agglim, CTLFLAG_RW,
244 &tcp_sosend_agglim, 0, "TCP sosend mbuf aggregation limit");
246 int tcp_sosend_async = 1;
247 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_async, CTLFLAG_RW,
248 &tcp_sosend_async, 0, "TCP asynchronized pru_send");
250 int tcp_sosend_jcluster = 1;
251 SYSCTL_INT(_net_inet_tcp, OID_AUTO, sosend_jcluster, CTLFLAG_RW,
252 &tcp_sosend_jcluster, 0, "TCP output uses jcluster");
254 static int tcp_ignore_redun_dsack = 1;
255 SYSCTL_INT(_net_inet_tcp, OID_AUTO, ignore_redun_dsack, CTLFLAG_RW,
256 &tcp_ignore_redun_dsack, 0, "Ignore redundant DSACK");
258 static int tcp_reuseport_ext = 1;
259 SYSCTL_INT(_net_inet_tcp, OID_AUTO, reuseport_ext, CTLFLAG_RW,
260 &tcp_reuseport_ext, 0, "SO_REUSEPORT extension");
262 static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t,
263 tcp_seq);
264 static void tcp_pulloutofband(struct socket *,
265 struct tcphdr *, struct mbuf *, int);
266 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
267 struct mbuf *);
268 static void tcp_xmit_timer(struct tcpcb *, int, tcp_seq);
269 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
270 static void tcp_sack_rexmt(struct tcpcb *, boolean_t);
271 static boolean_t tcp_sack_limitedxmit(struct tcpcb *);
272 static int tcp_rmx_msl(const struct tcpcb *);
273 static void tcp_established(struct tcpcb *);
274 static boolean_t tcp_recv_dupack(struct tcpcb *, tcp_seq, u_int);
276 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
277 #ifdef INET6
278 #define ND6_HINT(tp) \
279 do { \
280 if ((tp) && (tp)->t_inpcb && \
281 INP_ISIPV6((tp)->t_inpcb) && \
282 (tp)->t_inpcb->in6p_route.ro_rt) \
283 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
284 } while (0)
285 #else
286 #define ND6_HINT(tp)
287 #endif
290 * Indicate whether this ack should be delayed. We can delay the ack if
291 * - delayed acks are enabled and
292 * - there is no delayed ack timer in progress and
293 * - our last ack wasn't a 0-sized window. We never want to delay
294 * the ack that opens up a 0-sized window.
296 #define DELAY_ACK(tp) \
297 (tcp_delack_enabled && !tcp_callout_pending(tp, tp->tt_delack) && \
298 !(tp->t_flags & TF_RXWIN0SENT))
300 #define acceptable_window_update(tp, th, tiwin) \
301 (SEQ_LT(tp->snd_wl1, th->th_seq) || \
302 (tp->snd_wl1 == th->th_seq && \
303 (SEQ_LT(tp->snd_wl2, th->th_ack) || \
304 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))
306 #define iceildiv(n, d) (((n)+(d)-1) / (d))
307 #define need_early_retransmit(tp, ownd) \
308 (tcp_do_early_retransmit && \
309 (tcp_do_eifel_detect && (tp->t_flags & TF_RCVD_TSTMP)) && \
310 ownd < ((tp->t_rxtthresh + 1) * tp->t_maxseg) && \
311 tp->t_dupacks + 1 >= iceildiv(ownd, tp->t_maxseg) && \
312 (!TCP_DO_SACK(tp) || ownd <= tp->t_maxseg || \
313 tcp_sack_has_sacked(&tp->scb, ownd - tp->t_maxseg)))
316 * Returns TRUE, if this segment can be merged with the last
317 * pending segment in the reassemble queue and this segment
318 * does not overlap with the pending segment immediately
319 * preceeding the last pending segment.
321 static __inline boolean_t
322 tcp_paws_canreasslast(const struct tcpcb *tp, const struct tcphdr *th, int tlen)
324 const struct tseg_qent *last, *prev;
326 last = TAILQ_LAST(&tp->t_segq, tsegqe_head);
327 if (last == NULL)
328 return FALSE;
330 /* This segment comes immediately after the last pending segment */
331 if (last->tqe_th->th_seq + last->tqe_len == th->th_seq) {
332 if (last->tqe_th->th_flags & TH_FIN) {
333 /* No segments should follow segment w/ FIN */
334 return FALSE;
336 return TRUE;
339 if (th->th_seq + tlen != last->tqe_th->th_seq)
340 return FALSE;
341 /* This segment comes immediately before the last pending segment */
343 prev = TAILQ_PREV(last, tsegqe_head, tqe_q);
344 if (prev == NULL) {
346 * No pending preceeding segment, we assume this segment
347 * could be reassembled.
349 return TRUE;
352 /* This segment does not overlap with the preceeding segment */
353 if (SEQ_GEQ(th->th_seq, prev->tqe_th->th_seq + prev->tqe_len))
354 return TRUE;
356 return FALSE;
359 static __inline void
360 tcp_ncr_update_rxtthresh(struct tcpcb *tp)
362 int old_rxtthresh = tp->t_rxtthresh;
363 uint32_t ownd = tp->snd_max - tp->snd_una;
365 tp->t_rxtthresh = min(tcp_ncr_rxtthresh_max,
366 max(tcprexmtthresh, ((ownd / tp->t_maxseg) >> 1)));
367 if (tp->t_rxtthresh != old_rxtthresh) {
368 tcp_sack_update_lostseq(&tp->scb, tp->snd_una,
369 tp->t_maxseg, tp->t_rxtthresh);
373 static int
374 tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
376 struct tseg_qent *q;
377 struct tseg_qent *p = NULL;
378 struct tseg_qent *te;
379 struct socket *so = tp->t_inpcb->inp_socket;
380 int flags;
383 * Call with th == NULL after become established to
384 * force pre-ESTABLISHED data up to user socket.
386 if (th == NULL)
387 goto present;
390 * Limit the number of segments in the reassembly queue to prevent
391 * holding on to too many segments (and thus running out of mbufs).
392 * Make sure to let the missing segment through which caused this
393 * queue. Always keep one global queue entry spare to be able to
394 * process the missing segment.
396 if (th->th_seq != tp->rcv_nxt &&
397 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
398 tcp_reass_overflows++;
399 tcpstat.tcps_rcvmemdrop++;
400 m_freem(m);
401 /* no SACK block to report */
402 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
403 return (0);
406 /* Allocate a new queue entry. */
407 te = kmalloc(sizeof(struct tseg_qent), M_TSEGQ, M_INTWAIT | M_NULLOK);
408 if (te == NULL) {
409 tcpstat.tcps_rcvmemdrop++;
410 m_freem(m);
411 /* no SACK block to report */
412 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
413 return (0);
415 atomic_add_int(&tcp_reass_qsize, 1);
417 if (th->th_flags & TH_FIN)
418 tp->t_flags |= TF_QUEDFIN;
421 * Find a segment which begins after this one does.
423 TAILQ_FOREACH(q, &tp->t_segq, tqe_q) {
424 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
425 break;
426 p = q;
430 * If there is a preceding segment, it may provide some of
431 * our data already. If so, drop the data from the incoming
432 * segment. If it provides all of our data, drop us.
434 if (p != NULL) {
435 tcp_seq_diff_t i;
437 /* conversion to int (in i) handles seq wraparound */
438 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
439 if (i > 0) { /* overlaps preceding segment */
440 tp->sack_flags |=
441 (TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG);
442 /* enclosing block starts w/ preceding segment */
443 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
444 if (i >= *tlenp) {
445 if (th->th_flags & TH_FIN)
446 p->tqe_th->th_flags |= TH_FIN;
448 /* preceding encloses incoming segment */
449 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
450 p->tqe_th->th_seq + p->tqe_len,
451 p->tqe_th->th_flags);
452 tcpstat.tcps_rcvduppack++;
453 tcpstat.tcps_rcvdupbyte += *tlenp;
454 m_freem(m);
455 kfree(te, M_TSEGQ);
456 atomic_add_int(&tcp_reass_qsize, -1);
458 * Try to present any queued data
459 * at the left window edge to the user.
460 * This is needed after the 3-WHS
461 * completes.
463 goto present; /* ??? */
465 m_adj(m, i);
466 *tlenp -= i;
467 th->th_seq += i;
468 /* incoming segment end is enclosing block end */
469 tp->encloseblk.rblk_end = TCP_SACK_BLKEND(
470 th->th_seq + *tlenp, th->th_flags);
471 /* trim end of reported D-SACK block */
472 tp->reportblk.rblk_end = th->th_seq;
475 tcpstat.tcps_rcvoopack++;
476 tcpstat.tcps_rcvoobyte += *tlenp;
479 * While we overlap succeeding segments trim them or,
480 * if they are completely covered, dequeue them.
482 while (q) {
483 tcp_seq_diff_t i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
484 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
485 tcp_seq qend_sack = TCP_SACK_BLKEND(qend, q->tqe_th->th_flags);
486 struct tseg_qent *nq;
488 if (i <= 0)
489 break;
490 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
491 /* first time through */
492 tp->sack_flags |= (TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG);
493 tp->encloseblk = tp->reportblk;
494 /* report trailing duplicate D-SACK segment */
495 tp->reportblk.rblk_start = q->tqe_th->th_seq;
497 if ((tp->sack_flags & TSACK_F_ENCLOSESEG) &&
498 SEQ_GT(qend_sack, tp->encloseblk.rblk_end)) {
499 /* extend enclosing block if one exists */
500 tp->encloseblk.rblk_end = qend_sack;
502 if (i < q->tqe_len) {
503 q->tqe_th->th_seq += i;
504 q->tqe_len -= i;
505 m_adj(q->tqe_m, i);
506 break;
509 if (q->tqe_th->th_flags & TH_FIN)
510 th->th_flags |= TH_FIN;
512 nq = TAILQ_NEXT(q, tqe_q);
513 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
514 m_freem(q->tqe_m);
515 kfree(q, M_TSEGQ);
516 atomic_add_int(&tcp_reass_qsize, -1);
517 q = nq;
520 /* Insert the new segment queue entry into place. */
521 te->tqe_m = m;
522 te->tqe_th = th;
523 te->tqe_len = *tlenp;
525 /* check if can coalesce with following segment */
526 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
527 tcp_seq tend_sack;
529 te->tqe_len += q->tqe_len;
530 if (q->tqe_th->th_flags & TH_FIN)
531 te->tqe_th->th_flags |= TH_FIN;
532 tend_sack = TCP_SACK_BLKEND(te->tqe_th->th_seq + te->tqe_len,
533 te->tqe_th->th_flags);
535 m_cat(te->tqe_m, q->tqe_m);
536 tp->encloseblk.rblk_end = tend_sack;
538 * When not reporting a duplicate segment, use
539 * the larger enclosing block as the SACK block.
541 if (!(tp->sack_flags & TSACK_F_DUPSEG))
542 tp->reportblk.rblk_end = tend_sack;
543 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
544 kfree(q, M_TSEGQ);
545 atomic_add_int(&tcp_reass_qsize, -1);
548 if (p == NULL) {
549 TAILQ_INSERT_HEAD(&tp->t_segq, te, tqe_q);
550 } else {
551 /* check if can coalesce with preceding segment */
552 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
553 if (te->tqe_th->th_flags & TH_FIN)
554 p->tqe_th->th_flags |= TH_FIN;
555 p->tqe_len += te->tqe_len;
556 m_cat(p->tqe_m, te->tqe_m);
557 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
559 * When not reporting a duplicate segment, use
560 * the larger enclosing block as the SACK block.
562 if (!(tp->sack_flags & TSACK_F_DUPSEG))
563 tp->reportblk.rblk_start = p->tqe_th->th_seq;
564 kfree(te, M_TSEGQ);
565 atomic_add_int(&tcp_reass_qsize, -1);
566 } else {
567 TAILQ_INSERT_AFTER(&tp->t_segq, p, te, tqe_q);
571 present:
573 * Present data to user, advancing rcv_nxt through
574 * completed sequence space.
576 if (!TCPS_HAVEESTABLISHED(tp->t_state))
577 return (0);
578 q = TAILQ_FIRST(&tp->t_segq);
579 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
580 return (0);
581 tp->rcv_nxt += q->tqe_len;
582 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
583 /* no SACK block to report since ACK advanced */
584 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
586 /* no enclosing block to report since ACK advanced */
587 tp->sack_flags &= ~TSACK_F_ENCLOSESEG;
588 flags = q->tqe_th->th_flags & TH_FIN;
589 TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
590 KASSERT(TAILQ_EMPTY(&tp->t_segq) ||
591 TAILQ_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
592 ("segment not coalesced"));
593 if (so->so_state & SS_CANTRCVMORE) {
594 m_freem(q->tqe_m);
595 } else {
596 lwkt_gettoken(&so->so_rcv.ssb_token);
597 ssb_appendstream(&so->so_rcv, q->tqe_m);
598 lwkt_reltoken(&so->so_rcv.ssb_token);
600 kfree(q, M_TSEGQ);
601 atomic_add_int(&tcp_reass_qsize, -1);
602 ND6_HINT(tp);
603 sorwakeup(so);
604 return (flags);
608 * TCP input routine, follows pages 65-76 of the
609 * protocol specification dated September, 1981 very closely.
611 #ifdef INET6
613 tcp6_input(struct mbuf **mp, int *offp, int proto)
615 struct mbuf *m = *mp;
616 struct in6_ifaddr *ia6;
618 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
621 * draft-itojun-ipv6-tcp-to-anycast
622 * better place to put this in?
624 ia6 = ip6_getdstifaddr(m);
625 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
626 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
627 offsetof(struct ip6_hdr, ip6_dst));
628 return (IPPROTO_DONE);
631 tcp_input(mp, offp, proto);
632 return (IPPROTO_DONE);
634 #endif
637 tcp_input(struct mbuf **mp, int *offp, int proto)
639 int off0;
640 struct tcphdr *th;
641 struct ip *ip = NULL;
642 struct ipovly *ipov;
643 struct inpcb *inp = NULL;
644 u_char *optp = NULL;
645 int optlen = 0;
646 int tlen, off;
647 int len = 0;
648 int drop_hdrlen;
649 struct tcpcb *tp = NULL;
650 int thflags;
651 struct socket *so = NULL;
652 int todrop, acked;
653 boolean_t ourfinisacked, needoutput = FALSE, delayed_dupack = FALSE;
654 tcp_seq th_dupack = 0; /* XXX gcc warning */
655 u_int to_flags = 0; /* XXX gcc warning */
656 u_long tiwin;
657 int recvwin;
658 struct tcpopt to; /* options in this segment */
659 struct sockaddr_in *next_hop = NULL;
660 int rstreason; /* For badport_bandlim accounting purposes */
661 int cpu;
662 struct ip6_hdr *ip6 = NULL;
663 struct mbuf *m;
664 #ifdef INET6
665 boolean_t isipv6;
666 #else
667 const boolean_t isipv6 = FALSE;
668 #endif
669 #ifdef TCPDEBUG
670 short ostate = 0;
671 #endif
673 off0 = *offp;
674 m = *mp;
675 *mp = NULL;
677 tcpstat.tcps_rcvtotal++;
679 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
680 struct m_tag *mtag;
682 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
683 KKASSERT(mtag != NULL);
684 next_hop = m_tag_data(mtag);
687 #ifdef INET6
688 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
689 #endif
691 if (isipv6) {
692 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
693 ip6 = mtod(m, struct ip6_hdr *);
694 tlen = (sizeof *ip6) + ntohs(ip6->ip6_plen) - off0;
695 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
696 tcpstat.tcps_rcvbadsum++;
697 goto drop;
699 th = (struct tcphdr *)((caddr_t)ip6 + off0);
702 * Be proactive about unspecified IPv6 address in source.
703 * As we use all-zero to indicate unbounded/unconnected pcb,
704 * unspecified IPv6 address can be used to confuse us.
706 * Note that packets with unspecified IPv6 destination is
707 * already dropped in ip6_input.
709 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
710 /* XXX stat */
711 goto drop;
713 } else {
715 * Get IP and TCP header together in first mbuf.
716 * Note: IP leaves IP header in first mbuf.
718 if (off0 > sizeof(struct ip)) {
719 ip_stripoptions(m);
720 off0 = sizeof(struct ip);
722 /* already checked and pulled up in ip_demux() */
723 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
724 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
725 ip = mtod(m, struct ip *);
726 ipov = (struct ipovly *)ip;
727 th = (struct tcphdr *)((caddr_t)ip + off0);
728 tlen = ip->ip_len;
730 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
731 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
732 th->th_sum = m->m_pkthdr.csum_data;
733 else
734 th->th_sum = in_pseudo(ip->ip_src.s_addr,
735 ip->ip_dst.s_addr,
736 htonl(m->m_pkthdr.csum_data +
737 ip->ip_len +
738 IPPROTO_TCP));
739 th->th_sum ^= 0xffff;
740 } else {
742 * Checksum extended TCP header and data.
744 len = sizeof(struct ip) + tlen;
745 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
746 ipov->ih_len = (u_short)tlen;
747 ipov->ih_len = htons(ipov->ih_len);
748 th->th_sum = in_cksum(m, len);
750 if (th->th_sum) {
751 tcpstat.tcps_rcvbadsum++;
752 goto drop;
754 #ifdef INET6
755 /* Re-initialization for later version check */
756 ip->ip_v = IPVERSION;
757 #endif
761 * Check that TCP offset makes sense,
762 * pull out TCP options and adjust length. XXX
764 off = th->th_off << 2;
765 /* already checked and pulled up in ip_demux() */
766 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
767 ("bad TCP data offset %d (tlen %d)", off, tlen));
768 tlen -= off; /* tlen is used instead of ti->ti_len */
769 if (off > sizeof(struct tcphdr)) {
770 if (isipv6) {
771 IP6_EXTHDR_CHECK(m, off0, off, IPPROTO_DONE);
772 ip6 = mtod(m, struct ip6_hdr *);
773 th = (struct tcphdr *)((caddr_t)ip6 + off0);
774 } else {
775 /* already pulled up in ip_demux() */
776 KASSERT(m->m_len >= sizeof(struct ip) + off,
777 ("TCP header and options not in one mbuf: "
778 "m_len %d, off %d", m->m_len, off));
780 optlen = off - sizeof(struct tcphdr);
781 optp = (u_char *)(th + 1);
783 thflags = th->th_flags;
785 #ifdef TCP_DROP_SYNFIN
787 * If the drop_synfin option is enabled, drop all packets with
788 * both the SYN and FIN bits set. This prevents e.g. nmap from
789 * identifying the TCP/IP stack.
791 * This is a violation of the TCP specification.
793 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
794 goto drop;
795 #endif
798 * Convert TCP protocol specific fields to host format.
800 th->th_seq = ntohl(th->th_seq);
801 th->th_ack = ntohl(th->th_ack);
802 th->th_win = ntohs(th->th_win);
803 th->th_urp = ntohs(th->th_urp);
806 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
807 * until after ip6_savecontrol() is called and before other functions
808 * which don't want those proto headers.
809 * Because ip6_savecontrol() is going to parse the mbuf to
810 * search for data to be passed up to user-land, it wants mbuf
811 * parameters to be unchanged.
812 * XXX: the call of ip6_savecontrol() has been obsoleted based on
813 * latest version of the advanced API (20020110).
815 drop_hdrlen = off0 + off;
818 * Locate pcb for segment.
820 findpcb:
821 /* IPFIREWALL_FORWARD section */
822 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
824 * Transparently forwarded. Pretend to be the destination.
825 * already got one like this?
827 cpu = mycpu->gd_cpuid;
828 inp = in_pcblookup_hash(&tcbinfo[cpu],
829 ip->ip_src, th->th_sport,
830 ip->ip_dst, th->th_dport,
831 0, m->m_pkthdr.rcvif);
832 if (!inp) {
834 * It's new. Try to find the ambushing socket.
838 * The rest of the ipfw code stores the port in
839 * host order. XXX
840 * (The IP address is still in network order.)
842 in_port_t dport = next_hop->sin_port ?
843 htons(next_hop->sin_port) :
844 th->th_dport;
846 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
847 next_hop->sin_addr.s_addr, dport);
848 inp = in_pcblookup_hash(&tcbinfo[cpu],
849 ip->ip_src, th->th_sport,
850 next_hop->sin_addr, dport,
851 1, m->m_pkthdr.rcvif);
853 } else {
854 if (isipv6) {
855 inp = in6_pcblookup_hash(&tcbinfo[0],
856 &ip6->ip6_src, th->th_sport,
857 &ip6->ip6_dst, th->th_dport,
858 1, m->m_pkthdr.rcvif);
859 } else {
860 cpu = mycpu->gd_cpuid;
861 inp = in_pcblookup_pkthash(&tcbinfo[cpu],
862 ip->ip_src, th->th_sport,
863 ip->ip_dst, th->th_dport,
864 1, m->m_pkthdr.rcvif,
865 tcp_reuseport_ext ? m : NULL);
870 * If the state is CLOSED (i.e., TCB does not exist) then
871 * all data in the incoming segment is discarded.
872 * If the TCB exists but is in CLOSED state, it is embryonic,
873 * but should either do a listen or a connect soon.
875 if (inp == NULL) {
876 if (log_in_vain) {
877 #ifdef INET6
878 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
879 #else
880 char dbuf[INET_ADDRSTRLEN], sbuf[INET_ADDRSTRLEN];
881 #endif
882 if (isipv6) {
883 strcpy(dbuf, "[");
884 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
885 strcat(dbuf, "]");
886 strcpy(sbuf, "[");
887 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
888 strcat(sbuf, "]");
889 } else {
890 kinet_ntoa(ip->ip_dst, dbuf);
891 kinet_ntoa(ip->ip_src, sbuf);
893 switch (log_in_vain) {
894 case 1:
895 if (!(thflags & TH_SYN))
896 break;
897 case 2:
898 log(LOG_INFO,
899 "Connection attempt to TCP %s:%d "
900 "from %s:%d flags:0x%02x\n",
901 dbuf, ntohs(th->th_dport), sbuf,
902 ntohs(th->th_sport), thflags);
903 break;
904 default:
905 break;
908 if (blackhole) {
909 switch (blackhole) {
910 case 1:
911 if (thflags & TH_SYN)
912 goto drop;
913 break;
914 case 2:
915 goto drop;
916 default:
917 goto drop;
920 rstreason = BANDLIM_RST_CLOSEDPORT;
921 goto dropwithreset;
924 /* Check the minimum TTL for socket. */
925 #ifdef INET6
926 if ((isipv6 ? ip6->ip6_hlim : ip->ip_ttl) < inp->inp_ip_minttl)
927 goto drop;
928 #endif
930 tp = intotcpcb(inp);
931 KASSERT(tp != NULL, ("tcp_input: tp is NULL"));
932 if (tp->t_state <= TCPS_CLOSED)
933 goto drop;
935 so = inp->inp_socket;
937 #ifdef TCPDEBUG
938 if (so->so_options & SO_DEBUG) {
939 ostate = tp->t_state;
940 if (isipv6)
941 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
942 else
943 bcopy(ip, tcp_saveipgen, sizeof(*ip));
944 tcp_savetcp = *th;
946 #endif
948 bzero(&to, sizeof to);
950 if (so->so_options & SO_ACCEPTCONN) {
951 struct in_conninfo inc;
953 #ifdef INET6
954 inc.inc_isipv6 = (isipv6 == TRUE);
955 #endif
956 if (isipv6) {
957 inc.inc6_faddr = ip6->ip6_src;
958 inc.inc6_laddr = ip6->ip6_dst;
959 inc.inc6_route.ro_rt = NULL; /* XXX */
960 } else {
961 inc.inc_faddr = ip->ip_src;
962 inc.inc_laddr = ip->ip_dst;
963 inc.inc_route.ro_rt = NULL; /* XXX */
965 inc.inc_fport = th->th_sport;
966 inc.inc_lport = th->th_dport;
969 * If the state is LISTEN then ignore segment if it contains
970 * a RST. If the segment contains an ACK then it is bad and
971 * send a RST. If it does not contain a SYN then it is not
972 * interesting; drop it.
974 * If the state is SYN_RECEIVED (syncache) and seg contains
975 * an ACK, but not for our SYN/ACK, send a RST. If the seg
976 * contains a RST, check the sequence number to see if it
977 * is a valid reset segment.
979 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
980 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
981 if (!syncache_expand(&inc, th, &so, m)) {
983 * No syncache entry, or ACK was not
984 * for our SYN/ACK. Send a RST.
986 tcpstat.tcps_badsyn++;
987 rstreason = BANDLIM_RST_OPENPORT;
988 goto dropwithreset;
992 * Could not complete 3-way handshake,
993 * connection is being closed down, and
994 * syncache will free mbuf.
996 if (so == NULL)
997 return(IPPROTO_DONE);
1000 * We must be in the correct protocol thread
1001 * for this connection.
1003 KKASSERT(so->so_port == &curthread->td_msgport);
1006 * Socket is created in state SYN_RECEIVED.
1007 * Continue processing segment.
1009 inp = so->so_pcb;
1010 tp = intotcpcb(inp);
1012 * This is what would have happened in
1013 * tcp_output() when the SYN,ACK was sent.
1015 tp->snd_up = tp->snd_una;
1016 tp->snd_max = tp->snd_nxt = tp->iss + 1;
1017 tp->last_ack_sent = tp->rcv_nxt;
1019 goto after_listen;
1021 if (thflags & TH_RST) {
1022 syncache_chkrst(&inc, th);
1023 goto drop;
1025 if (thflags & TH_ACK) {
1026 syncache_badack(&inc);
1027 tcpstat.tcps_badsyn++;
1028 rstreason = BANDLIM_RST_OPENPORT;
1029 goto dropwithreset;
1031 goto drop;
1035 * Segment's flags are (SYN) or (SYN | FIN).
1037 #ifdef INET6
1039 * If deprecated address is forbidden,
1040 * we do not accept SYN to deprecated interface
1041 * address to prevent any new inbound connection from
1042 * getting established.
1043 * When we do not accept SYN, we send a TCP RST,
1044 * with deprecated source address (instead of dropping
1045 * it). We compromise it as it is much better for peer
1046 * to send a RST, and RST will be the final packet
1047 * for the exchange.
1049 * If we do not forbid deprecated addresses, we accept
1050 * the SYN packet. RFC2462 does not suggest dropping
1051 * SYN in this case.
1052 * If we decipher RFC2462 5.5.4, it says like this:
1053 * 1. use of deprecated addr with existing
1054 * communication is okay - "SHOULD continue to be
1055 * used"
1056 * 2. use of it with new communication:
1057 * (2a) "SHOULD NOT be used if alternate address
1058 * with sufficient scope is available"
1059 * (2b) nothing mentioned otherwise.
1060 * Here we fall into (2b) case as we have no choice in
1061 * our source address selection - we must obey the peer.
1063 * The wording in RFC2462 is confusing, and there are
1064 * multiple description text for deprecated address
1065 * handling - worse, they are not exactly the same.
1066 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1068 if (isipv6 && !ip6_use_deprecated) {
1069 struct in6_ifaddr *ia6;
1071 if ((ia6 = ip6_getdstifaddr(m)) &&
1072 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1073 tp = NULL;
1074 rstreason = BANDLIM_RST_OPENPORT;
1075 goto dropwithreset;
1078 #endif
1080 * If it is from this socket, drop it, it must be forged.
1081 * Don't bother responding if the destination was a broadcast.
1083 if (th->th_dport == th->th_sport) {
1084 if (isipv6) {
1085 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1086 &ip6->ip6_src))
1087 goto drop;
1088 } else {
1089 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1090 goto drop;
1094 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1096 * Note that it is quite possible to receive unicast
1097 * link-layer packets with a broadcast IP address. Use
1098 * in_broadcast() to find them.
1100 if (m->m_flags & (M_BCAST | M_MCAST))
1101 goto drop;
1102 if (isipv6) {
1103 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1104 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1105 goto drop;
1106 } else {
1107 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1108 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1109 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1110 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1111 goto drop;
1114 * SYN appears to be valid; create compressed TCP state
1115 * for syncache.
1117 if (so->so_qlen <= so->so_qlimit) {
1118 tcp_dooptions(&to, optp, optlen, TRUE, th->th_ack);
1119 if (!syncache_add(&inc, &to, th, so, m))
1120 goto drop;
1123 * Entry added to syncache, mbuf used to
1124 * send SYN,ACK packet.
1126 return(IPPROTO_DONE);
1128 goto drop;
1131 after_listen:
1133 * Should not happen - syncache should pick up these connections.
1135 * Once we are past handling listen sockets we must be in the
1136 * correct protocol processing thread.
1138 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
1139 KKASSERT(so->so_port == &curthread->td_msgport);
1141 /* Unscale the window into a 32-bit value. */
1142 if (!(thflags & TH_SYN))
1143 tiwin = th->th_win << tp->snd_scale;
1144 else
1145 tiwin = th->th_win;
1148 * This is the second part of the MSS DoS prevention code (after
1149 * minmss on the sending side) and it deals with too many too small
1150 * tcp packets in a too short timeframe (1 second).
1152 * XXX Removed. This code was crap. It does not scale to network
1153 * speed, and default values break NFS. Gone.
1155 /* REMOVED */
1158 * Segment received on connection.
1160 * Reset idle time and keep-alive timer. Don't waste time if less
1161 * then a second has elapsed.
1163 if ((int)(ticks - tp->t_rcvtime) > hz)
1164 tcp_timer_keep_activity(tp, thflags);
1167 * Process options.
1168 * XXX this is tradtitional behavior, may need to be cleaned up.
1170 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0, th->th_ack);
1171 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1172 if ((to.to_flags & TOF_SCALE) && (tp->t_flags & TF_REQ_SCALE)) {
1173 tp->t_flags |= TF_RCVD_SCALE;
1174 tp->snd_scale = to.to_requested_s_scale;
1178 * Initial send window; will be updated upon next ACK
1180 tp->snd_wnd = th->th_win;
1182 if (to.to_flags & TOF_TS) {
1183 tp->t_flags |= TF_RCVD_TSTMP;
1184 tp->ts_recent = to.to_tsval;
1185 tp->ts_recent_age = ticks;
1187 if (!(to.to_flags & TOF_MSS))
1188 to.to_mss = 0;
1189 tcp_rmx_init(tp, to.to_mss);
1191 * Only set the TF_SACK_PERMITTED per-connection flag
1192 * if we got a SACK_PERMITTED option from the other side
1193 * and the global tcp_do_sack variable is true.
1195 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1196 tp->t_flags |= TF_SACK_PERMITTED;
1200 * Header prediction: check for the two common cases
1201 * of a uni-directional data xfer. If the packet has
1202 * no control flags, is in-sequence, the window didn't
1203 * change and we're not retransmitting, it's a
1204 * candidate. If the length is zero and the ack moved
1205 * forward, we're the sender side of the xfer. Just
1206 * free the data acked & wake any higher level process
1207 * that was blocked waiting for space. If the length
1208 * is non-zero and the ack didn't move, we're the
1209 * receiver side. If we're getting packets in-order
1210 * (the reassembly queue is empty), add the data to
1211 * the socket buffer and note that we need a delayed ack.
1212 * Make sure that the hidden state-flags are also off.
1213 * Since we check for TCPS_ESTABLISHED above, it can only
1214 * be TH_NEEDSYN.
1216 if (tp->t_state == TCPS_ESTABLISHED &&
1217 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1218 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1219 (!(to.to_flags & TOF_TS) ||
1220 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1221 th->th_seq == tp->rcv_nxt &&
1222 tp->snd_nxt == tp->snd_max) {
1225 * If last ACK falls within this segment's sequence numbers,
1226 * record the timestamp.
1227 * NOTE that the test is modified according to the latest
1228 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1230 if ((to.to_flags & TOF_TS) &&
1231 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1232 tp->ts_recent_age = ticks;
1233 tp->ts_recent = to.to_tsval;
1236 if (tlen == 0) {
1237 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1238 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1239 tp->snd_cwnd >= tp->snd_wnd &&
1240 !IN_FASTRECOVERY(tp)) {
1242 * This is a pure ack for outstanding data.
1244 ++tcpstat.tcps_predack;
1246 * "bad retransmit" recovery
1248 * If Eifel detection applies, then
1249 * it is deterministic, so use it
1250 * unconditionally over the old heuristic.
1251 * Otherwise, fall back to the old heuristic.
1253 if (tcp_do_eifel_detect &&
1254 (to.to_flags & TOF_TS) && to.to_tsecr &&
1255 (tp->rxt_flags & TRXT_F_FIRSTACCACK)) {
1256 /* Eifel detection applicable. */
1257 if (to.to_tsecr < tp->t_rexmtTS) {
1258 tcp_revert_congestion_state(tp);
1259 ++tcpstat.tcps_eifeldetected;
1260 if (tp->t_rxtshift != 1 ||
1261 ticks >= tp->t_badrxtwin)
1262 ++tcpstat.tcps_rttcantdetect;
1264 } else if (tp->t_rxtshift == 1 &&
1265 ticks < tp->t_badrxtwin) {
1266 tcp_revert_congestion_state(tp);
1267 ++tcpstat.tcps_rttdetected;
1269 tp->rxt_flags &= ~(TRXT_F_FIRSTACCACK |
1270 TRXT_F_FASTREXMT | TRXT_F_EARLYREXMT);
1272 * Recalculate the retransmit timer / rtt.
1274 * Some machines (certain windows boxes)
1275 * send broken timestamp replies during the
1276 * SYN+ACK phase, ignore timestamps of 0.
1278 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
1279 tcp_xmit_timer(tp,
1280 ticks - to.to_tsecr + 1,
1281 th->th_ack);
1282 } else if (tp->t_rtttime &&
1283 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1284 tcp_xmit_timer(tp,
1285 ticks - tp->t_rtttime + 1,
1286 th->th_ack);
1288 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1289 acked = th->th_ack - tp->snd_una;
1290 tcpstat.tcps_rcvackpack++;
1291 tcpstat.tcps_rcvackbyte += acked;
1292 sbdrop(&so->so_snd.sb, acked);
1293 tp->snd_recover = th->th_ack - 1;
1294 tp->snd_una = th->th_ack;
1295 tp->t_dupacks = 0;
1297 * Update window information.
1299 if (tiwin != tp->snd_wnd &&
1300 acceptable_window_update(tp, th, tiwin)) {
1301 /* keep track of pure window updates */
1302 if (tp->snd_wl2 == th->th_ack &&
1303 tiwin > tp->snd_wnd)
1304 tcpstat.tcps_rcvwinupd++;
1305 tp->snd_wnd = tiwin;
1306 tp->snd_wl1 = th->th_seq;
1307 tp->snd_wl2 = th->th_ack;
1308 if (tp->snd_wnd > tp->max_sndwnd)
1309 tp->max_sndwnd = tp->snd_wnd;
1311 m_freem(m);
1312 ND6_HINT(tp); /* some progress has been done */
1314 * If all outstanding data are acked, stop
1315 * retransmit timer, otherwise restart timer
1316 * using current (possibly backed-off) value.
1317 * If process is waiting for space,
1318 * wakeup/selwakeup/signal. If data
1319 * are ready to send, let tcp_output
1320 * decide between more output or persist.
1322 if (tp->snd_una == tp->snd_max) {
1323 tcp_callout_stop(tp, tp->tt_rexmt);
1324 } else if (!tcp_callout_active(tp,
1325 tp->tt_persist)) {
1326 tcp_callout_reset(tp, tp->tt_rexmt,
1327 tp->t_rxtcur, tcp_timer_rexmt);
1329 sowwakeup(so);
1330 if (so->so_snd.ssb_cc > 0 &&
1331 !tcp_output_pending(tp))
1332 tcp_output_fair(tp);
1333 return(IPPROTO_DONE);
1335 } else if (tiwin == tp->snd_wnd &&
1336 th->th_ack == tp->snd_una &&
1337 TAILQ_EMPTY(&tp->t_segq) &&
1338 tlen <= ssb_space(&so->so_rcv)) {
1339 u_long newsize = 0; /* automatic sockbuf scaling */
1341 * This is a pure, in-sequence data packet
1342 * with nothing on the reassembly queue and
1343 * we have enough buffer space to take it.
1345 ++tcpstat.tcps_preddat;
1346 tp->rcv_nxt += tlen;
1347 tcpstat.tcps_rcvpack++;
1348 tcpstat.tcps_rcvbyte += tlen;
1349 ND6_HINT(tp); /* some progress has been done */
1351 * Automatic sizing of receive socket buffer. Often the send
1352 * buffer size is not optimally adjusted to the actual network
1353 * conditions at hand (delay bandwidth product). Setting the
1354 * buffer size too small limits throughput on links with high
1355 * bandwidth and high delay (eg. trans-continental/oceanic links).
1357 * On the receive side the socket buffer memory is only rarely
1358 * used to any significant extent. This allows us to be much
1359 * more aggressive in scaling the receive socket buffer. For
1360 * the case that the buffer space is actually used to a large
1361 * extent and we run out of kernel memory we can simply drop
1362 * the new segments; TCP on the sender will just retransmit it
1363 * later. Setting the buffer size too big may only consume too
1364 * much kernel memory if the application doesn't read() from
1365 * the socket or packet loss or reordering makes use of the
1366 * reassembly queue.
1368 * The criteria to step up the receive buffer one notch are:
1369 * 1. the number of bytes received during the time it takes
1370 * one timestamp to be reflected back to us (the RTT);
1371 * 2. received bytes per RTT is within seven eighth of the
1372 * current socket buffer size;
1373 * 3. receive buffer size has not hit maximal automatic size;
1375 * This algorithm does one step per RTT at most and only if
1376 * we receive a bulk stream w/o packet losses or reorderings.
1377 * Shrinking the buffer during idle times is not necessary as
1378 * it doesn't consume any memory when idle.
1380 * TODO: Only step up if the application is actually serving
1381 * the buffer to better manage the socket buffer resources.
1383 if (tcp_do_autorcvbuf &&
1384 to.to_tsecr &&
1385 (so->so_rcv.ssb_flags & SSB_AUTOSIZE)) {
1386 if (to.to_tsecr > tp->rfbuf_ts &&
1387 to.to_tsecr - tp->rfbuf_ts < hz) {
1388 if (tp->rfbuf_cnt >
1389 (so->so_rcv.ssb_hiwat / 8 * 7) &&
1390 so->so_rcv.ssb_hiwat <
1391 tcp_autorcvbuf_max) {
1392 newsize =
1393 ulmin(so->so_rcv.ssb_hiwat +
1394 tcp_autorcvbuf_inc,
1395 tcp_autorcvbuf_max);
1397 /* Start over with next RTT. */
1398 tp->rfbuf_ts = 0;
1399 tp->rfbuf_cnt = 0;
1400 } else
1401 tp->rfbuf_cnt += tlen; /* add up */
1404 * Add data to socket buffer.
1406 if (so->so_state & SS_CANTRCVMORE) {
1407 m_freem(m);
1408 } else {
1410 * Set new socket buffer size, give up when
1411 * limit is reached.
1413 * Adjusting the size can mess up ACK
1414 * sequencing when pure window updates are
1415 * being avoided (which is the default),
1416 * so force an ack.
1418 lwkt_gettoken(&so->so_rcv.ssb_token);
1419 if (newsize) {
1420 tp->t_flags |= TF_RXRESIZED;
1421 if (!ssb_reserve(&so->so_rcv, newsize,
1422 so, NULL)) {
1423 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1425 if (newsize >=
1426 (TCP_MAXWIN << tp->rcv_scale)) {
1427 atomic_clear_int(&so->so_rcv.ssb_flags, SSB_AUTOSIZE);
1430 m_adj(m, drop_hdrlen); /* delayed header drop */
1431 ssb_appendstream(&so->so_rcv, m);
1432 lwkt_reltoken(&so->so_rcv.ssb_token);
1434 sorwakeup(so);
1436 * This code is responsible for most of the ACKs
1437 * the TCP stack sends back after receiving a data
1438 * packet. Note that the DELAY_ACK check fails if
1439 * the delack timer is already running, which results
1440 * in an ack being sent every other packet (which is
1441 * what we want).
1443 * We then further aggregate acks by not actually
1444 * sending one until the protocol thread has completed
1445 * processing the current backlog of packets. This
1446 * does not delay the ack any further, but allows us
1447 * to take advantage of the packet aggregation that
1448 * high speed NICs do (usually blocks of 8-10 packets)
1449 * to send a single ack rather then four or five acks,
1450 * greatly reducing the ack rate, the return channel
1451 * bandwidth, and the protocol overhead on both ends.
1453 * Since this also has the effect of slowing down
1454 * the exponential slow-start ramp-up, systems with
1455 * very large bandwidth-delay products might want
1456 * to turn the feature off.
1458 if (DELAY_ACK(tp)) {
1459 tcp_callout_reset(tp, tp->tt_delack,
1460 tcp_delacktime, tcp_timer_delack);
1461 } else if (tcp_aggregate_acks) {
1462 tp->t_flags |= TF_ACKNOW;
1463 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
1464 tp->t_flags |= TF_ONOUTPUTQ;
1465 tp->tt_cpu = mycpu->gd_cpuid;
1466 TAILQ_INSERT_TAIL(
1467 &tcpcbackq[tp->tt_cpu].head,
1468 tp, t_outputq);
1470 } else {
1471 tp->t_flags |= TF_ACKNOW;
1472 tcp_output(tp);
1474 return(IPPROTO_DONE);
1479 * Calculate amount of space in receive window,
1480 * and then do TCP input processing.
1481 * Receive window is amount of space in rcv queue,
1482 * but not less than advertised window.
1484 recvwin = ssb_space(&so->so_rcv);
1485 if (recvwin < 0)
1486 recvwin = 0;
1487 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
1489 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1490 tp->rfbuf_ts = 0;
1491 tp->rfbuf_cnt = 0;
1493 switch (tp->t_state) {
1495 * If the state is SYN_RECEIVED:
1496 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1498 case TCPS_SYN_RECEIVED:
1499 if ((thflags & TH_ACK) &&
1500 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1501 SEQ_GT(th->th_ack, tp->snd_max))) {
1502 rstreason = BANDLIM_RST_OPENPORT;
1503 goto dropwithreset;
1505 break;
1508 * If the state is SYN_SENT:
1509 * if seg contains an ACK, but not for our SYN, drop the input.
1510 * if seg contains a RST, then drop the connection.
1511 * if seg does not contain SYN, then drop it.
1512 * Otherwise this is an acceptable SYN segment
1513 * initialize tp->rcv_nxt and tp->irs
1514 * if seg contains ack then advance tp->snd_una
1515 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1516 * arrange for segment to be acked (eventually)
1517 * continue processing rest of data/controls, beginning with URG
1519 case TCPS_SYN_SENT:
1520 if ((thflags & TH_ACK) &&
1521 (SEQ_LEQ(th->th_ack, tp->iss) ||
1522 SEQ_GT(th->th_ack, tp->snd_max))) {
1523 rstreason = BANDLIM_UNLIMITED;
1524 goto dropwithreset;
1526 if (thflags & TH_RST) {
1527 if (thflags & TH_ACK)
1528 tp = tcp_drop(tp, ECONNREFUSED);
1529 goto drop;
1531 if (!(thflags & TH_SYN))
1532 goto drop;
1534 tp->irs = th->th_seq;
1535 tcp_rcvseqinit(tp);
1536 if (thflags & TH_ACK) {
1537 /* Our SYN was acked. */
1538 tcpstat.tcps_connects++;
1539 soisconnected(so);
1540 /* Do window scaling on this connection? */
1541 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1542 (TF_RCVD_SCALE | TF_REQ_SCALE))
1543 tp->rcv_scale = tp->request_r_scale;
1544 tp->rcv_adv += tp->rcv_wnd;
1545 tp->snd_una++; /* SYN is acked */
1546 tcp_callout_stop(tp, tp->tt_rexmt);
1548 * If there's data, delay ACK; if there's also a FIN
1549 * ACKNOW will be turned on later.
1551 if (DELAY_ACK(tp) && tlen != 0) {
1552 tcp_callout_reset(tp, tp->tt_delack,
1553 tcp_delacktime, tcp_timer_delack);
1554 } else {
1555 tp->t_flags |= TF_ACKNOW;
1558 * Received <SYN,ACK> in SYN_SENT[*] state.
1559 * Transitions:
1560 * SYN_SENT --> ESTABLISHED
1561 * SYN_SENT* --> FIN_WAIT_1
1563 tp->t_starttime = ticks;
1564 if (tp->t_flags & TF_NEEDFIN) {
1565 TCP_STATE_CHANGE(tp, TCPS_FIN_WAIT_1);
1566 tp->t_flags &= ~TF_NEEDFIN;
1567 thflags &= ~TH_SYN;
1568 } else {
1569 tcp_established(tp);
1571 } else {
1573 * Received initial SYN in SYN-SENT[*] state =>
1574 * simultaneous open.
1575 * Do 3-way handshake:
1576 * SYN-SENT -> SYN-RECEIVED
1577 * SYN-SENT* -> SYN-RECEIVED*
1579 tp->t_flags |= TF_ACKNOW;
1580 tcp_callout_stop(tp, tp->tt_rexmt);
1581 TCP_STATE_CHANGE(tp, TCPS_SYN_RECEIVED);
1585 * Advance th->th_seq to correspond to first data byte.
1586 * If data, trim to stay within window,
1587 * dropping FIN if necessary.
1589 th->th_seq++;
1590 if (tlen > tp->rcv_wnd) {
1591 todrop = tlen - tp->rcv_wnd;
1592 m_adj(m, -todrop);
1593 tlen = tp->rcv_wnd;
1594 thflags &= ~TH_FIN;
1595 tcpstat.tcps_rcvpackafterwin++;
1596 tcpstat.tcps_rcvbyteafterwin += todrop;
1598 tp->snd_wl1 = th->th_seq - 1;
1599 tp->rcv_up = th->th_seq;
1601 * Client side of transaction: already sent SYN and data.
1602 * If the remote host used T/TCP to validate the SYN,
1603 * our data will be ACK'd; if so, enter normal data segment
1604 * processing in the middle of step 5, ack processing.
1605 * Otherwise, goto step 6.
1607 if (thflags & TH_ACK)
1608 goto process_ACK;
1610 goto step6;
1613 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1614 * do normal processing (we no longer bother with T/TCP).
1616 case TCPS_LAST_ACK:
1617 case TCPS_CLOSING:
1618 case TCPS_TIME_WAIT:
1619 break; /* continue normal processing */
1623 * States other than LISTEN or SYN_SENT.
1624 * First check the RST flag and sequence number since reset segments
1625 * are exempt from the timestamp and connection count tests. This
1626 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1627 * below which allowed reset segments in half the sequence space
1628 * to fall though and be processed (which gives forged reset
1629 * segments with a random sequence number a 50 percent chance of
1630 * killing a connection).
1631 * Then check timestamp, if present.
1632 * Then check the connection count, if present.
1633 * Then check that at least some bytes of segment are within
1634 * receive window. If segment begins before rcv_nxt,
1635 * drop leading data (and SYN); if nothing left, just ack.
1638 * If the RST bit is set, check the sequence number to see
1639 * if this is a valid reset segment.
1640 * RFC 793 page 37:
1641 * In all states except SYN-SENT, all reset (RST) segments
1642 * are validated by checking their SEQ-fields. A reset is
1643 * valid if its sequence number is in the window.
1644 * Note: this does not take into account delayed ACKs, so
1645 * we should test against last_ack_sent instead of rcv_nxt.
1646 * The sequence number in the reset segment is normally an
1647 * echo of our outgoing acknowledgement numbers, but some hosts
1648 * send a reset with the sequence number at the rightmost edge
1649 * of our receive window, and we have to handle this case.
1650 * If we have multiple segments in flight, the intial reset
1651 * segment sequence numbers will be to the left of last_ack_sent,
1652 * but they will eventually catch up.
1653 * In any case, it never made sense to trim reset segments to
1654 * fit the receive window since RFC 1122 says:
1655 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1657 * A TCP SHOULD allow a received RST segment to include data.
1659 * DISCUSSION
1660 * It has been suggested that a RST segment could contain
1661 * ASCII text that encoded and explained the cause of the
1662 * RST. No standard has yet been established for such
1663 * data.
1665 * If the reset segment passes the sequence number test examine
1666 * the state:
1667 * SYN_RECEIVED STATE:
1668 * If passive open, return to LISTEN state.
1669 * If active open, inform user that connection was refused.
1670 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1671 * Inform user that connection was reset, and close tcb.
1672 * CLOSING, LAST_ACK STATES:
1673 * Close the tcb.
1674 * TIME_WAIT STATE:
1675 * Drop the segment - see Stevens, vol. 2, p. 964 and
1676 * RFC 1337.
1678 if (thflags & TH_RST) {
1679 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1680 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1681 switch (tp->t_state) {
1683 case TCPS_SYN_RECEIVED:
1684 so->so_error = ECONNREFUSED;
1685 goto close;
1687 case TCPS_ESTABLISHED:
1688 case TCPS_FIN_WAIT_1:
1689 case TCPS_FIN_WAIT_2:
1690 case TCPS_CLOSE_WAIT:
1691 so->so_error = ECONNRESET;
1692 close:
1693 TCP_STATE_CHANGE(tp, TCPS_CLOSED);
1694 tcpstat.tcps_drops++;
1695 tp = tcp_close(tp);
1696 break;
1698 case TCPS_CLOSING:
1699 case TCPS_LAST_ACK:
1700 tp = tcp_close(tp);
1701 break;
1703 case TCPS_TIME_WAIT:
1704 break;
1707 goto drop;
1711 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1712 * and it's less than ts_recent, drop it.
1714 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
1715 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1716 /* Check to see if ts_recent is over 24 days old. */
1717 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1719 * Invalidate ts_recent. If this segment updates
1720 * ts_recent, the age will be reset later and ts_recent
1721 * will get a valid value. If it does not, setting
1722 * ts_recent to zero will at least satisfy the
1723 * requirement that zero be placed in the timestamp
1724 * echo reply when ts_recent isn't valid. The
1725 * age isn't reset until we get a valid ts_recent
1726 * because we don't want out-of-order segments to be
1727 * dropped when ts_recent is old.
1729 tp->ts_recent = 0;
1730 } else if (tcp_paws_tolerance && tlen != 0 &&
1731 tp->t_state == TCPS_ESTABLISHED &&
1732 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK&&
1733 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1734 th->th_ack == tp->snd_una &&
1735 tiwin == tp->snd_wnd &&
1736 TSTMP_GEQ(to.to_tsval + tcp_paws_tolerance, tp->ts_recent)&&
1737 (th->th_seq == tp->rcv_nxt ||
1738 (SEQ_GT(th->th_seq, tp->rcv_nxt) &&
1739 tcp_paws_canreasslast(tp, th, tlen)))) {
1741 * This tends to prevent valid new segments from being
1742 * dropped by the reordered segments sent by the fast
1743 * retransmission algorithm on the sending side, i.e.
1744 * the fast retransmitted segment w/ larger timestamp
1745 * arrives earlier than the previously sent new segments
1746 * w/ smaller timestamp.
1748 * If following conditions are met, the segment is
1749 * accepted:
1750 * - The segment contains data
1751 * - The connection is established
1752 * - The header does not contain important flags
1753 * - SYN or FIN is not needed
1754 * - It does not acknowledge new data
1755 * - Receive window is not changed
1756 * - The timestamp is within "acceptable" range
1757 * - The new segment is what we are expecting or
1758 * the new segment could be merged w/ the last
1759 * pending segment on the reassemble queue
1761 tcpstat.tcps_pawsaccept++;
1762 tcpstat.tcps_pawsdrop++;
1763 } else {
1764 tcpstat.tcps_rcvduppack++;
1765 tcpstat.tcps_rcvdupbyte += tlen;
1766 tcpstat.tcps_pawsdrop++;
1767 if (tlen)
1768 goto dropafterack;
1769 goto drop;
1774 * In the SYN-RECEIVED state, validate that the packet belongs to
1775 * this connection before trimming the data to fit the receive
1776 * window. Check the sequence number versus IRS since we know
1777 * the sequence numbers haven't wrapped. This is a partial fix
1778 * for the "LAND" DoS attack.
1780 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1781 rstreason = BANDLIM_RST_OPENPORT;
1782 goto dropwithreset;
1785 todrop = tp->rcv_nxt - th->th_seq;
1786 if (todrop > 0) {
1787 if (TCP_DO_SACK(tp)) {
1788 /* Report duplicate segment at head of packet. */
1789 tp->reportblk.rblk_start = th->th_seq;
1790 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
1791 th->th_seq + tlen, thflags);
1792 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1793 tp->reportblk.rblk_end = tp->rcv_nxt;
1794 tp->sack_flags |= (TSACK_F_DUPSEG | TSACK_F_SACKLEFT);
1795 tp->t_flags |= TF_ACKNOW;
1797 if (thflags & TH_SYN) {
1798 thflags &= ~TH_SYN;
1799 th->th_seq++;
1800 if (th->th_urp > 1)
1801 th->th_urp--;
1802 else
1803 thflags &= ~TH_URG;
1804 todrop--;
1807 * Following if statement from Stevens, vol. 2, p. 960.
1809 if (todrop > tlen ||
1810 (todrop == tlen && !(thflags & TH_FIN))) {
1812 * Any valid FIN must be to the left of the window.
1813 * At this point the FIN must be a duplicate or out
1814 * of sequence; drop it.
1816 thflags &= ~TH_FIN;
1819 * Send an ACK to resynchronize and drop any data.
1820 * But keep on processing for RST or ACK.
1822 tp->t_flags |= TF_ACKNOW;
1823 todrop = tlen;
1824 tcpstat.tcps_rcvduppack++;
1825 tcpstat.tcps_rcvdupbyte += todrop;
1826 } else {
1827 tcpstat.tcps_rcvpartduppack++;
1828 tcpstat.tcps_rcvpartdupbyte += todrop;
1830 drop_hdrlen += todrop; /* drop from the top afterwards */
1831 th->th_seq += todrop;
1832 tlen -= todrop;
1833 if (th->th_urp > todrop)
1834 th->th_urp -= todrop;
1835 else {
1836 thflags &= ~TH_URG;
1837 th->th_urp = 0;
1842 * If new data are received on a connection after the
1843 * user processes are gone, then RST the other end.
1845 if ((so->so_state & SS_NOFDREF) &&
1846 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1847 tp = tcp_close(tp);
1848 tcpstat.tcps_rcvafterclose++;
1849 rstreason = BANDLIM_UNLIMITED;
1850 goto dropwithreset;
1854 * If segment ends after window, drop trailing data
1855 * (and PUSH and FIN); if nothing left, just ACK.
1857 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1858 if (todrop > 0) {
1859 tcpstat.tcps_rcvpackafterwin++;
1860 if (todrop >= tlen) {
1861 tcpstat.tcps_rcvbyteafterwin += tlen;
1863 * If a new connection request is received
1864 * while in TIME_WAIT, drop the old connection
1865 * and start over if the sequence numbers
1866 * are above the previous ones.
1868 if (thflags & TH_SYN &&
1869 tp->t_state == TCPS_TIME_WAIT &&
1870 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1871 tp = tcp_close(tp);
1872 goto findpcb;
1875 * If window is closed can only take segments at
1876 * window edge, and have to drop data and PUSH from
1877 * incoming segments. Continue processing, but
1878 * remember to ack. Otherwise, drop segment
1879 * and ack.
1881 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1882 tp->t_flags |= TF_ACKNOW;
1883 tcpstat.tcps_rcvwinprobe++;
1884 } else
1885 goto dropafterack;
1886 } else
1887 tcpstat.tcps_rcvbyteafterwin += todrop;
1888 m_adj(m, -todrop);
1889 tlen -= todrop;
1890 thflags &= ~(TH_PUSH | TH_FIN);
1894 * If last ACK falls within this segment's sequence numbers,
1895 * record its timestamp.
1896 * NOTE:
1897 * 1) That the test incorporates suggestions from the latest
1898 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1899 * 2) That updating only on newer timestamps interferes with
1900 * our earlier PAWS tests, so this check should be solely
1901 * predicated on the sequence space of this segment.
1902 * 3) That we modify the segment boundary check to be
1903 * Last.ACK.Sent <= SEG.SEQ + SEG.LEN
1904 * instead of RFC1323's
1905 * Last.ACK.Sent < SEG.SEQ + SEG.LEN,
1906 * This modified check allows us to overcome RFC1323's
1907 * limitations as described in Stevens TCP/IP Illustrated
1908 * Vol. 2 p.869. In such cases, we can still calculate the
1909 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1911 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1912 SEQ_LEQ(tp->last_ack_sent, (th->th_seq + tlen
1913 + ((thflags & TH_SYN) != 0)
1914 + ((thflags & TH_FIN) != 0)))) {
1915 tp->ts_recent_age = ticks;
1916 tp->ts_recent = to.to_tsval;
1920 * If a SYN is in the window, then this is an
1921 * error and we send an RST and drop the connection.
1923 if (thflags & TH_SYN) {
1924 tp = tcp_drop(tp, ECONNRESET);
1925 rstreason = BANDLIM_UNLIMITED;
1926 goto dropwithreset;
1930 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1931 * flag is on (half-synchronized state), then queue data for
1932 * later processing; else drop segment and return.
1934 if (!(thflags & TH_ACK)) {
1935 if (tp->t_state == TCPS_SYN_RECEIVED ||
1936 (tp->t_flags & TF_NEEDSYN))
1937 goto step6;
1938 else
1939 goto drop;
1943 * Ack processing.
1945 switch (tp->t_state) {
1947 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
1948 * ESTABLISHED state and continue processing.
1949 * The ACK was checked above.
1951 case TCPS_SYN_RECEIVED:
1953 tcpstat.tcps_connects++;
1954 soisconnected(so);
1955 /* Do window scaling? */
1956 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
1957 (TF_RCVD_SCALE | TF_REQ_SCALE))
1958 tp->rcv_scale = tp->request_r_scale;
1960 * Make transitions:
1961 * SYN-RECEIVED -> ESTABLISHED
1962 * SYN-RECEIVED* -> FIN-WAIT-1
1964 tp->t_starttime = ticks;
1965 if (tp->t_flags & TF_NEEDFIN) {
1966 TCP_STATE_CHANGE(tp, TCPS_FIN_WAIT_1);
1967 tp->t_flags &= ~TF_NEEDFIN;
1968 } else {
1969 tcp_established(tp);
1972 * If segment contains data or ACK, will call tcp_reass()
1973 * later; if not, do so now to pass queued data to user.
1975 if (tlen == 0 && !(thflags & TH_FIN))
1976 tcp_reass(tp, NULL, NULL, NULL);
1977 /* fall into ... */
1980 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1981 * ACKs. If the ack is in the range
1982 * tp->snd_una < th->th_ack <= tp->snd_max
1983 * then advance tp->snd_una to th->th_ack and drop
1984 * data from the retransmission queue. If this ACK reflects
1985 * more up to date window information we update our window information.
1987 case TCPS_ESTABLISHED:
1988 case TCPS_FIN_WAIT_1:
1989 case TCPS_FIN_WAIT_2:
1990 case TCPS_CLOSE_WAIT:
1991 case TCPS_CLOSING:
1992 case TCPS_LAST_ACK:
1993 case TCPS_TIME_WAIT:
1995 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1996 boolean_t maynotdup = FALSE;
1998 if (TCP_DO_SACK(tp))
1999 tcp_sack_update_scoreboard(tp, &to);
2001 if (tlen != 0 || tiwin != tp->snd_wnd ||
2002 ((thflags & TH_FIN) && !(tp->t_flags & TF_SAWFIN)))
2003 maynotdup = TRUE;
2005 if (!tcp_callout_active(tp, tp->tt_rexmt) ||
2006 th->th_ack != tp->snd_una) {
2007 if (!maynotdup)
2008 tcpstat.tcps_rcvdupack++;
2009 tp->t_dupacks = 0;
2010 break;
2013 #define DELAY_DUPACK \
2014 do { \
2015 delayed_dupack = TRUE; \
2016 th_dupack = th->th_ack; \
2017 to_flags = to.to_flags; \
2018 } while (0)
2019 if (maynotdup) {
2020 if (!tcp_do_rfc6675 ||
2021 !TCP_DO_SACK(tp) ||
2022 (to.to_flags &
2023 (TOF_SACK | TOF_SACK_REDUNDANT))
2024 != TOF_SACK) {
2025 tp->t_dupacks = 0;
2026 } else {
2027 DELAY_DUPACK;
2029 break;
2031 if ((thflags & TH_FIN) && !(tp->t_flags & TF_QUEDFIN)) {
2033 * This could happen, if the reassemable
2034 * queue overflew or was drained. Don't
2035 * drop this FIN here; defer the duplicated
2036 * ACK processing until this FIN gets queued.
2038 DELAY_DUPACK;
2039 break;
2041 #undef DELAY_DUPACK
2043 if (tcp_recv_dupack(tp, th->th_ack, to.to_flags))
2044 goto drop;
2045 else
2046 break;
2049 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2050 tp->t_dupacks = 0;
2051 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2053 * Detected optimistic ACK attack.
2054 * Force slow-start to de-synchronize attack.
2056 tp->snd_cwnd = tp->t_maxseg;
2057 tp->snd_wacked = 0;
2059 tcpstat.tcps_rcvacktoomuch++;
2060 goto dropafterack;
2063 * If we reach this point, ACK is not a duplicate,
2064 * i.e., it ACKs something we sent.
2066 if (tp->t_flags & TF_NEEDSYN) {
2068 * T/TCP: Connection was half-synchronized, and our
2069 * SYN has been ACK'd (so connection is now fully
2070 * synchronized). Go to non-starred state,
2071 * increment snd_una for ACK of SYN, and check if
2072 * we can do window scaling.
2074 tp->t_flags &= ~TF_NEEDSYN;
2075 tp->snd_una++;
2076 /* Do window scaling? */
2077 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2078 (TF_RCVD_SCALE | TF_REQ_SCALE))
2079 tp->rcv_scale = tp->request_r_scale;
2082 process_ACK:
2083 acked = th->th_ack - tp->snd_una;
2084 tcpstat.tcps_rcvackpack++;
2085 tcpstat.tcps_rcvackbyte += acked;
2087 if (tcp_do_eifel_detect && acked > 0 &&
2088 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2089 (tp->rxt_flags & TRXT_F_FIRSTACCACK)) {
2090 /* Eifel detection applicable. */
2091 if (to.to_tsecr < tp->t_rexmtTS) {
2092 ++tcpstat.tcps_eifeldetected;
2093 tcp_revert_congestion_state(tp);
2094 if (tp->t_rxtshift != 1 ||
2095 ticks >= tp->t_badrxtwin)
2096 ++tcpstat.tcps_rttcantdetect;
2098 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2100 * If we just performed our first retransmit,
2101 * and the ACK arrives within our recovery window,
2102 * then it was a mistake to do the retransmit
2103 * in the first place. Recover our original cwnd
2104 * and ssthresh, and proceed to transmit where we
2105 * left off.
2107 tcp_revert_congestion_state(tp);
2108 ++tcpstat.tcps_rttdetected;
2112 * If we have a timestamp reply, update smoothed
2113 * round trip time. If no timestamp is present but
2114 * transmit timer is running and timed sequence
2115 * number was acked, update smoothed round trip time.
2116 * Since we now have an rtt measurement, cancel the
2117 * timer backoff (cf., Phil Karn's retransmit alg.).
2118 * Recompute the initial retransmit timer.
2120 * Some machines (certain windows boxes) send broken
2121 * timestamp replies during the SYN+ACK phase, ignore
2122 * timestamps of 0.
2124 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2125 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1,
2126 th->th_ack);
2127 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2128 tcp_xmit_timer(tp, ticks - tp->t_rtttime + 1,
2129 th->th_ack);
2130 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2133 * If no data (only SYN) was ACK'd,
2134 * skip rest of ACK processing.
2136 if (acked == 0)
2137 goto step6;
2139 /* Stop looking for an acceptable ACK since one was received. */
2140 tp->rxt_flags &= ~(TRXT_F_FIRSTACCACK |
2141 TRXT_F_FASTREXMT | TRXT_F_EARLYREXMT);
2143 if (acked > so->so_snd.ssb_cc) {
2144 tp->snd_wnd -= so->so_snd.ssb_cc;
2145 sbdrop(&so->so_snd.sb, (int)so->so_snd.ssb_cc);
2146 ourfinisacked = TRUE;
2147 } else {
2148 sbdrop(&so->so_snd.sb, acked);
2149 tp->snd_wnd -= acked;
2150 ourfinisacked = FALSE;
2152 sowwakeup(so);
2155 * Update window information.
2157 if (acceptable_window_update(tp, th, tiwin)) {
2158 /* keep track of pure window updates */
2159 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2160 tiwin > tp->snd_wnd)
2161 tcpstat.tcps_rcvwinupd++;
2162 tp->snd_wnd = tiwin;
2163 tp->snd_wl1 = th->th_seq;
2164 tp->snd_wl2 = th->th_ack;
2165 if (tp->snd_wnd > tp->max_sndwnd)
2166 tp->max_sndwnd = tp->snd_wnd;
2167 needoutput = TRUE;
2170 tp->snd_una = th->th_ack;
2171 if (TCP_DO_SACK(tp))
2172 tcp_sack_update_scoreboard(tp, &to);
2173 if (IN_FASTRECOVERY(tp)) {
2174 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2175 EXIT_FASTRECOVERY(tp);
2176 needoutput = TRUE;
2178 * If the congestion window was inflated
2179 * to account for the other side's
2180 * cached packets, retract it.
2182 if (!TCP_DO_SACK(tp))
2183 tp->snd_cwnd = tp->snd_ssthresh;
2186 * Window inflation should have left us
2187 * with approximately snd_ssthresh outstanding
2188 * data. But, in case we would be inclined
2189 * to send a burst, better do it using
2190 * slow start.
2192 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2193 tp->snd_max + 2 * tp->t_maxseg))
2194 tp->snd_cwnd =
2195 (tp->snd_max - tp->snd_una) +
2196 2 * tp->t_maxseg;
2198 tp->snd_wacked = 0;
2199 } else {
2200 if (TCP_DO_SACK(tp)) {
2201 tp->snd_max_rexmt = tp->snd_max;
2202 tcp_sack_rexmt(tp,
2203 tp->snd_una == tp->rexmt_high);
2204 } else {
2205 tcp_newreno_partial_ack(tp, th, acked);
2207 needoutput = FALSE;
2209 } else {
2211 * Open the congestion window. When in slow-start,
2212 * open exponentially: maxseg per packet. Otherwise,
2213 * open linearly: maxseg per window.
2215 if (tp->snd_cwnd <= tp->snd_ssthresh) {
2216 u_int abc_sslimit =
2217 (SEQ_LT(tp->snd_nxt, tp->snd_max) ?
2218 tp->t_maxseg : 2 * tp->t_maxseg);
2220 /* slow-start */
2221 tp->snd_cwnd += tcp_do_abc ?
2222 min(acked, abc_sslimit) : tp->t_maxseg;
2223 } else {
2224 /* linear increase */
2225 tp->snd_wacked += tcp_do_abc ? acked :
2226 tp->t_maxseg;
2227 if (tp->snd_wacked >= tp->snd_cwnd) {
2228 tp->snd_wacked -= tp->snd_cwnd;
2229 tp->snd_cwnd += tp->t_maxseg;
2232 tp->snd_cwnd = min(tp->snd_cwnd,
2233 TCP_MAXWIN << tp->snd_scale);
2234 tp->snd_recover = th->th_ack - 1;
2236 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2237 tp->snd_nxt = tp->snd_una;
2240 * If all outstanding data is acked, stop retransmit
2241 * timer and remember to restart (more output or persist).
2242 * If there is more data to be acked, restart retransmit
2243 * timer, using current (possibly backed-off) value.
2245 if (th->th_ack == tp->snd_max) {
2246 tcp_callout_stop(tp, tp->tt_rexmt);
2247 needoutput = TRUE;
2248 } else if (!tcp_callout_active(tp, tp->tt_persist)) {
2249 tcp_callout_reset(tp, tp->tt_rexmt, tp->t_rxtcur,
2250 tcp_timer_rexmt);
2253 switch (tp->t_state) {
2255 * In FIN_WAIT_1 STATE in addition to the processing
2256 * for the ESTABLISHED state if our FIN is now acknowledged
2257 * then enter FIN_WAIT_2.
2259 case TCPS_FIN_WAIT_1:
2260 if (ourfinisacked) {
2262 * If we can't receive any more
2263 * data, then closing user can proceed.
2264 * Starting the timer is contrary to the
2265 * specification, but if we don't get a FIN
2266 * we'll hang forever.
2268 if (so->so_state & SS_CANTRCVMORE) {
2269 soisdisconnected(so);
2270 tcp_callout_reset(tp, tp->tt_2msl,
2271 tp->t_maxidle, tcp_timer_2msl);
2273 TCP_STATE_CHANGE(tp, TCPS_FIN_WAIT_2);
2275 break;
2278 * In CLOSING STATE in addition to the processing for
2279 * the ESTABLISHED state if the ACK acknowledges our FIN
2280 * then enter the TIME-WAIT state, otherwise ignore
2281 * the segment.
2283 case TCPS_CLOSING:
2284 if (ourfinisacked) {
2285 TCP_STATE_CHANGE(tp, TCPS_TIME_WAIT);
2286 tcp_canceltimers(tp);
2287 tcp_callout_reset(tp, tp->tt_2msl,
2288 2 * tcp_rmx_msl(tp),
2289 tcp_timer_2msl);
2290 soisdisconnected(so);
2292 break;
2295 * In LAST_ACK, we may still be waiting for data to drain
2296 * and/or to be acked, as well as for the ack of our FIN.
2297 * If our FIN is now acknowledged, delete the TCB,
2298 * enter the closed state and return.
2300 case TCPS_LAST_ACK:
2301 if (ourfinisacked) {
2302 tp = tcp_close(tp);
2303 goto drop;
2305 break;
2308 * In TIME_WAIT state the only thing that should arrive
2309 * is a retransmission of the remote FIN. Acknowledge
2310 * it and restart the finack timer.
2312 case TCPS_TIME_WAIT:
2313 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2314 tcp_timer_2msl);
2315 goto dropafterack;
2319 step6:
2321 * Update window information.
2322 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2324 if ((thflags & TH_ACK) &&
2325 acceptable_window_update(tp, th, tiwin)) {
2326 /* keep track of pure window updates */
2327 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2328 tiwin > tp->snd_wnd)
2329 tcpstat.tcps_rcvwinupd++;
2330 tp->snd_wnd = tiwin;
2331 tp->snd_wl1 = th->th_seq;
2332 tp->snd_wl2 = th->th_ack;
2333 if (tp->snd_wnd > tp->max_sndwnd)
2334 tp->max_sndwnd = tp->snd_wnd;
2335 needoutput = TRUE;
2339 * Process segments with URG.
2341 if ((thflags & TH_URG) && th->th_urp &&
2342 !TCPS_HAVERCVDFIN(tp->t_state)) {
2344 * This is a kludge, but if we receive and accept
2345 * random urgent pointers, we'll crash in
2346 * soreceive. It's hard to imagine someone
2347 * actually wanting to send this much urgent data.
2349 if (th->th_urp + so->so_rcv.ssb_cc > sb_max) {
2350 th->th_urp = 0; /* XXX */
2351 thflags &= ~TH_URG; /* XXX */
2352 goto dodata; /* XXX */
2355 * If this segment advances the known urgent pointer,
2356 * then mark the data stream. This should not happen
2357 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2358 * a FIN has been received from the remote side.
2359 * In these states we ignore the URG.
2361 * According to RFC961 (Assigned Protocols),
2362 * the urgent pointer points to the last octet
2363 * of urgent data. We continue, however,
2364 * to consider it to indicate the first octet
2365 * of data past the urgent section as the original
2366 * spec states (in one of two places).
2368 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2369 tp->rcv_up = th->th_seq + th->th_urp;
2370 so->so_oobmark = so->so_rcv.ssb_cc +
2371 (tp->rcv_up - tp->rcv_nxt) - 1;
2372 if (so->so_oobmark == 0)
2373 sosetstate(so, SS_RCVATMARK);
2374 sohasoutofband(so);
2375 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2378 * Remove out of band data so doesn't get presented to user.
2379 * This can happen independent of advancing the URG pointer,
2380 * but if two URG's are pending at once, some out-of-band
2381 * data may creep in... ick.
2383 if (th->th_urp <= (u_long)tlen &&
2384 !(so->so_options & SO_OOBINLINE)) {
2385 /* hdr drop is delayed */
2386 tcp_pulloutofband(so, th, m, drop_hdrlen);
2388 } else {
2390 * If no out of band data is expected,
2391 * pull receive urgent pointer along
2392 * with the receive window.
2394 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2395 tp->rcv_up = tp->rcv_nxt;
2398 dodata: /* XXX */
2400 * Process the segment text, merging it into the TCP sequencing queue,
2401 * and arranging for acknowledgment of receipt if necessary.
2402 * This process logically involves adjusting tp->rcv_wnd as data
2403 * is presented to the user (this happens in tcp_usrreq.c,
2404 * case PRU_RCVD). If a FIN has already been received on this
2405 * connection then we just ignore the text.
2407 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2408 if (thflags & TH_FIN)
2409 tp->t_flags |= TF_SAWFIN;
2410 m_adj(m, drop_hdrlen); /* delayed header drop */
2412 * Insert segment which includes th into TCP reassembly queue
2413 * with control block tp. Set thflags to whether reassembly now
2414 * includes a segment with FIN. This handles the common case
2415 * inline (segment is the next to be received on an established
2416 * connection, and the queue is empty), avoiding linkage into
2417 * and removal from the queue and repetition of various
2418 * conversions.
2419 * Set DELACK for segments received in order, but ack
2420 * immediately when segments are out of order (so
2421 * fast retransmit can work).
2423 if (th->th_seq == tp->rcv_nxt &&
2424 TAILQ_EMPTY(&tp->t_segq) &&
2425 TCPS_HAVEESTABLISHED(tp->t_state)) {
2426 if (thflags & TH_FIN)
2427 tp->t_flags |= TF_QUEDFIN;
2428 if (DELAY_ACK(tp)) {
2429 tcp_callout_reset(tp, tp->tt_delack,
2430 tcp_delacktime, tcp_timer_delack);
2431 } else {
2432 tp->t_flags |= TF_ACKNOW;
2434 tp->rcv_nxt += tlen;
2435 thflags = th->th_flags & TH_FIN;
2436 tcpstat.tcps_rcvpack++;
2437 tcpstat.tcps_rcvbyte += tlen;
2438 ND6_HINT(tp);
2439 if (so->so_state & SS_CANTRCVMORE) {
2440 m_freem(m);
2441 } else {
2442 lwkt_gettoken(&so->so_rcv.ssb_token);
2443 ssb_appendstream(&so->so_rcv, m);
2444 lwkt_reltoken(&so->so_rcv.ssb_token);
2446 sorwakeup(so);
2447 } else {
2448 if (!(tp->sack_flags & TSACK_F_DUPSEG)) {
2449 /* Initialize SACK report block. */
2450 tp->reportblk.rblk_start = th->th_seq;
2451 tp->reportblk.rblk_end = TCP_SACK_BLKEND(
2452 th->th_seq + tlen, thflags);
2454 thflags = tcp_reass(tp, th, &tlen, m);
2455 tp->t_flags |= TF_ACKNOW;
2459 * Note the amount of data that peer has sent into
2460 * our window, in order to estimate the sender's
2461 * buffer size.
2463 len = so->so_rcv.ssb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2464 } else {
2465 m_freem(m);
2466 thflags &= ~TH_FIN;
2470 * If FIN is received ACK the FIN and let the user know
2471 * that the connection is closing.
2473 if (thflags & TH_FIN) {
2474 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2475 socantrcvmore(so);
2477 * If connection is half-synchronized
2478 * (ie NEEDSYN flag on) then delay ACK,
2479 * so it may be piggybacked when SYN is sent.
2480 * Otherwise, since we received a FIN then no
2481 * more input can be expected, send ACK now.
2483 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
2484 tcp_callout_reset(tp, tp->tt_delack,
2485 tcp_delacktime, tcp_timer_delack);
2486 } else {
2487 tp->t_flags |= TF_ACKNOW;
2489 tp->rcv_nxt++;
2492 switch (tp->t_state) {
2494 * In SYN_RECEIVED and ESTABLISHED STATES
2495 * enter the CLOSE_WAIT state.
2497 case TCPS_SYN_RECEIVED:
2498 tp->t_starttime = ticks;
2499 /*FALLTHROUGH*/
2500 case TCPS_ESTABLISHED:
2501 TCP_STATE_CHANGE(tp, TCPS_CLOSE_WAIT);
2502 break;
2505 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2506 * enter the CLOSING state.
2508 case TCPS_FIN_WAIT_1:
2509 TCP_STATE_CHANGE(tp, TCPS_CLOSING);
2510 break;
2513 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2514 * starting the time-wait timer, turning off the other
2515 * standard timers.
2517 case TCPS_FIN_WAIT_2:
2518 TCP_STATE_CHANGE(tp, TCPS_TIME_WAIT);
2519 tcp_canceltimers(tp);
2520 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2521 tcp_timer_2msl);
2522 soisdisconnected(so);
2523 break;
2526 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2528 case TCPS_TIME_WAIT:
2529 tcp_callout_reset(tp, tp->tt_2msl, 2 * tcp_rmx_msl(tp),
2530 tcp_timer_2msl);
2531 break;
2535 #ifdef TCPDEBUG
2536 if (so->so_options & SO_DEBUG)
2537 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2538 #endif
2541 * Delayed duplicated ACK processing
2543 if (delayed_dupack && tcp_recv_dupack(tp, th_dupack, to_flags))
2544 needoutput = FALSE;
2547 * Return any desired output.
2549 if ((tp->t_flags & TF_ACKNOW) ||
2550 (needoutput && tcp_sack_report_needed(tp))) {
2551 tcp_output_cancel(tp);
2552 tcp_output_fair(tp);
2553 } else if (needoutput && !tcp_output_pending(tp)) {
2554 tcp_output_fair(tp);
2556 tcp_sack_report_cleanup(tp);
2557 return(IPPROTO_DONE);
2559 dropafterack:
2561 * Generate an ACK dropping incoming segment if it occupies
2562 * sequence space, where the ACK reflects our state.
2564 * We can now skip the test for the RST flag since all
2565 * paths to this code happen after packets containing
2566 * RST have been dropped.
2568 * In the SYN-RECEIVED state, don't send an ACK unless the
2569 * segment we received passes the SYN-RECEIVED ACK test.
2570 * If it fails send a RST. This breaks the loop in the
2571 * "LAND" DoS attack, and also prevents an ACK storm
2572 * between two listening ports that have been sent forged
2573 * SYN segments, each with the source address of the other.
2575 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2576 (SEQ_GT(tp->snd_una, th->th_ack) ||
2577 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2578 rstreason = BANDLIM_RST_OPENPORT;
2579 goto dropwithreset;
2581 #ifdef TCPDEBUG
2582 if (so->so_options & SO_DEBUG)
2583 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2584 #endif
2585 m_freem(m);
2586 tp->t_flags |= TF_ACKNOW;
2587 tcp_output(tp);
2588 tcp_sack_report_cleanup(tp);
2589 return(IPPROTO_DONE);
2591 dropwithreset:
2593 * Generate a RST, dropping incoming segment.
2594 * Make ACK acceptable to originator of segment.
2595 * Don't bother to respond if destination was broadcast/multicast.
2597 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2598 goto drop;
2599 if (isipv6) {
2600 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2601 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2602 goto drop;
2603 } else {
2604 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2605 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2606 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2607 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2608 goto drop;
2610 /* IPv6 anycast check is done at tcp6_input() */
2613 * Perform bandwidth limiting.
2615 #ifdef ICMP_BANDLIM
2616 if (badport_bandlim(rstreason) < 0)
2617 goto drop;
2618 #endif
2620 #ifdef TCPDEBUG
2621 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2622 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2623 #endif
2624 if (thflags & TH_ACK)
2625 /* mtod() below is safe as long as hdr dropping is delayed */
2626 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2627 TH_RST);
2628 else {
2629 if (thflags & TH_SYN)
2630 tlen++;
2631 /* mtod() below is safe as long as hdr dropping is delayed */
2632 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2633 (tcp_seq)0, TH_RST | TH_ACK);
2635 if (tp != NULL)
2636 tcp_sack_report_cleanup(tp);
2637 return(IPPROTO_DONE);
2639 drop:
2641 * Drop space held by incoming segment and return.
2643 #ifdef TCPDEBUG
2644 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2645 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2646 #endif
2647 m_freem(m);
2648 if (tp != NULL)
2649 tcp_sack_report_cleanup(tp);
2650 return(IPPROTO_DONE);
2654 * Parse TCP options and place in tcpopt.
2656 static void
2657 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn,
2658 tcp_seq ack)
2660 int opt, optlen, i;
2662 to->to_flags = 0;
2663 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2664 opt = cp[0];
2665 if (opt == TCPOPT_EOL)
2666 break;
2667 if (opt == TCPOPT_NOP)
2668 optlen = 1;
2669 else {
2670 if (cnt < 2)
2671 break;
2672 optlen = cp[1];
2673 if (optlen < 2 || optlen > cnt)
2674 break;
2676 switch (opt) {
2677 case TCPOPT_MAXSEG:
2678 if (optlen != TCPOLEN_MAXSEG)
2679 continue;
2680 if (!is_syn)
2681 continue;
2682 to->to_flags |= TOF_MSS;
2683 bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2684 to->to_mss = ntohs(to->to_mss);
2685 break;
2686 case TCPOPT_WINDOW:
2687 if (optlen != TCPOLEN_WINDOW)
2688 continue;
2689 if (!is_syn)
2690 continue;
2691 to->to_flags |= TOF_SCALE;
2692 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2693 break;
2694 case TCPOPT_TIMESTAMP:
2695 if (optlen != TCPOLEN_TIMESTAMP)
2696 continue;
2697 to->to_flags |= TOF_TS;
2698 bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2699 to->to_tsval = ntohl(to->to_tsval);
2700 bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2701 to->to_tsecr = ntohl(to->to_tsecr);
2703 * If echoed timestamp is later than the current time,
2704 * fall back to non RFC1323 RTT calculation.
2706 if (to->to_tsecr != 0 && TSTMP_GT(to->to_tsecr, ticks))
2707 to->to_tsecr = 0;
2708 break;
2709 case TCPOPT_SACK_PERMITTED:
2710 if (optlen != TCPOLEN_SACK_PERMITTED)
2711 continue;
2712 if (!is_syn)
2713 continue;
2714 to->to_flags |= TOF_SACK_PERMITTED;
2715 break;
2716 case TCPOPT_SACK:
2717 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2718 continue;
2719 to->to_nsackblocks = (optlen - 2) / 8;
2720 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2721 to->to_flags |= TOF_SACK;
2722 for (i = 0; i < to->to_nsackblocks; i++) {
2723 struct raw_sackblock *r = &to->to_sackblocks[i];
2725 r->rblk_start = ntohl(r->rblk_start);
2726 r->rblk_end = ntohl(r->rblk_end);
2728 if (SEQ_LEQ(r->rblk_end, r->rblk_start)) {
2730 * Invalid SACK block; discard all
2731 * SACK blocks
2733 tcpstat.tcps_rcvbadsackopt++;
2734 to->to_nsackblocks = 0;
2735 to->to_sackblocks = NULL;
2736 to->to_flags &= ~TOF_SACK;
2737 break;
2740 if ((to->to_flags & TOF_SACK) &&
2741 tcp_sack_ndsack_blocks(to->to_sackblocks,
2742 to->to_nsackblocks, ack))
2743 to->to_flags |= TOF_DSACK;
2744 break;
2745 #ifdef TCP_SIGNATURE
2747 * XXX In order to reply to a host which has set the
2748 * TCP_SIGNATURE option in its initial SYN, we have to
2749 * record the fact that the option was observed here
2750 * for the syncache code to perform the correct response.
2752 case TCPOPT_SIGNATURE:
2753 if (optlen != TCPOLEN_SIGNATURE)
2754 continue;
2755 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2756 break;
2757 #endif /* TCP_SIGNATURE */
2758 default:
2759 continue;
2765 * Pull out of band byte out of a segment so
2766 * it doesn't appear in the user's data queue.
2767 * It is still reflected in the segment length for
2768 * sequencing purposes.
2769 * "off" is the delayed to be dropped hdrlen.
2771 static void
2772 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2774 int cnt = off + th->th_urp - 1;
2776 while (cnt >= 0) {
2777 if (m->m_len > cnt) {
2778 char *cp = mtod(m, caddr_t) + cnt;
2779 struct tcpcb *tp = sototcpcb(so);
2781 tp->t_iobc = *cp;
2782 tp->t_oobflags |= TCPOOB_HAVEDATA;
2783 bcopy(cp + 1, cp, m->m_len - cnt - 1);
2784 m->m_len--;
2785 if (m->m_flags & M_PKTHDR)
2786 m->m_pkthdr.len--;
2787 return;
2789 cnt -= m->m_len;
2790 m = m->m_next;
2791 if (m == NULL)
2792 break;
2794 panic("tcp_pulloutofband");
2798 * Collect new round-trip time estimate and update averages and current
2799 * timeout.
2801 static void
2802 tcp_xmit_timer(struct tcpcb *tp, int rtt, tcp_seq ack)
2804 int rebaserto = 0;
2806 tcpstat.tcps_rttupdated++;
2807 tp->t_rttupdated++;
2808 if ((tp->rxt_flags & TRXT_F_REBASERTO) &&
2809 SEQ_GT(ack, tp->snd_max_prev)) {
2810 #ifdef DEBUG_EIFEL_RESPONSE
2811 kprintf("srtt/rttvar, prev %d/%d, cur %d/%d, ",
2812 tp->t_srtt_prev, tp->t_rttvar_prev,
2813 tp->t_srtt, tp->t_rttvar);
2814 #endif
2816 tcpstat.tcps_eifelresponse++;
2817 rebaserto = 1;
2818 tp->rxt_flags &= ~TRXT_F_REBASERTO;
2819 tp->t_srtt = max(tp->t_srtt_prev, (rtt << TCP_RTT_SHIFT));
2820 tp->t_rttvar = max(tp->t_rttvar_prev,
2821 (rtt << (TCP_RTTVAR_SHIFT - 1)));
2822 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2823 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2825 #ifdef DEBUG_EIFEL_RESPONSE
2826 kprintf("new %d/%d ", tp->t_srtt, tp->t_rttvar);
2827 #endif
2828 } else if (tp->t_srtt != 0) {
2829 int delta;
2832 * srtt is stored as fixed point with 5 bits after the
2833 * binary point (i.e., scaled by 32). The following magic
2834 * is equivalent to the smoothing algorithm in rfc793 with
2835 * an alpha of .875 (srtt = rtt/32 + srtt*31/32 in fixed
2836 * point). Adjust rtt to origin 0.
2838 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2839 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2841 if ((tp->t_srtt += delta) <= 0)
2842 tp->t_srtt = 1;
2845 * We accumulate a smoothed rtt variance (actually, a
2846 * smoothed mean difference), then set the retransmit
2847 * timer to smoothed rtt + 4 times the smoothed variance.
2848 * rttvar is stored as fixed point with 4 bits after the
2849 * binary point (scaled by 16). The following is
2850 * equivalent to rfc793 smoothing with an alpha of .75
2851 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2852 * rfc793's wired-in beta.
2854 if (delta < 0)
2855 delta = -delta;
2856 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2857 if ((tp->t_rttvar += delta) <= 0)
2858 tp->t_rttvar = 1;
2859 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2860 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2861 } else {
2863 * No rtt measurement yet - use the unsmoothed rtt.
2864 * Set the variance to half the rtt (so our first
2865 * retransmit happens at 3*rtt).
2867 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2868 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2869 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2871 tp->t_rtttime = 0;
2872 tp->t_rxtshift = 0;
2874 #ifdef DEBUG_EIFEL_RESPONSE
2875 if (rebaserto) {
2876 kprintf("| rxtcur prev %d, old %d, ",
2877 tp->t_rxtcur_prev, tp->t_rxtcur);
2879 #endif
2882 * the retransmit should happen at rtt + 4 * rttvar.
2883 * Because of the way we do the smoothing, srtt and rttvar
2884 * will each average +1/2 tick of bias. When we compute
2885 * the retransmit timer, we want 1/2 tick of rounding and
2886 * 1 extra tick because of +-1/2 tick uncertainty in the
2887 * firing of the timer. The bias will give us exactly the
2888 * 1.5 tick we need. But, because the bias is
2889 * statistical, we have to test that we don't drop below
2890 * the minimum feasible timer (which is 2 ticks).
2892 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2893 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2895 if (rebaserto) {
2896 if (tp->t_rxtcur < tp->t_rxtcur_prev + tcp_eifel_rtoinc) {
2898 * RFC4015 requires that the new RTO is at least
2899 * 2*G (tcp_eifel_rtoinc) greater then the RTO
2900 * (t_rxtcur_prev) when the spurious retransmit
2901 * timeout happens.
2903 * The above condition could be true, if the SRTT
2904 * and RTTVAR used to calculate t_rxtcur_prev
2905 * resulted in a value less than t_rttmin. So
2906 * simply increasing SRTT by tcp_eifel_rtoinc when
2907 * preparing for the Eifel response could not ensure
2908 * that the new RTO will be tcp_eifel_rtoinc greater
2909 * t_rxtcur_prev.
2911 tp->t_rxtcur = tp->t_rxtcur_prev + tcp_eifel_rtoinc;
2913 #ifdef DEBUG_EIFEL_RESPONSE
2914 kprintf("new %d\n", tp->t_rxtcur);
2915 #endif
2919 * We received an ack for a packet that wasn't retransmitted;
2920 * it is probably safe to discard any error indications we've
2921 * received recently. This isn't quite right, but close enough
2922 * for now (a route might have failed after we sent a segment,
2923 * and the return path might not be symmetrical).
2925 tp->t_softerror = 0;
2929 * Determine a reasonable value for maxseg size.
2930 * If the route is known, check route for mtu.
2931 * If none, use an mss that can be handled on the outgoing
2932 * interface without forcing IP to fragment; if bigger than
2933 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2934 * to utilize large mbufs. If no route is found, route has no mtu,
2935 * or the destination isn't local, use a default, hopefully conservative
2936 * size (usually 512 or the default IP max size, but no more than the mtu
2937 * of the interface), as we can't discover anything about intervening
2938 * gateways or networks. We also initialize the congestion/slow start
2939 * window to be a single segment if the destination isn't local.
2941 * Also take into account the space needed for options that we
2942 * send regularly. Make maxseg shorter by that amount to assure
2943 * that we can send maxseg amount of data even when the options
2944 * are present. Store the upper limit of the length of options plus
2945 * data in maxopd.
2947 * NOTE that this routine is only called when we process an incoming
2948 * segment, for outgoing segments only tcp_mssopt is called.
2950 static void
2951 tcp_rmx_mss(struct tcpcb *tp, struct rtentry *rt, int offer)
2953 struct ifnet *ifp;
2954 int mss;
2955 u_long bufsize;
2956 struct inpcb *inp = tp->t_inpcb;
2957 struct socket *so;
2958 #ifdef INET6
2959 boolean_t isipv6 = INP_ISIPV6(inp);
2960 size_t min_protoh = isipv6 ?
2961 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2962 sizeof(struct tcpiphdr);
2963 #else
2964 const boolean_t isipv6 = FALSE;
2965 const size_t min_protoh = sizeof(struct tcpiphdr);
2966 #endif
2968 if (rt == NULL) {
2969 tp->t_maxopd = tp->t_maxseg =
2970 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2971 return;
2973 ifp = rt->rt_ifp;
2974 so = inp->inp_socket;
2977 * Offer == 0 means that there was no MSS on the SYN segment,
2978 * in this case we use either the interface mtu or tcp_mssdflt.
2980 * An offer which is too large will be cut down later.
2982 if (offer == 0) {
2983 if (isipv6) {
2984 if (in6_localaddr(&inp->in6p_faddr))
2985 offer = IN6_LINKMTU(rt->rt_ifp) - min_protoh;
2986 else
2987 offer = tcp_v6mssdflt;
2988 } else {
2989 if (in_localaddr(inp->inp_faddr))
2990 offer = ifp->if_mtu - min_protoh;
2991 else
2992 offer = tcp_mssdflt;
2997 * Prevent DoS attack with too small MSS. Round up
2998 * to at least minmss.
3000 * Sanity check: make sure that maxopd will be large
3001 * enough to allow some data on segments even is the
3002 * all the option space is used (40bytes). Otherwise
3003 * funny things may happen in tcp_output.
3005 offer = max(offer, tcp_minmss);
3006 offer = max(offer, 64);
3008 rt->rt_rmx.rmx_mssopt = offer;
3011 * if there's an mtu associated with the route, use it
3012 * else, use the link mtu. Take the smaller of mss or offer
3013 * as our final mss.
3015 if (rt->rt_rmx.rmx_mtu) {
3016 mss = rt->rt_rmx.rmx_mtu;
3017 } else {
3018 if (isipv6)
3019 mss = IN6_LINKMTU(rt->rt_ifp);
3020 else
3021 mss = ifp->if_mtu;
3023 mss -= min_protoh;
3024 mss = min(mss, offer);
3027 * maxopd stores the maximum length of data AND options
3028 * in a segment; maxseg is the amount of data in a normal
3029 * segment. We need to store this value (maxopd) apart
3030 * from maxseg, because now every segment carries options
3031 * and thus we normally have somewhat less data in segments.
3033 tp->t_maxopd = mss;
3035 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
3036 ((tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3037 mss -= TCPOLEN_TSTAMP_APPA;
3039 #if (MCLBYTES & (MCLBYTES - 1)) == 0
3040 if (mss > MCLBYTES)
3041 mss &= ~(MCLBYTES-1);
3042 #else
3043 if (mss > MCLBYTES)
3044 mss = mss / MCLBYTES * MCLBYTES;
3045 #endif
3047 * If there's a pipesize, change the socket buffer
3048 * to that size. Make the socket buffers an integral
3049 * number of mss units; if the mss is larger than
3050 * the socket buffer, decrease the mss.
3052 #ifdef RTV_SPIPE
3053 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
3054 #endif
3055 bufsize = so->so_snd.ssb_hiwat;
3056 if (bufsize < mss)
3057 mss = bufsize;
3058 else {
3059 bufsize = roundup(bufsize, mss);
3060 if (bufsize > sb_max)
3061 bufsize = sb_max;
3062 if (bufsize > so->so_snd.ssb_hiwat)
3063 ssb_reserve(&so->so_snd, bufsize, so, NULL);
3065 tp->t_maxseg = mss;
3067 #ifdef RTV_RPIPE
3068 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3069 #endif
3070 bufsize = so->so_rcv.ssb_hiwat;
3071 if (bufsize > mss) {
3072 bufsize = roundup(bufsize, mss);
3073 if (bufsize > sb_max)
3074 bufsize = sb_max;
3075 if (bufsize > so->so_rcv.ssb_hiwat) {
3076 lwkt_gettoken(&so->so_rcv.ssb_token);
3077 ssb_reserve(&so->so_rcv, bufsize, so, NULL);
3078 lwkt_reltoken(&so->so_rcv.ssb_token);
3083 * Set the slow-start flight size
3085 * NOTE: t_maxseg must have been configured!
3087 tp->snd_cwnd = tcp_initial_window(tp);
3089 if (rt->rt_rmx.rmx_ssthresh) {
3091 * There's some sort of gateway or interface
3092 * buffer limit on the path. Use this to set
3093 * the slow start threshhold, but set the
3094 * threshold to no less than 2*mss.
3096 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3097 tcpstat.tcps_usedssthresh++;
3101 static void
3102 tcp_rmx_rtt(struct tcpcb *tp, struct rtentry *rt)
3104 int rtt;
3106 if (rt == NULL)
3107 return;
3110 * Check if there's an initial rtt or rttvar. Convert
3111 * from the route-table units to scaled multiples of
3112 * the slow timeout timer.
3114 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
3116 * XXX the lock bit for RTT indicates that the value
3117 * is also a minimum value; this is subject to time.
3119 if (rt->rt_rmx.rmx_locks & RTV_RTT)
3120 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
3121 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
3122 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3123 tcpstat.tcps_usedrtt++;
3124 if (rt->rt_rmx.rmx_rttvar) {
3125 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
3126 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
3127 tcpstat.tcps_usedrttvar++;
3128 } else {
3129 /* default variation is +- 1 rtt */
3130 tp->t_rttvar =
3131 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3133 TCPT_RANGESET(tp->t_rxtcur,
3134 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3135 tp->t_rttmin, TCPTV_REXMTMAX);
3139 void
3140 tcp_rmx_init(struct tcpcb *tp, int offer)
3142 struct inpcb *inp = tp->t_inpcb;
3143 #ifdef INET6
3144 boolean_t isipv6 = INP_ISIPV6(inp);
3145 #else
3146 const boolean_t isipv6 = FALSE;
3147 #endif
3148 struct rtentry *rt;
3150 if (isipv6)
3151 rt = tcp_rtlookup6(&inp->inp_inc);
3152 else
3153 rt = tcp_rtlookup(&inp->inp_inc);
3155 tcp_rmx_mss(tp, rt, offer);
3156 tcp_rmx_rtt(tp, rt);
3158 if (rt != NULL && !tcp_ncr_linklocal && (rt->rt_flags & RTF_LLINFO)) {
3159 /* Don't enable NCR on link-local network. */
3160 tp->t_flags &= ~TF_NCR;
3165 * Determine the MSS option to send on an outgoing SYN.
3168 tcp_mssopt(struct tcpcb *tp)
3170 struct rtentry *rt;
3171 #ifdef INET6
3172 boolean_t isipv6 = INP_ISIPV6(tp->t_inpcb);
3173 int min_protoh = isipv6 ?
3174 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3175 sizeof(struct tcpiphdr);
3176 #else
3177 const boolean_t isipv6 = FALSE;
3178 const size_t min_protoh = sizeof(struct tcpiphdr);
3179 #endif
3181 if (isipv6)
3182 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3183 else
3184 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3185 if (rt == NULL)
3186 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3188 #ifdef INET6
3189 return ((isipv6 ? IN6_LINKMTU(rt->rt_ifp) : rt->rt_ifp->if_mtu) -
3190 min_protoh);
3191 #else
3192 return (rt->rt_ifp->if_mtu - min_protoh);
3193 #endif
3197 * When a partial ack arrives, force the retransmission of the
3198 * next unacknowledged segment. Do not exit Fast Recovery.
3200 * Implement the Slow-but-Steady variant of NewReno by restarting the
3201 * the retransmission timer. Turn it off here so it can be restarted
3202 * later in tcp_output().
3204 static void
3205 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3207 tcp_seq old_snd_nxt = tp->snd_nxt;
3208 u_long ocwnd = tp->snd_cwnd;
3210 tcp_callout_stop(tp, tp->tt_rexmt);
3211 tp->t_rtttime = 0;
3212 tp->snd_nxt = th->th_ack;
3213 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3214 tp->snd_cwnd = tp->t_maxseg;
3215 tp->t_flags |= TF_ACKNOW;
3216 tcp_output(tp);
3217 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3218 tp->snd_nxt = old_snd_nxt;
3219 /* partial window deflation */
3220 if (ocwnd > acked)
3221 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3222 else
3223 tp->snd_cwnd = tp->t_maxseg;
3227 * In contrast to the Slow-but-Steady NewReno variant,
3228 * we do not reset the retransmission timer for SACK retransmissions,
3229 * except when retransmitting snd_una.
3231 static void
3232 tcp_sack_rexmt(struct tcpcb *tp, boolean_t force)
3234 tcp_seq old_snd_nxt = tp->snd_nxt;
3235 u_long ocwnd = tp->snd_cwnd;
3236 uint32_t pipe;
3237 int nseg = 0; /* consecutive new segments */
3238 int nseg_rexmt = 0; /* retransmitted segments */
3239 int maxrexmt = 0;
3241 if (force) {
3242 uint32_t unsacked = tcp_sack_first_unsacked_len(tp);
3245 * Try to fill the first hole in the receiver's
3246 * reassemble queue.
3248 maxrexmt = howmany(unsacked, tp->t_maxseg);
3249 if (maxrexmt > tcp_force_sackrxt)
3250 maxrexmt = tcp_force_sackrxt;
3253 tp->t_rtttime = 0;
3254 pipe = tcp_sack_compute_pipe(tp);
3255 while (((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg
3256 || (force && nseg_rexmt < maxrexmt && nseg == 0)) &&
3257 (!tcp_do_smartsack || nseg < TCP_SACK_MAXBURST)) {
3258 tcp_seq old_snd_max, old_rexmt_high, nextrexmt;
3259 uint32_t sent, seglen;
3260 boolean_t rescue;
3261 int error;
3263 old_rexmt_high = tp->rexmt_high;
3264 if (!tcp_sack_nextseg(tp, &nextrexmt, &seglen, &rescue)) {
3265 tp->rexmt_high = old_rexmt_high;
3266 break;
3270 * If the next tranmission is a rescue retranmission,
3271 * we check whether we have already sent some data
3272 * (either new segments or retransmitted segments)
3273 * into the the network or not. Since the idea of rescue
3274 * retransmission is to sustain ACK clock, as long as
3275 * some segments are in the network, ACK clock will be
3276 * kept ticking.
3278 if (rescue && (nseg_rexmt > 0 || nseg > 0)) {
3279 tp->rexmt_high = old_rexmt_high;
3280 break;
3283 if (nextrexmt == tp->snd_max)
3284 ++nseg;
3285 else
3286 ++nseg_rexmt;
3287 tp->snd_nxt = nextrexmt;
3288 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3289 old_snd_max = tp->snd_max;
3290 if (nextrexmt == tp->snd_una)
3291 tcp_callout_stop(tp, tp->tt_rexmt);
3292 tp->t_flags |= TF_XMITNOW;
3293 error = tcp_output(tp);
3294 if (error != 0) {
3295 tp->rexmt_high = old_rexmt_high;
3296 break;
3298 sent = tp->snd_nxt - nextrexmt;
3299 if (sent <= 0) {
3300 tp->rexmt_high = old_rexmt_high;
3301 break;
3303 pipe += sent;
3304 tcpstat.tcps_sndsackpack++;
3305 tcpstat.tcps_sndsackbyte += sent;
3307 if (rescue) {
3308 tcpstat.tcps_sackrescue++;
3309 tp->rexmt_rescue = tp->snd_nxt;
3310 tp->sack_flags |= TSACK_F_SACKRESCUED;
3311 break;
3313 if (SEQ_LT(nextrexmt, old_snd_max) &&
3314 SEQ_LT(tp->rexmt_high, tp->snd_nxt)) {
3315 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3316 if (tcp_aggressive_rescuesack &&
3317 (tp->sack_flags & TSACK_F_SACKRESCUED) &&
3318 SEQ_LT(tp->rexmt_rescue, tp->rexmt_high)) {
3319 /* Drag RescueRxt along with HighRxt */
3320 tp->rexmt_rescue = tp->rexmt_high;
3324 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3325 tp->snd_nxt = old_snd_nxt;
3326 tp->snd_cwnd = ocwnd;
3330 * Return TRUE, if some new segments are sent
3332 static boolean_t
3333 tcp_sack_limitedxmit(struct tcpcb *tp)
3335 tcp_seq oldsndnxt = tp->snd_nxt;
3336 tcp_seq oldsndmax = tp->snd_max;
3337 u_long ocwnd = tp->snd_cwnd;
3338 uint32_t pipe, sent;
3339 boolean_t ret = FALSE;
3340 tcp_seq_diff_t cwnd_left;
3341 tcp_seq next;
3343 tp->rexmt_high = tp->snd_una - 1;
3344 pipe = tcp_sack_compute_pipe(tp);
3345 cwnd_left = (tcp_seq_diff_t)(ocwnd - pipe);
3346 if (cwnd_left < (tcp_seq_diff_t)tp->t_maxseg)
3347 return FALSE;
3349 if (tcp_do_smartsack)
3350 cwnd_left = ulmin(cwnd_left, tp->t_maxseg * TCP_SACK_MAXBURST);
3352 next = tp->snd_nxt = tp->snd_max;
3353 tp->snd_cwnd = tp->snd_nxt - tp->snd_una +
3354 rounddown(cwnd_left, tp->t_maxseg);
3356 tp->t_flags |= TF_XMITNOW;
3357 tcp_output(tp);
3359 sent = tp->snd_nxt - next;
3360 if (sent > 0) {
3361 tcpstat.tcps_sndlimited += howmany(sent, tp->t_maxseg);
3362 ret = TRUE;
3365 if (SEQ_LT(oldsndnxt, oldsndmax)) {
3366 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
3367 ("snd_una moved in other threads"));
3368 tp->snd_nxt = oldsndnxt;
3370 tp->snd_cwnd = ocwnd;
3372 if (ret && TCP_DO_NCR(tp))
3373 tcp_ncr_update_rxtthresh(tp);
3375 return ret;
3379 * Reset idle time and keep-alive timer, typically called when a valid
3380 * tcp packet is received but may also be called when FASTKEEP is set
3381 * to prevent the previous long-timeout from calculating to a drop.
3383 * Only update t_rcvtime for non-SYN packets.
3385 * Handle the case where one side thinks the connection is established
3386 * but the other side has, say, rebooted without cleaning out the
3387 * connection. The SYNs could be construed as an attack and wind
3388 * up ignored, but in case it isn't an attack we can validate the
3389 * connection by forcing a keepalive.
3391 void
3392 tcp_timer_keep_activity(struct tcpcb *tp, int thflags)
3394 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3395 if ((thflags & (TH_SYN | TH_ACK)) == TH_SYN) {
3396 tp->t_flags |= TF_KEEPALIVE;
3397 tcp_callout_reset(tp, tp->tt_keep, hz / 2,
3398 tcp_timer_keep);
3399 } else {
3400 tp->t_rcvtime = ticks;
3401 tp->t_flags &= ~TF_KEEPALIVE;
3402 tcp_callout_reset(tp, tp->tt_keep,
3403 tp->t_keepidle,
3404 tcp_timer_keep);
3409 static int
3410 tcp_rmx_msl(const struct tcpcb *tp)
3412 struct rtentry *rt;
3413 struct inpcb *inp = tp->t_inpcb;
3414 int msl;
3415 #ifdef INET6
3416 boolean_t isipv6 = INP_ISIPV6(inp);
3417 #else
3418 const boolean_t isipv6 = FALSE;
3419 #endif
3421 if (isipv6)
3422 rt = tcp_rtlookup6(&inp->inp_inc);
3423 else
3424 rt = tcp_rtlookup(&inp->inp_inc);
3425 if (rt == NULL || rt->rt_rmx.rmx_msl == 0)
3426 return tcp_msl;
3428 msl = (rt->rt_rmx.rmx_msl * hz) / 1000;
3429 if (msl == 0)
3430 msl = 1;
3432 return msl;
3435 static void
3436 tcp_established(struct tcpcb *tp)
3438 TCP_STATE_CHANGE(tp, TCPS_ESTABLISHED);
3439 tcp_callout_reset(tp, tp->tt_keep, tp->t_keepidle, tcp_timer_keep);
3441 if (tp->t_rxtsyn > 0) {
3443 * RFC6298:
3444 * "If the timer expires awaiting the ACK of a SYN segment
3445 * and the TCP implementation is using an RTO less than 3
3446 * seconds, the RTO MUST be re-initialized to 3 seconds
3447 * when data transmission begins"
3449 if (tp->t_rxtcur < TCPTV_RTOBASE3)
3450 tp->t_rxtcur = TCPTV_RTOBASE3;
3455 * Returns TRUE, if the ACK should be dropped
3457 static boolean_t
3458 tcp_recv_dupack(struct tcpcb *tp, tcp_seq th_ack, u_int to_flags)
3460 boolean_t fast_sack_rexmt = TRUE;
3462 tcpstat.tcps_rcvdupack++;
3465 * We have outstanding data (other than a window probe),
3466 * this is a completely duplicate ack (ie, window info
3467 * didn't change), the ack is the biggest we've seen and
3468 * we've seen exactly our rexmt threshhold of them, so
3469 * assume a packet has been dropped and retransmit it.
3470 * Kludge snd_nxt & the congestion window so we send only
3471 * this one packet.
3473 if (IN_FASTRECOVERY(tp)) {
3474 if (TCP_DO_SACK(tp)) {
3475 boolean_t force = FALSE;
3477 if (tp->snd_una == tp->rexmt_high &&
3478 (to_flags & (TOF_SACK | TOF_SACK_REDUNDANT)) ==
3479 TOF_SACK) {
3481 * New segments got SACKed and
3482 * no retransmit yet.
3484 force = TRUE;
3487 /* No artifical cwnd inflation. */
3488 tcp_sack_rexmt(tp, force);
3489 } else {
3491 * Dup acks mean that packets have left
3492 * the network (they're now cached at the
3493 * receiver) so bump cwnd by the amount in
3494 * the receiver to keep a constant cwnd
3495 * packets in the network.
3497 tp->snd_cwnd += tp->t_maxseg;
3498 tcp_output(tp);
3500 return TRUE;
3501 } else if (SEQ_LT(th_ack, tp->snd_recover)) {
3502 tp->t_dupacks = 0;
3503 return FALSE;
3504 } else if (tcp_ignore_redun_dsack && TCP_DO_SACK(tp) &&
3505 (to_flags & (TOF_DSACK | TOF_SACK_REDUNDANT)) ==
3506 (TOF_DSACK | TOF_SACK_REDUNDANT)) {
3508 * If the ACK carries DSACK and other SACK blocks
3509 * carry information that we have already known,
3510 * don't count this ACK as duplicate ACK. This
3511 * prevents spurious early retransmit and fast
3512 * retransmit. This also meets the requirement of
3513 * RFC3042 that new segments should not be sent if
3514 * the SACK blocks do not contain new information
3515 * (XXX we actually loosen the requirment that only
3516 * DSACK is checked here).
3518 * This kind of ACKs are usually sent after spurious
3519 * retransmit.
3521 /* Do nothing; don't change t_dupacks */
3522 return TRUE;
3523 } else if (tp->t_dupacks == 0 && TCP_DO_NCR(tp)) {
3524 tcp_ncr_update_rxtthresh(tp);
3527 if (++tp->t_dupacks == tp->t_rxtthresh) {
3528 tcp_seq old_snd_nxt;
3529 u_int win;
3531 fastretransmit:
3532 if (tcp_do_eifel_detect && (tp->t_flags & TF_RCVD_TSTMP)) {
3533 tcp_save_congestion_state(tp);
3534 tp->rxt_flags |= TRXT_F_FASTREXMT;
3537 * We know we're losing at the current window size,
3538 * so do congestion avoidance: set ssthresh to half
3539 * the current window and pull our congestion window
3540 * back to the new ssthresh.
3542 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;
3543 if (win < 2)
3544 win = 2;
3545 tp->snd_ssthresh = win * tp->t_maxseg;
3546 ENTER_FASTRECOVERY(tp);
3547 tp->snd_recover = tp->snd_max;
3548 tcp_callout_stop(tp, tp->tt_rexmt);
3549 tp->t_rtttime = 0;
3550 old_snd_nxt = tp->snd_nxt;
3551 tp->snd_nxt = th_ack;
3552 if (TCP_DO_SACK(tp)) {
3553 uint32_t rxtlen;
3555 rxtlen = tcp_sack_first_unsacked_len(tp);
3556 if (rxtlen > tp->t_maxseg)
3557 rxtlen = tp->t_maxseg;
3558 tp->snd_cwnd = rxtlen;
3559 } else {
3560 tp->snd_cwnd = tp->t_maxseg;
3562 tcp_output(tp);
3563 ++tcpstat.tcps_sndfastrexmit;
3564 tp->snd_cwnd = tp->snd_ssthresh;
3565 tp->rexmt_high = tp->snd_nxt;
3566 tp->sack_flags &= ~TSACK_F_SACKRESCUED;
3567 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3568 tp->snd_nxt = old_snd_nxt;
3569 KASSERT(tp->snd_limited <= 2, ("tp->snd_limited too big"));
3570 if (TCP_DO_SACK(tp)) {
3571 if (fast_sack_rexmt)
3572 tcp_sack_rexmt(tp, FALSE);
3573 } else {
3574 tp->snd_cwnd += tp->t_maxseg *
3575 (tp->t_dupacks - tp->snd_limited);
3577 } else if ((tcp_do_rfc6675 && TCP_DO_SACK(tp)) || TCP_DO_NCR(tp)) {
3579 * The RFC6675 recommends to reduce the byte threshold,
3580 * and enter fast retransmit if IsLost(snd_una). However,
3581 * if we use IsLost(snd_una) based fast retransmit here,
3582 * segments reordering will cause spurious retransmit. So
3583 * we defer the IsLost(snd_una) based fast retransmit until
3584 * the extended limited transmit can't send any segments and
3585 * early retransmit can't be done.
3587 if (tcp_rfc6675_rxt && tcp_do_rfc6675 &&
3588 tcp_sack_islost(&tp->scb, tp->snd_una))
3589 goto fastretransmit;
3591 if (tcp_do_limitedtransmit || TCP_DO_NCR(tp)) {
3592 if (!tcp_sack_limitedxmit(tp)) {
3593 /* outstanding data */
3594 uint32_t ownd = tp->snd_max - tp->snd_una;
3596 if (need_early_retransmit(tp, ownd)) {
3597 ++tcpstat.tcps_sndearlyrexmit;
3598 tp->rxt_flags |= TRXT_F_EARLYREXMT;
3599 goto fastretransmit;
3600 } else if (tcp_do_rfc6675 &&
3601 tcp_sack_islost(&tp->scb, tp->snd_una)) {
3602 fast_sack_rexmt = FALSE;
3603 goto fastretransmit;
3607 } else if (tcp_do_limitedtransmit) {
3608 u_long oldcwnd = tp->snd_cwnd;
3609 tcp_seq oldsndmax = tp->snd_max;
3610 tcp_seq oldsndnxt = tp->snd_nxt;
3611 /* outstanding data */
3612 uint32_t ownd = tp->snd_max - tp->snd_una;
3613 u_int sent;
3615 KASSERT(tp->t_dupacks == 1 || tp->t_dupacks == 2,
3616 ("dupacks not 1 or 2"));
3617 if (tp->t_dupacks == 1)
3618 tp->snd_limited = 0;
3619 tp->snd_nxt = tp->snd_max;
3620 tp->snd_cwnd = ownd +
3621 (tp->t_dupacks - tp->snd_limited) * tp->t_maxseg;
3622 tp->t_flags |= TF_XMITNOW;
3623 tcp_output(tp);
3625 if (SEQ_LT(oldsndnxt, oldsndmax)) {
3626 KASSERT(SEQ_GEQ(oldsndnxt, tp->snd_una),
3627 ("snd_una moved in other threads"));
3628 tp->snd_nxt = oldsndnxt;
3630 tp->snd_cwnd = oldcwnd;
3631 sent = tp->snd_max - oldsndmax;
3632 if (sent > tp->t_maxseg) {
3633 KASSERT((tp->t_dupacks == 2 && tp->snd_limited == 0) ||
3634 (sent == tp->t_maxseg + 1 &&
3635 (tp->t_flags & TF_SENTFIN)),
3636 ("sent too much"));
3637 KASSERT(sent <= tp->t_maxseg * 2,
3638 ("sent too many segments"));
3639 tp->snd_limited = 2;
3640 tcpstat.tcps_sndlimited += 2;
3641 } else if (sent > 0) {
3642 ++tp->snd_limited;
3643 ++tcpstat.tcps_sndlimited;
3644 } else if (need_early_retransmit(tp, ownd)) {
3645 ++tcpstat.tcps_sndearlyrexmit;
3646 tp->rxt_flags |= TRXT_F_EARLYREXMT;
3647 goto fastretransmit;
3650 return TRUE;