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