Split pcm into the generic framework (pcm) and the sound cards (snd).
[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.58 2005/03/23 08:02:46 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                                 tp->snd_nxt = tp->snd_max;
1993                                 tp->snd_cwnd = ownd +
1994                                     (tp->t_dupacks - tp->snd_limited) *
1995                                     tp->t_maxseg;
1996                                 tcp_output(tp);
1997                                 if (SEQ_LT(oldsndnxt, oldsndmax))
1998                                         tp->snd_nxt = oldsndnxt;
1999                                 tp->snd_cwnd = oldcwnd;
2000                                 sent = tp->snd_max - oldsndmax;
2001                                 if (sent > tp->t_maxseg) {
2002                                         KASSERT((tp->t_dupacks == 2 &&
2003                                                  tp->snd_limited == 0) ||
2004                                                 (sent == tp->t_maxseg + 1 &&
2005                                                  tp->t_flags & TF_SENTFIN),
2006                                             ("sent too much"));
2007                                         KASSERT(sent <= tp->t_maxseg * 2,
2008                                             ("sent too many segments"));
2009                                         tp->snd_limited = 2;
2010                                         tcpstat.tcps_sndlimited += 2;
2011                                 } else if (sent > 0) {
2012                                         ++tp->snd_limited;
2013                                         ++tcpstat.tcps_sndlimited;
2014                                 } else if (tcp_do_early_retransmit &&
2015                                     (tcp_do_eifel_detect &&
2016                                      (tp->t_flags & TF_RCVD_TSTMP)) &&
2017                                     ownd < 4 * tp->t_maxseg &&
2018                                     tp->t_dupacks + 1 >=
2019                                       iceildiv(ownd, tp->t_maxseg) &&
2020                                     (!TCP_DO_SACK(tp) ||
2021                                      ownd <= tp->t_maxseg ||
2022                                      tcp_sack_has_sacked(&tp->scb,
2023                                                         ownd - tp->t_maxseg))) {
2024                                         ++tcpstat.tcps_sndearlyrexmit;
2025                                         tp->t_flags |= TF_EARLYREXMT;
2026                                         goto fastretransmit;
2027                                 }
2028                         }
2029                         goto drop;
2030                 }
2031
2032                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
2033                 tp->t_dupacks = 0;
2034                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2035                         /*
2036                          * Detected optimistic ACK attack.
2037                          * Force slow-start to de-synchronize attack.
2038                          */
2039                         tp->snd_cwnd = tp->t_maxseg;
2040
2041                         tcpstat.tcps_rcvacktoomuch++;
2042                         goto dropafterack;
2043                 }
2044                 /*
2045                  * If we reach this point, ACK is not a duplicate,
2046                  *     i.e., it ACKs something we sent.
2047                  */
2048                 if (tp->t_flags & TF_NEEDSYN) {
2049                         /*
2050                          * T/TCP: Connection was half-synchronized, and our
2051                          * SYN has been ACK'd (so connection is now fully
2052                          * synchronized).  Go to non-starred state,
2053                          * increment snd_una for ACK of SYN, and check if
2054                          * we can do window scaling.
2055                          */
2056                         tp->t_flags &= ~TF_NEEDSYN;
2057                         tp->snd_una++;
2058                         /* Do window scaling? */
2059                         if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2060                             (TF_RCVD_SCALE | TF_REQ_SCALE)) {
2061                                 tp->snd_scale = tp->requested_s_scale;
2062                                 tp->rcv_scale = tp->request_r_scale;
2063                         }
2064                 }
2065
2066 process_ACK:
2067                 acked = th->th_ack - tp->snd_una;
2068                 tcpstat.tcps_rcvackpack++;
2069                 tcpstat.tcps_rcvackbyte += acked;
2070
2071                 if (tcp_do_eifel_detect && acked > 0 &&
2072                     (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
2073                     (tp->t_flags & TF_FIRSTACCACK)) {
2074                         /* Eifel detection applicable. */
2075                         if (to.to_tsecr < tp->t_rexmtTS) {
2076                                 ++tcpstat.tcps_eifeldetected;
2077                                 tcp_revert_congestion_state(tp);
2078                                 if (tp->t_rxtshift == 1 &&
2079                                     ticks >= tp->t_badrxtwin)
2080                                         ++tcpstat.tcps_rttcantdetect;
2081                         }
2082                 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2083                         /*
2084                          * If we just performed our first retransmit,
2085                          * and the ACK arrives within our recovery window,
2086                          * then it was a mistake to do the retransmit
2087                          * in the first place.  Recover our original cwnd
2088                          * and ssthresh, and proceed to transmit where we
2089                          * left off.
2090                          */
2091                         tcp_revert_congestion_state(tp);
2092                         ++tcpstat.tcps_rttdetected;
2093                 }
2094
2095                 /*
2096                  * If we have a timestamp reply, update smoothed
2097                  * round trip time.  If no timestamp is present but
2098                  * transmit timer is running and timed sequence
2099                  * number was acked, update smoothed round trip time.
2100                  * Since we now have an rtt measurement, cancel the
2101                  * timer backoff (cf., Phil Karn's retransmit alg.).
2102                  * Recompute the initial retransmit timer.
2103                  *
2104                  * Some machines (certain windows boxes) send broken
2105                  * timestamp replies during the SYN+ACK phase, ignore
2106                  * timestamps of 0.
2107                  */
2108                 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
2109                         tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2110                 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2111                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2112                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2113
2114                 /*
2115                  * If no data (only SYN) was ACK'd,
2116                  *    skip rest of ACK processing.
2117                  */
2118                 if (acked == 0)
2119                         goto step6;
2120
2121                 /* Stop looking for an acceptable ACK since one was received. */
2122                 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
2123
2124                 if (acked > so->so_snd.sb_cc) {
2125                         tp->snd_wnd -= so->so_snd.sb_cc;
2126                         sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2127                         ourfinisacked = TRUE;
2128                 } else {
2129                         sbdrop(&so->so_snd, acked);
2130                         tp->snd_wnd -= acked;
2131                         ourfinisacked = FALSE;
2132                 }
2133                 sowwakeup(so);
2134
2135                 /*
2136                  * Update window information.
2137                  * Don't look at window if no ACK:
2138                  * TAC's send garbage on first SYN.
2139                  */
2140                 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2141                     (tp->snd_wl1 == th->th_seq &&
2142                      (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2143                       (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2144                         /* keep track of pure window updates */
2145                         if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2146                             tiwin > tp->snd_wnd)
2147                                 tcpstat.tcps_rcvwinupd++;
2148                         tp->snd_wnd = tiwin;
2149                         tp->snd_wl1 = th->th_seq;
2150                         tp->snd_wl2 = th->th_ack;
2151                         if (tp->snd_wnd > tp->max_sndwnd)
2152                                 tp->max_sndwnd = tp->snd_wnd;
2153                         needoutput = TRUE;
2154                 }
2155
2156                 tp->snd_una = th->th_ack;
2157                 if (TCP_DO_SACK(tp))
2158                         tcp_sack_update_scoreboard(tp, &to);
2159                 if (IN_FASTRECOVERY(tp)) {
2160                         if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2161                                 EXIT_FASTRECOVERY(tp);
2162                                 needoutput = TRUE;
2163                                 /*
2164                                  * If the congestion window was inflated
2165                                  * to account for the other side's
2166                                  * cached packets, retract it.
2167                                  *
2168                                  * Window inflation should have left us
2169                                  * with approximately snd_ssthresh outstanding
2170                                  * data.  But, in case we would be inclined
2171                                  * to send a burst, better do it using
2172                                  * slow start.
2173                                  */
2174                                 if (!TCP_DO_SACK(tp))
2175                                         tp->snd_cwnd = tp->snd_ssthresh;
2176
2177                                 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2178                                            tp->snd_max + 2 * tp->t_maxseg))
2179                                         tp->snd_cwnd =
2180                                             (tp->snd_max - tp->snd_una) +
2181                                             2 * tp->t_maxseg;
2182                         } else {
2183                                 if (TCP_DO_SACK(tp)) {
2184                                         tp->snd_max_rexmt = tp->snd_max;
2185                                         tcp_sack_rexmt(tp, th);
2186                                 } else {
2187                                         tcp_newreno_partial_ack(tp, th, acked);
2188                                 }
2189                                 needoutput = FALSE;
2190                         }
2191                 } else {
2192                         /*
2193                          * When new data is acked, open the congestion window.
2194                          * If the window gives us less than ssthresh packets
2195                          * in flight, open exponentially (maxseg per packet).
2196                          * Otherwise open linearly: maxseg per window
2197                          * (maxseg^2 / cwnd per packet).
2198                          */
2199                         u_int cw = tp->snd_cwnd;
2200                         u_int incr;
2201
2202                         if (cw > tp->snd_ssthresh)
2203                                 incr = tp->t_maxseg * tp->t_maxseg / cw;
2204                         else
2205                                 incr = tp->t_maxseg;
2206                         tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2207                         tp->snd_recover = th->th_ack - 1;
2208                 }
2209                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2210                         tp->snd_nxt = tp->snd_una;
2211
2212                 /*
2213                  * If all outstanding data is acked, stop retransmit
2214                  * timer and remember to restart (more output or persist).
2215                  * If there is more data to be acked, restart retransmit
2216                  * timer, using current (possibly backed-off) value.
2217                  */
2218                 if (th->th_ack == tp->snd_max) {
2219                         callout_stop(tp->tt_rexmt);
2220                         needoutput = TRUE;
2221                 } else if (!callout_active(tp->tt_persist))
2222                         callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2223                                       tcp_timer_rexmt, tp);
2224
2225                 switch (tp->t_state) {
2226                 /*
2227                  * In FIN_WAIT_1 STATE in addition to the processing
2228                  * for the ESTABLISHED state if our FIN is now acknowledged
2229                  * then enter FIN_WAIT_2.
2230                  */
2231                 case TCPS_FIN_WAIT_1:
2232                         if (ourfinisacked) {
2233                                 /*
2234                                  * If we can't receive any more
2235                                  * data, then closing user can proceed.
2236                                  * Starting the timer is contrary to the
2237                                  * specification, but if we don't get a FIN
2238                                  * we'll hang forever.
2239                                  */
2240                                 if (so->so_state & SS_CANTRCVMORE) {
2241                                         soisdisconnected(so);
2242                                         callout_reset(tp->tt_2msl, tcp_maxidle,
2243                                                       tcp_timer_2msl, tp);
2244                                 }
2245                                 tp->t_state = TCPS_FIN_WAIT_2;
2246                         }
2247                         break;
2248
2249                 /*
2250                  * In CLOSING STATE in addition to the processing for
2251                  * the ESTABLISHED state if the ACK acknowledges our FIN
2252                  * then enter the TIME-WAIT state, otherwise ignore
2253                  * the segment.
2254                  */
2255                 case TCPS_CLOSING:
2256                         if (ourfinisacked) {
2257                                 tp->t_state = TCPS_TIME_WAIT;
2258                                 tcp_canceltimers(tp);
2259                                 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2260                                 if (tp->cc_recv != 0 &&
2261                                     (ticks - tp->t_starttime) < tcp_msl)
2262                                         callout_reset(tp->tt_2msl,
2263                                             tp->t_rxtcur * TCPTV_TWTRUNC,
2264                                             tcp_timer_2msl, tp);
2265                                 else
2266                                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2267                                             tcp_timer_2msl, tp);
2268                                 soisdisconnected(so);
2269                         }
2270                         break;
2271
2272                 /*
2273                  * In LAST_ACK, we may still be waiting for data to drain
2274                  * and/or to be acked, as well as for the ack of our FIN.
2275                  * If our FIN is now acknowledged, delete the TCB,
2276                  * enter the closed state and return.
2277                  */
2278                 case TCPS_LAST_ACK:
2279                         if (ourfinisacked) {
2280                                 tp = tcp_close(tp);
2281                                 goto drop;
2282                         }
2283                         break;
2284
2285                 /*
2286                  * In TIME_WAIT state the only thing that should arrive
2287                  * is a retransmission of the remote FIN.  Acknowledge
2288                  * it and restart the finack timer.
2289                  */
2290                 case TCPS_TIME_WAIT:
2291                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2292                                       tcp_timer_2msl, tp);
2293                         goto dropafterack;
2294                 }
2295         }
2296
2297 step6:
2298         /*
2299          * Update window information.
2300          * Don't look at window if no ACK: TAC's send garbage on first SYN.
2301          */
2302         if ((thflags & TH_ACK) &&
2303             acceptable_window_update(tp, th, tiwin)) {
2304                 /* keep track of pure window updates */
2305                 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2306                     tiwin > tp->snd_wnd)
2307                         tcpstat.tcps_rcvwinupd++;
2308                 tp->snd_wnd = tiwin;
2309                 tp->snd_wl1 = th->th_seq;
2310                 tp->snd_wl2 = th->th_ack;
2311                 if (tp->snd_wnd > tp->max_sndwnd)
2312                         tp->max_sndwnd = tp->snd_wnd;
2313                 needoutput = TRUE;
2314         }
2315
2316         /*
2317          * Process segments with URG.
2318          */
2319         if ((thflags & TH_URG) && th->th_urp &&
2320             !TCPS_HAVERCVDFIN(tp->t_state)) {
2321                 /*
2322                  * This is a kludge, but if we receive and accept
2323                  * random urgent pointers, we'll crash in
2324                  * soreceive.  It's hard to imagine someone
2325                  * actually wanting to send this much urgent data.
2326                  */
2327                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2328                         th->th_urp = 0;                 /* XXX */
2329                         thflags &= ~TH_URG;             /* XXX */
2330                         goto dodata;                    /* XXX */
2331                 }
2332                 /*
2333                  * If this segment advances the known urgent pointer,
2334                  * then mark the data stream.  This should not happen
2335                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2336                  * a FIN has been received from the remote side.
2337                  * In these states we ignore the URG.
2338                  *
2339                  * According to RFC961 (Assigned Protocols),
2340                  * the urgent pointer points to the last octet
2341                  * of urgent data.  We continue, however,
2342                  * to consider it to indicate the first octet
2343                  * of data past the urgent section as the original
2344                  * spec states (in one of two places).
2345                  */
2346                 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
2347                         tp->rcv_up = th->th_seq + th->th_urp;
2348                         so->so_oobmark = so->so_rcv.sb_cc +
2349                             (tp->rcv_up - tp->rcv_nxt) - 1;
2350                         if (so->so_oobmark == 0)
2351                                 so->so_state |= SS_RCVATMARK;
2352                         sohasoutofband(so);
2353                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2354                 }
2355                 /*
2356                  * Remove out of band data so doesn't get presented to user.
2357                  * This can happen independent of advancing the URG pointer,
2358                  * but if two URG's are pending at once, some out-of-band
2359                  * data may creep in... ick.
2360                  */
2361                 if (th->th_urp <= (u_long)tlen &&
2362                     !(so->so_options & SO_OOBINLINE)) {
2363                         /* hdr drop is delayed */
2364                         tcp_pulloutofband(so, th, m, drop_hdrlen);
2365                 }
2366         } else {
2367                 /*
2368                  * If no out of band data is expected,
2369                  * pull receive urgent pointer along
2370                  * with the receive window.
2371                  */
2372                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2373                         tp->rcv_up = tp->rcv_nxt;
2374         }
2375
2376 dodata:                                                 /* XXX */
2377         /*
2378          * Process the segment text, merging it into the TCP sequencing queue,
2379          * and arranging for acknowledgment of receipt if necessary.
2380          * This process logically involves adjusting tp->rcv_wnd as data
2381          * is presented to the user (this happens in tcp_usrreq.c,
2382          * case PRU_RCVD).  If a FIN has already been received on this
2383          * connection then we just ignore the text.
2384          */
2385         if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
2386                 m_adj(m, drop_hdrlen);  /* delayed header drop */
2387                 /*
2388                  * Insert segment which includes th into TCP reassembly queue
2389                  * with control block tp.  Set thflags to whether reassembly now
2390                  * includes a segment with FIN.  This handles the common case
2391                  * inline (segment is the next to be received on an established
2392                  * connection, and the queue is empty), avoiding linkage into
2393                  * and removal from the queue and repetition of various
2394                  * conversions.
2395                  * Set DELACK for segments received in order, but ack
2396                  * immediately when segments are out of order (so
2397                  * fast retransmit can work).
2398                  */
2399                 if (th->th_seq == tp->rcv_nxt &&
2400                     LIST_EMPTY(&tp->t_segq) &&
2401                     TCPS_HAVEESTABLISHED(tp->t_state)) {
2402                         if (DELAY_ACK(tp))
2403                                 callout_reset(tp->tt_delack, tcp_delacktime,
2404                                               tcp_timer_delack, tp);
2405                         else
2406                                 tp->t_flags |= TF_ACKNOW;
2407                         tp->rcv_nxt += tlen;
2408                         thflags = th->th_flags & TH_FIN;
2409                         tcpstat.tcps_rcvpack++;
2410                         tcpstat.tcps_rcvbyte += tlen;
2411                         ND6_HINT(tp);
2412                         if (so->so_state & SS_CANTRCVMORE)
2413                                 m_freem(m);
2414                         else
2415                                 sbappendstream(&so->so_rcv, m);
2416                         sorwakeup(so);
2417                 } else {
2418                         if (!(tp->t_flags & TF_DUPSEG)) {
2419                                 /* Initialize SACK report block. */
2420                                 tp->reportblk.rblk_start = th->th_seq;
2421                                 tp->reportblk.rblk_end = th->th_seq + tlen +
2422                                     ((thflags & TH_FIN) != 0);
2423                         }
2424                         thflags = tcp_reass(tp, th, &tlen, m);
2425                         tp->t_flags |= TF_ACKNOW;
2426                 }
2427
2428                 /*
2429                  * Note the amount of data that peer has sent into
2430                  * our window, in order to estimate the sender's
2431                  * buffer size.
2432                  */
2433                 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2434         } else {
2435                 m_freem(m);
2436                 thflags &= ~TH_FIN;
2437         }
2438
2439         /*
2440          * If FIN is received ACK the FIN and let the user know
2441          * that the connection is closing.
2442          */
2443         if (thflags & TH_FIN) {
2444                 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
2445                         socantrcvmore(so);
2446                         /*
2447                          * If connection is half-synchronized
2448                          * (ie NEEDSYN flag on) then delay ACK,
2449                          * so it may be piggybacked when SYN is sent.
2450                          * Otherwise, since we received a FIN then no
2451                          * more input can be expected, send ACK now.
2452                          */
2453                         if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2454                                 callout_reset(tp->tt_delack, tcp_delacktime,
2455                                     tcp_timer_delack, tp);
2456                         else
2457                                 tp->t_flags |= TF_ACKNOW;
2458                         tp->rcv_nxt++;
2459                 }
2460
2461                 switch (tp->t_state) {
2462                 /*
2463                  * In SYN_RECEIVED and ESTABLISHED STATES
2464                  * enter the CLOSE_WAIT state.
2465                  */
2466                 case TCPS_SYN_RECEIVED:
2467                         tp->t_starttime = ticks;
2468                         /*FALLTHROUGH*/
2469                 case TCPS_ESTABLISHED:
2470                         tp->t_state = TCPS_CLOSE_WAIT;
2471                         break;
2472
2473                 /*
2474                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
2475                  * enter the CLOSING state.
2476                  */
2477                 case TCPS_FIN_WAIT_1:
2478                         tp->t_state = TCPS_CLOSING;
2479                         break;
2480
2481                 /*
2482                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
2483                  * starting the time-wait timer, turning off the other
2484                  * standard timers.
2485                  */
2486                 case TCPS_FIN_WAIT_2:
2487                         tp->t_state = TCPS_TIME_WAIT;
2488                         tcp_canceltimers(tp);
2489                         /* Shorten TIME_WAIT [RFC-1644, p.28] */
2490                         if (tp->cc_recv != 0 &&
2491                             (ticks - tp->t_starttime) < tcp_msl) {
2492                                 callout_reset(tp->tt_2msl,
2493                                               tp->t_rxtcur * TCPTV_TWTRUNC,
2494                                               tcp_timer_2msl, tp);
2495                                 /* For transaction client, force ACK now. */
2496                                 tp->t_flags |= TF_ACKNOW;
2497                         }
2498                         else
2499                                 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2500                                               tcp_timer_2msl, tp);
2501                         soisdisconnected(so);
2502                         break;
2503
2504                 /*
2505                  * In TIME_WAIT state restart the 2 MSL time_wait timer.
2506                  */
2507                 case TCPS_TIME_WAIT:
2508                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2509                                       tcp_timer_2msl, tp);
2510                         break;
2511                 }
2512         }
2513
2514 #ifdef TCPDEBUG
2515         if (so->so_options & SO_DEBUG)
2516                 tcp_trace(TA_INPUT, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2517 #endif
2518
2519         /*
2520          * Return any desired output.
2521          */
2522         if (needoutput || (tp->t_flags & TF_ACKNOW))
2523                 tcp_output(tp);
2524         return;
2525
2526 dropafterack:
2527         /*
2528          * Generate an ACK dropping incoming segment if it occupies
2529          * sequence space, where the ACK reflects our state.
2530          *
2531          * We can now skip the test for the RST flag since all
2532          * paths to this code happen after packets containing
2533          * RST have been dropped.
2534          *
2535          * In the SYN-RECEIVED state, don't send an ACK unless the
2536          * segment we received passes the SYN-RECEIVED ACK test.
2537          * If it fails send a RST.  This breaks the loop in the
2538          * "LAND" DoS attack, and also prevents an ACK storm
2539          * between two listening ports that have been sent forged
2540          * SYN segments, each with the source address of the other.
2541          */
2542         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2543             (SEQ_GT(tp->snd_una, th->th_ack) ||
2544              SEQ_GT(th->th_ack, tp->snd_max)) ) {
2545                 rstreason = BANDLIM_RST_OPENPORT;
2546                 goto dropwithreset;
2547         }
2548 #ifdef TCPDEBUG
2549         if (so->so_options & SO_DEBUG)
2550                 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2551 #endif
2552         m_freem(m);
2553         tp->t_flags |= TF_ACKNOW;
2554         tcp_output(tp);
2555         return;
2556
2557 dropwithreset:
2558         /*
2559          * Generate a RST, dropping incoming segment.
2560          * Make ACK acceptable to originator of segment.
2561          * Don't bother to respond if destination was broadcast/multicast.
2562          */
2563         if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
2564                 goto drop;
2565         if (isipv6) {
2566                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2567                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2568                         goto drop;
2569         } else {
2570                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2571                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2572                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2573                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2574                         goto drop;
2575         }
2576         /* IPv6 anycast check is done at tcp6_input() */
2577
2578         /*
2579          * Perform bandwidth limiting.
2580          */
2581 #ifdef ICMP_BANDLIM
2582         if (badport_bandlim(rstreason) < 0)
2583                 goto drop;
2584 #endif
2585
2586 #ifdef TCPDEBUG
2587         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2588                 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2589 #endif
2590         if (thflags & TH_ACK)
2591                 /* mtod() below is safe as long as hdr dropping is delayed */
2592                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2593                             TH_RST);
2594         else {
2595                 if (thflags & TH_SYN)
2596                         tlen++;
2597                 /* mtod() below is safe as long as hdr dropping is delayed */
2598                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2599                             (tcp_seq)0, TH_RST | TH_ACK);
2600         }
2601         return;
2602
2603 drop:
2604         /*
2605          * Drop space held by incoming segment and return.
2606          */
2607 #ifdef TCPDEBUG
2608         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2609                 tcp_trace(TA_DROP, ostate, tp, tcp_saveipgen, &tcp_savetcp, 0);
2610 #endif
2611         m_freem(m);
2612         return;
2613 }
2614
2615 /*
2616  * Parse TCP options and place in tcpopt.
2617  */
2618 static void
2619 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
2620 {
2621         int opt, optlen, i;
2622
2623         to->to_flags = 0;
2624         for (; cnt > 0; cnt -= optlen, cp += optlen) {
2625                 opt = cp[0];
2626                 if (opt == TCPOPT_EOL)
2627                         break;
2628                 if (opt == TCPOPT_NOP)
2629                         optlen = 1;
2630                 else {
2631                         if (cnt < 2)
2632                                 break;
2633                         optlen = cp[1];
2634                         if (optlen < 2 || optlen > cnt)
2635                                 break;
2636                 }
2637                 switch (opt) {
2638                 case TCPOPT_MAXSEG:
2639                         if (optlen != TCPOLEN_MAXSEG)
2640                                 continue;
2641                         if (!is_syn)
2642                                 continue;
2643                         to->to_flags |= TOF_MSS;
2644                         bcopy(cp + 2, &to->to_mss, sizeof to->to_mss);
2645                         to->to_mss = ntohs(to->to_mss);
2646                         break;
2647                 case TCPOPT_WINDOW:
2648                         if (optlen != TCPOLEN_WINDOW)
2649                                 continue;
2650                         if (!is_syn)
2651                                 continue;
2652                         to->to_flags |= TOF_SCALE;
2653                         to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2654                         break;
2655                 case TCPOPT_TIMESTAMP:
2656                         if (optlen != TCPOLEN_TIMESTAMP)
2657                                 continue;
2658                         to->to_flags |= TOF_TS;
2659                         bcopy(cp + 2, &to->to_tsval, sizeof to->to_tsval);
2660                         to->to_tsval = ntohl(to->to_tsval);
2661                         bcopy(cp + 6, &to->to_tsecr, sizeof to->to_tsecr);
2662                         to->to_tsecr = ntohl(to->to_tsecr);
2663                         break;
2664                 case TCPOPT_CC:
2665                         if (optlen != TCPOLEN_CC)
2666                                 continue;
2667                         to->to_flags |= TOF_CC;
2668                         bcopy(cp + 2, &to->to_cc, sizeof to->to_cc);
2669                         to->to_cc = ntohl(to->to_cc);
2670                         break;
2671                 case TCPOPT_CCNEW:
2672                         if (optlen != TCPOLEN_CC)
2673                                 continue;
2674                         if (!is_syn)
2675                                 continue;
2676                         to->to_flags |= TOF_CCNEW;
2677                         bcopy(cp + 2, &to->to_cc, sizeof to->to_cc);
2678                         to->to_cc = ntohl(to->to_cc);
2679                         break;
2680                 case TCPOPT_CCECHO:
2681                         if (optlen != TCPOLEN_CC)
2682                                 continue;
2683                         if (!is_syn)
2684                                 continue;
2685                         to->to_flags |= TOF_CCECHO;
2686                         bcopy(cp + 2, &to->to_ccecho, sizeof to->to_ccecho);
2687                         to->to_ccecho = ntohl(to->to_ccecho);
2688                         break;
2689                 case TCPOPT_SACK_PERMITTED:
2690                         if (optlen != TCPOLEN_SACK_PERMITTED)
2691                                 continue;
2692                         if (!is_syn)
2693                                 continue;
2694                         to->to_flags |= TOF_SACK_PERMITTED;
2695                         break;
2696                 case TCPOPT_SACK:
2697                         if ((optlen - 2) & 0x07)        /* not multiple of 8 */
2698                                 continue;
2699                         to->to_nsackblocks = (optlen - 2) / 8;
2700                         to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2701                         to->to_flags |= TOF_SACK;
2702                         for (i = 0; i < to->to_nsackblocks; i++) {
2703                                 struct raw_sackblock *r = &to->to_sackblocks[i];
2704
2705                                 r->rblk_start = ntohl(r->rblk_start);
2706                                 r->rblk_end = ntohl(r->rblk_end);
2707                         }
2708                         break;
2709                 default:
2710                         continue;
2711                 }
2712         }
2713 }
2714
2715 /*
2716  * Pull out of band byte out of a segment so
2717  * it doesn't appear in the user's data queue.
2718  * It is still reflected in the segment length for
2719  * sequencing purposes.
2720  * "off" is the delayed to be dropped hdrlen.
2721  */
2722 static void
2723 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
2724 {
2725         int cnt = off + th->th_urp - 1;
2726
2727         while (cnt >= 0) {
2728                 if (m->m_len > cnt) {
2729                         char *cp = mtod(m, caddr_t) + cnt;
2730                         struct tcpcb *tp = sototcpcb(so);
2731
2732                         tp->t_iobc = *cp;
2733                         tp->t_oobflags |= TCPOOB_HAVEDATA;
2734                         bcopy(cp + 1, cp, m->m_len - cnt - 1);
2735                         m->m_len--;
2736                         if (m->m_flags & M_PKTHDR)
2737                                 m->m_pkthdr.len--;
2738                         return;
2739                 }
2740                 cnt -= m->m_len;
2741                 m = m->m_next;
2742                 if (m == 0)
2743                         break;
2744         }
2745         panic("tcp_pulloutofband");
2746 }
2747
2748 /*
2749  * Collect new round-trip time estimate
2750  * and update averages and current timeout.
2751  */
2752 static void
2753 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2754 {
2755         int delta;
2756
2757         tcpstat.tcps_rttupdated++;
2758         tp->t_rttupdated++;
2759         if (tp->t_srtt != 0) {
2760                 /*
2761                  * srtt is stored as fixed point with 5 bits after the
2762                  * binary point (i.e., scaled by 8).  The following magic
2763                  * is equivalent to the smoothing algorithm in rfc793 with
2764                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2765                  * point).  Adjust rtt to origin 0.
2766                  */
2767                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2768                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2769
2770                 if ((tp->t_srtt += delta) <= 0)
2771                         tp->t_srtt = 1;
2772
2773                 /*
2774                  * We accumulate a smoothed rtt variance (actually, a
2775                  * smoothed mean difference), then set the retransmit
2776                  * timer to smoothed rtt + 4 times the smoothed variance.
2777                  * rttvar is stored as fixed point with 4 bits after the
2778                  * binary point (scaled by 16).  The following is
2779                  * equivalent to rfc793 smoothing with an alpha of .75
2780                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2781                  * rfc793's wired-in beta.
2782                  */
2783                 if (delta < 0)
2784                         delta = -delta;
2785                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2786                 if ((tp->t_rttvar += delta) <= 0)
2787                         tp->t_rttvar = 1;
2788                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2789                         tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2790         } else {
2791                 /*
2792                  * No rtt measurement yet - use the unsmoothed rtt.
2793                  * Set the variance to half the rtt (so our first
2794                  * retransmit happens at 3*rtt).
2795                  */
2796                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2797                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2798                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2799         }
2800         tp->t_rtttime = 0;
2801         tp->t_rxtshift = 0;
2802
2803         /*
2804          * the retransmit should happen at rtt + 4 * rttvar.
2805          * Because of the way we do the smoothing, srtt and rttvar
2806          * will each average +1/2 tick of bias.  When we compute
2807          * the retransmit timer, we want 1/2 tick of rounding and
2808          * 1 extra tick because of +-1/2 tick uncertainty in the
2809          * firing of the timer.  The bias will give us exactly the
2810          * 1.5 tick we need.  But, because the bias is
2811          * statistical, we have to test that we don't drop below
2812          * the minimum feasible timer (which is 2 ticks).
2813          */
2814         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2815                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2816
2817         /*
2818          * We received an ack for a packet that wasn't retransmitted;
2819          * it is probably safe to discard any error indications we've
2820          * received recently.  This isn't quite right, but close enough
2821          * for now (a route might have failed after we sent a segment,
2822          * and the return path might not be symmetrical).
2823          */
2824         tp->t_softerror = 0;
2825 }
2826
2827 /*
2828  * Determine a reasonable value for maxseg size.
2829  * If the route is known, check route for mtu.
2830  * If none, use an mss that can be handled on the outgoing
2831  * interface without forcing IP to fragment; if bigger than
2832  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2833  * to utilize large mbufs.  If no route is found, route has no mtu,
2834  * or the destination isn't local, use a default, hopefully conservative
2835  * size (usually 512 or the default IP max size, but no more than the mtu
2836  * of the interface), as we can't discover anything about intervening
2837  * gateways or networks.  We also initialize the congestion/slow start
2838  * window to be a single segment if the destination isn't local.
2839  * While looking at the routing entry, we also initialize other path-dependent
2840  * parameters from pre-set or cached values in the routing entry.
2841  *
2842  * Also take into account the space needed for options that we
2843  * send regularly.  Make maxseg shorter by that amount to assure
2844  * that we can send maxseg amount of data even when the options
2845  * are present.  Store the upper limit of the length of options plus
2846  * data in maxopd.
2847  *
2848  * NOTE that this routine is only called when we process an incoming
2849  * segment, for outgoing segments only tcp_mssopt is called.
2850  *
2851  * In case of T/TCP, we call this routine during implicit connection
2852  * setup as well (offer = -1), to initialize maxseg from the cached
2853  * MSS of our peer.
2854  */
2855 void
2856 tcp_mss(struct tcpcb *tp, int offer)
2857 {
2858         struct rtentry *rt;
2859         struct ifnet *ifp;
2860         int rtt, mss;
2861         u_long bufsize;
2862         struct inpcb *inp = tp->t_inpcb;
2863         struct socket *so;
2864         struct rmxp_tao *taop;
2865         int origoffer = offer;
2866 #ifdef INET6
2867         boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
2868         size_t min_protoh = isipv6 ?
2869                             sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2870                             sizeof(struct tcpiphdr);
2871 #else
2872         const boolean_t isipv6 = FALSE;
2873         const size_t min_protoh = sizeof(struct tcpiphdr);
2874 #endif
2875
2876         if (isipv6)
2877                 rt = tcp_rtlookup6(&inp->inp_inc);
2878         else
2879                 rt = tcp_rtlookup(&inp->inp_inc);
2880         if (rt == NULL) {
2881                 tp->t_maxopd = tp->t_maxseg =
2882                     (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2883                 return;
2884         }
2885         ifp = rt->rt_ifp;
2886         so = inp->inp_socket;
2887
2888         taop = rmx_taop(rt->rt_rmx);
2889         /*
2890          * Offer == -1 means that we didn't receive SYN yet,
2891          * use cached value in that case;
2892          */
2893         if (offer == -1)
2894                 offer = taop->tao_mssopt;
2895         /*
2896          * Offer == 0 means that there was no MSS on the SYN segment,
2897          * in this case we use tcp_mssdflt.
2898          */
2899         if (offer == 0)
2900                 offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2901         else
2902                 /*
2903                  * Sanity check: make sure that maxopd will be large
2904                  * enough to allow some data on segments even is the
2905                  * all the option space is used (40bytes).  Otherwise
2906                  * funny things may happen in tcp_output.
2907                  */
2908                 offer = max(offer, 64);
2909         taop->tao_mssopt = offer;
2910
2911         /*
2912          * While we're here, check if there's an initial rtt
2913          * or rttvar.  Convert from the route-table units
2914          * to scaled multiples of the slow timeout timer.
2915          */
2916         if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2917                 /*
2918                  * XXX the lock bit for RTT indicates that the value
2919                  * is also a minimum value; this is subject to time.
2920                  */
2921                 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2922                         tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2923                 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2924                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2925                 tcpstat.tcps_usedrtt++;
2926                 if (rt->rt_rmx.rmx_rttvar) {
2927                         tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2928                             (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2929                         tcpstat.tcps_usedrttvar++;
2930                 } else {
2931                         /* default variation is +- 1 rtt */
2932                         tp->t_rttvar =
2933                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2934                 }
2935                 TCPT_RANGESET(tp->t_rxtcur,
2936                               ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2937                               tp->t_rttmin, TCPTV_REXMTMAX);
2938         }
2939         /*
2940          * if there's an mtu associated with the route, use it
2941          * else, use the link mtu.
2942          */
2943         if (rt->rt_rmx.rmx_mtu)
2944                 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2945         else {
2946                 if (isipv6) {
2947                         mss = ND_IFINFO(rt->rt_ifp)->linkmtu - min_protoh;
2948                         if (!in6_localaddr(&inp->in6p_faddr))
2949                                 mss = min(mss, tcp_v6mssdflt);
2950                 } else {
2951                         mss = ifp->if_mtu - min_protoh;
2952                         if (!in_localaddr(inp->inp_faddr))
2953                                 mss = min(mss, tcp_mssdflt);
2954                 }
2955         }
2956         mss = min(mss, offer);
2957         /*
2958          * maxopd stores the maximum length of data AND options
2959          * in a segment; maxseg is the amount of data in a normal
2960          * segment.  We need to store this value (maxopd) apart
2961          * from maxseg, because now every segment carries options
2962          * and thus we normally have somewhat less data in segments.
2963          */
2964         tp->t_maxopd = mss;
2965
2966         /*
2967          * In case of T/TCP, origoffer==-1 indicates, that no segments
2968          * were received yet.  In this case we just guess, otherwise
2969          * we do the same as before T/TCP.
2970          */
2971         if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2972             (origoffer == -1 ||
2973              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2974                 mss -= TCPOLEN_TSTAMP_APPA;
2975         if ((tp->t_flags & (TF_REQ_CC | TF_NOOPT)) == TF_REQ_CC &&
2976             (origoffer == -1 ||
2977              (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2978                 mss -= TCPOLEN_CC_APPA;
2979
2980 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
2981                 if (mss > MCLBYTES)
2982                         mss &= ~(MCLBYTES-1);
2983 #else
2984                 if (mss > MCLBYTES)
2985                         mss = mss / MCLBYTES * MCLBYTES;
2986 #endif
2987         /*
2988          * If there's a pipesize, change the socket buffer
2989          * to that size.  Make the socket buffers an integral
2990          * number of mss units; if the mss is larger than
2991          * the socket buffer, decrease the mss.
2992          */
2993 #ifdef RTV_SPIPE
2994         if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2995 #endif
2996                 bufsize = so->so_snd.sb_hiwat;
2997         if (bufsize < mss)
2998                 mss = bufsize;
2999         else {
3000                 bufsize = roundup(bufsize, mss);
3001                 if (bufsize > sb_max)
3002                         bufsize = sb_max;
3003                 if (bufsize > so->so_snd.sb_hiwat)
3004                         sbreserve(&so->so_snd, bufsize, so, NULL);
3005         }
3006         tp->t_maxseg = mss;
3007
3008 #ifdef RTV_RPIPE
3009         if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
3010 #endif
3011                 bufsize = so->so_rcv.sb_hiwat;
3012         if (bufsize > mss) {
3013                 bufsize = roundup(bufsize, mss);
3014                 if (bufsize > sb_max)
3015                         bufsize = sb_max;
3016                 if (bufsize > so->so_rcv.sb_hiwat)
3017                         sbreserve(&so->so_rcv, bufsize, so, NULL);
3018         }
3019
3020         /*
3021          * Set the slow-start flight size depending on whether this
3022          * is a local network or not.
3023          */
3024         if (tcp_do_rfc3390)
3025                 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3026         else
3027                 tp->snd_cwnd = mss;
3028
3029         if (rt->rt_rmx.rmx_ssthresh) {
3030                 /*
3031                  * There's some sort of gateway or interface
3032                  * buffer limit on the path.  Use this to set
3033                  * the slow start threshhold, but set the
3034                  * threshold to no less than 2*mss.
3035                  */
3036                 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3037                 tcpstat.tcps_usedssthresh++;
3038         }
3039 }
3040
3041 /*
3042  * Determine the MSS option to send on an outgoing SYN.
3043  */
3044 int
3045 tcp_mssopt(struct tcpcb *tp)
3046 {
3047         struct rtentry *rt;
3048 #ifdef INET6
3049         boolean_t isipv6 =
3050             ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
3051         int min_protoh = isipv6 ?
3052                              sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3053                              sizeof(struct tcpiphdr);
3054 #else
3055         const boolean_t isipv6 = FALSE;
3056         const size_t min_protoh = sizeof(struct tcpiphdr);
3057 #endif
3058
3059         if (isipv6)
3060                 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3061         else
3062                 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3063         if (rt == NULL)
3064                 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3065
3066         return (rt->rt_ifp->if_mtu - min_protoh);
3067 }
3068
3069 /*
3070  * When a partial ack arrives, force the retransmission of the
3071  * next unacknowledged segment.  Do not exit Fast Recovery.
3072  *
3073  * Implement the Slow-but-Steady variant of NewReno by restarting the
3074  * the retransmission timer.  Turn it off here so it can be restarted
3075  * later in tcp_output().
3076  */
3077 static void
3078 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
3079 {
3080         tcp_seq old_snd_nxt = tp->snd_nxt;
3081         u_long ocwnd = tp->snd_cwnd;
3082
3083         callout_stop(tp->tt_rexmt);
3084         tp->t_rtttime = 0;
3085         tp->snd_nxt = th->th_ack;
3086         /* Set snd_cwnd to one segment beyond acknowledged offset. */
3087         tp->snd_cwnd = tp->t_maxseg;
3088         tp->t_flags |= TF_ACKNOW;
3089         tcp_output(tp);
3090         if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3091                 tp->snd_nxt = old_snd_nxt;
3092         /* partial window deflation */
3093         tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3094 }
3095
3096 /*
3097  * In contrast to the Slow-but-Steady NewReno variant,
3098  * we do not reset the retransmission timer for SACK retransmissions,
3099  * except when retransmitting snd_una.
3100  */
3101 static void
3102 tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3103 {
3104         uint32_t pipe, seglen;
3105         tcp_seq nextrexmt;
3106         boolean_t lostdup;
3107         tcp_seq old_snd_nxt = tp->snd_nxt;
3108         u_long ocwnd = tp->snd_cwnd;
3109         int nseg = 0;           /* consecutive new segments */
3110 #define MAXBURST 4              /* limit burst of new packets on partial ack */
3111
3112         tp->t_rtttime = 0;
3113         pipe = tcp_sack_compute_pipe(tp);
3114         while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3115             (!tcp_do_smartsack || nseg < MAXBURST) &&
3116             tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3117                 uint32_t sent;
3118                 tcp_seq old_snd_max;
3119                 int error;
3120
3121                 if (nextrexmt == tp->snd_max) ++nseg;
3122                 tp->snd_nxt = nextrexmt;
3123                 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3124                 old_snd_max = tp->snd_max;
3125                 if (nextrexmt == tp->snd_una)
3126                         callout_stop(tp->tt_rexmt);
3127                 error = tcp_output(tp);
3128                 if (error != 0)
3129                         break;
3130                 sent = tp->snd_nxt - nextrexmt;
3131                 if (sent <= 0)
3132                         break;
3133                 if (!lostdup)
3134                         pipe += sent;
3135                 tcpstat.tcps_sndsackpack++;
3136                 tcpstat.tcps_sndsackbyte += sent;
3137                 if (SEQ_LT(nextrexmt, old_snd_max) &&
3138                     SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3139                         tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3140         }
3141         if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3142                 tp->snd_nxt = old_snd_nxt;
3143         tp->snd_cwnd = ocwnd;
3144 }