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