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