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