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