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