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