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