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