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