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