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