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