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