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