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