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