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