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