xref: /freebsd/sys/netinet/tcp_stacks/rack.c (revision 28f4385e45a2681c14bd04b83fe1796eaefe8265)
1 /*-
2  * Copyright (c) 2016-2018
3  *	Netflix Inc.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_ipsec.h"
34 #include "opt_tcpdebug.h"
35 
36 #include <sys/param.h>
37 #include <sys/module.h>
38 #include <sys/kernel.h>
39 #ifdef TCP_HHOOK
40 #include <sys/hhook.h>
41 #endif
42 #include <sys/lock.h>
43 #include <sys/malloc.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/mbuf.h>
47 #include <sys/proc.h>		/* for proc0 declaration */
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52 #ifdef NETFLIX_STATS
53 #include <sys/stats.h>
54 #endif
55 #include <sys/refcount.h>
56 #include <sys/queue.h>
57 #include <sys/smp.h>
58 #include <sys/kthread.h>
59 #include <sys/kern_prefetch.h>
60 
61 #include <vm/uma.h>
62 
63 #include <net/route.h>
64 #include <net/vnet.h>
65 
66 #define TCPSTATES		/* for logging */
67 
68 #include <netinet/in.h>
69 #include <netinet/in_kdtrace.h>
70 #include <netinet/in_pcb.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
73 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
74 #include <netinet/ip_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet6/in6_pcb.h>
77 #include <netinet6/ip6_var.h>
78 #include <netinet/tcp.h>
79 #define	TCPOUTFLAGS
80 #include <netinet/tcp_fsm.h>
81 #include <netinet/tcp_log_buf.h>
82 #include <netinet/tcp_seq.h>
83 #include <netinet/tcp_timer.h>
84 #include <netinet/tcp_var.h>
85 #include <netinet/tcp_hpts.h>
86 #include <netinet/tcpip.h>
87 #include <netinet/cc/cc.h>
88 #ifdef NETFLIX_CWV
89 #include <netinet/tcp_newcwv.h>
90 #endif
91 #include <netinet/tcp_fastopen.h>
92 #ifdef TCPDEBUG
93 #include <netinet/tcp_debug.h>
94 #endif				/* TCPDEBUG */
95 #ifdef TCP_OFFLOAD
96 #include <netinet/tcp_offload.h>
97 #endif
98 #ifdef INET6
99 #include <netinet6/tcp6_var.h>
100 #endif
101 
102 #include <netipsec/ipsec_support.h>
103 
104 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
105 #include <netipsec/ipsec.h>
106 #include <netipsec/ipsec6.h>
107 #endif				/* IPSEC */
108 
109 #include <netinet/udp.h>
110 #include <netinet/udp_var.h>
111 #include <machine/in_cksum.h>
112 
113 #ifdef MAC
114 #include <security/mac/mac_framework.h>
115 #endif
116 #include "sack_filter.h"
117 #include "tcp_rack.h"
118 #include "rack_bbr_common.h"
119 
120 uma_zone_t rack_zone;
121 uma_zone_t rack_pcb_zone;
122 
123 #ifndef TICKS2SBT
124 #define	TICKS2SBT(__t)	(tick_sbt * ((sbintime_t)(__t)))
125 #endif
126 
127 struct sysctl_ctx_list rack_sysctl_ctx;
128 struct sysctl_oid *rack_sysctl_root;
129 
130 #define CUM_ACKED 1
131 #define SACKED 2
132 
133 /*
134  * The RACK module incorporates a number of
135  * TCP ideas that have been put out into the IETF
136  * over the last few years:
137  * - Matt Mathis's Rate Halving which slowly drops
138  *    the congestion window so that the ack clock can
139  *    be maintained during a recovery.
140  * - Yuchung Cheng's RACK TCP (for which its named) that
141  *    will stop us using the number of dup acks and instead
142  *    use time as the gage of when we retransmit.
143  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
144  *    of Dukkipati et.al.
145  * RACK depends on SACK, so if an endpoint arrives that
146  * cannot do SACK the state machine below will shuttle the
147  * connection back to using the "default" TCP stack that is
148  * in FreeBSD.
149  *
150  * To implement RACK the original TCP stack was first decomposed
151  * into a functional state machine with individual states
152  * for each of the possible TCP connection states. The do_segement
153  * functions role in life is to mandate the connection supports SACK
154  * initially and then assure that the RACK state matches the conenction
155  * state before calling the states do_segment function. Each
156  * state is simplified due to the fact that the original do_segment
157  * has been decomposed and we *know* what state we are in (no
158  * switches on the state) and all tests for SACK are gone. This
159  * greatly simplifies what each state does.
160  *
161  * TCP output is also over-written with a new version since it
162  * must maintain the new rack scoreboard.
163  *
164  */
165 static int32_t rack_precache = 1;
166 static int32_t rack_tlp_thresh = 1;
167 static int32_t rack_reorder_thresh = 2;
168 static int32_t rack_reorder_fade = 60000;	/* 0 - never fade, def 60,000
169 						 * - 60 seconds */
170 static int32_t rack_pkt_delay = 1;
171 static int32_t rack_inc_var = 0;/* For TLP */
172 static int32_t rack_reduce_largest_on_idle = 0;
173 static int32_t rack_min_pace_time = 0;
174 static int32_t rack_min_pace_time_seg_req=6;
175 static int32_t rack_early_recovery = 1;
176 static int32_t rack_early_recovery_max_seg = 6;
177 static int32_t rack_send_a_lot_in_prr = 1;
178 static int32_t rack_min_to = 1;	/* Number of ms minimum timeout */
179 static int32_t rack_tlp_in_recovery = 1;	/* Can we do TLP in recovery? */
180 static int32_t rack_verbose_logging = 0;
181 static int32_t rack_ignore_data_after_close = 1;
182 /*
183  * Currently regular tcp has a rto_min of 30ms
184  * the backoff goes 12 times so that ends up
185  * being a total of 122.850 seconds before a
186  * connection is killed.
187  */
188 static int32_t rack_tlp_min = 10;
189 static int32_t rack_rto_min = 30;	/* 30ms same as main freebsd */
190 static int32_t rack_rto_max = 30000;	/* 30 seconds */
191 static const int32_t rack_free_cache = 2;
192 static int32_t rack_hptsi_segments = 40;
193 static int32_t rack_rate_sample_method = USE_RTT_LOW;
194 static int32_t rack_pace_every_seg = 1;
195 static int32_t rack_delayed_ack_time = 200;	/* 200ms */
196 static int32_t rack_slot_reduction = 4;
197 static int32_t rack_lower_cwnd_at_tlp = 0;
198 static int32_t rack_use_proportional_reduce = 0;
199 static int32_t rack_proportional_rate = 10;
200 static int32_t rack_tlp_max_resend = 2;
201 static int32_t rack_limited_retran = 0;
202 static int32_t rack_always_send_oldest = 0;
203 static int32_t rack_sack_block_limit = 128;
204 static int32_t rack_use_sack_filter = 1;
205 static int32_t rack_tlp_threshold_use = TLP_USE_TWO_ONE;
206 
207 /* Rack specific counters */
208 counter_u64_t rack_badfr;
209 counter_u64_t rack_badfr_bytes;
210 counter_u64_t rack_rtm_prr_retran;
211 counter_u64_t rack_rtm_prr_newdata;
212 counter_u64_t rack_timestamp_mismatch;
213 counter_u64_t rack_reorder_seen;
214 counter_u64_t rack_paced_segments;
215 counter_u64_t rack_unpaced_segments;
216 counter_u64_t rack_saw_enobuf;
217 counter_u64_t rack_saw_enetunreach;
218 
219 /* Tail loss probe counters */
220 counter_u64_t rack_tlp_tot;
221 counter_u64_t rack_tlp_newdata;
222 counter_u64_t rack_tlp_retran;
223 counter_u64_t rack_tlp_retran_bytes;
224 counter_u64_t rack_tlp_retran_fail;
225 counter_u64_t rack_to_tot;
226 counter_u64_t rack_to_arm_rack;
227 counter_u64_t rack_to_arm_tlp;
228 counter_u64_t rack_to_alloc;
229 counter_u64_t rack_to_alloc_hard;
230 counter_u64_t rack_to_alloc_emerg;
231 
232 counter_u64_t rack_sack_proc_all;
233 counter_u64_t rack_sack_proc_short;
234 counter_u64_t rack_sack_proc_restart;
235 counter_u64_t rack_runt_sacks;
236 counter_u64_t rack_used_tlpmethod;
237 counter_u64_t rack_used_tlpmethod2;
238 counter_u64_t rack_enter_tlp_calc;
239 counter_u64_t rack_input_idle_reduces;
240 counter_u64_t rack_tlp_does_nada;
241 
242 /* Temp CPU counters */
243 counter_u64_t rack_find_high;
244 
245 counter_u64_t rack_progress_drops;
246 counter_u64_t rack_out_size[TCP_MSS_ACCT_SIZE];
247 counter_u64_t rack_opts_arry[RACK_OPTS_SIZE];
248 
249 static void
250 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line);
251 
252 static int
253 rack_process_ack(struct mbuf *m, struct tcphdr *th,
254     struct socket *so, struct tcpcb *tp, struct tcpopt *to,
255     uint32_t tiwin, int32_t tlen, int32_t * ofia, int32_t thflags, int32_t * ret_val);
256 static int
257 rack_process_data(struct mbuf *m, struct tcphdr *th,
258     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
259     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
260 static void
261 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack,
262     struct tcphdr *th, uint16_t nsegs, uint16_t type, int32_t recovery);
263 static struct rack_sendmap *rack_alloc(struct tcp_rack *rack);
264 static struct rack_sendmap *
265 rack_check_recovery_mode(struct tcpcb *tp,
266     uint32_t tsused);
267 static void
268 rack_cong_signal(struct tcpcb *tp, struct tcphdr *th,
269     uint32_t type);
270 static void rack_counter_destroy(void);
271 static int
272 rack_ctloutput(struct socket *so, struct sockopt *sopt,
273     struct inpcb *inp, struct tcpcb *tp);
274 static int32_t rack_ctor(void *mem, int32_t size, void *arg, int32_t how);
275 static void
276 rack_do_segment(struct mbuf *m, struct tcphdr *th,
277     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
278     uint8_t iptos);
279 static void rack_dtor(void *mem, int32_t size, void *arg);
280 static void
281 rack_earlier_retran(struct tcpcb *tp, struct rack_sendmap *rsm,
282     uint32_t t, uint32_t cts);
283 static struct rack_sendmap *
284 rack_find_high_nonack(struct tcp_rack *rack,
285     struct rack_sendmap *rsm);
286 static struct rack_sendmap *rack_find_lowest_rsm(struct tcp_rack *rack);
287 static void rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm);
288 static void rack_fini(struct tcpcb *tp, int32_t tcb_is_purged);
289 static int
290 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
291     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
292 static int32_t rack_handoff_ok(struct tcpcb *tp);
293 static int32_t rack_init(struct tcpcb *tp);
294 static void rack_init_sysctls(void);
295 static void
296 rack_log_ack(struct tcpcb *tp, struct tcpopt *to,
297     struct tcphdr *th);
298 static void
299 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
300     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t ts,
301     uint8_t pass, struct rack_sendmap *hintrsm);
302 static void
303 rack_log_sack_passed(struct tcpcb *tp, struct tcp_rack *rack,
304     struct rack_sendmap *rsm);
305 static void rack_log_to_event(struct tcp_rack *rack, int32_t to_num);
306 static int32_t rack_output(struct tcpcb *tp);
307 static void
308 rack_hpts_do_segment(struct mbuf *m, struct tcphdr *th,
309     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
310     uint8_t iptos, int32_t nxt_pkt, struct timeval *tv);
311 
312 static uint32_t
313 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack,
314     struct sackblk *sack, struct tcpopt *to, struct rack_sendmap **prsm,
315     uint32_t cts);
316 static void rack_post_recovery(struct tcpcb *tp, struct tcphdr *th);
317 static void rack_remxt_tmr(struct tcpcb *tp);
318 static int
319 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
320     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
321 static void rack_set_state(struct tcpcb *tp, struct tcp_rack *rack);
322 static int32_t rack_stopall(struct tcpcb *tp);
323 static void
324 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type,
325     uint32_t delta);
326 static int32_t rack_timer_active(struct tcpcb *tp, uint32_t timer_type);
327 static void rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line);
328 static void rack_timer_stop(struct tcpcb *tp, uint32_t timer_type);
329 static uint32_t
330 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
331     struct rack_sendmap *rsm, uint32_t ts, int32_t * lenp);
332 static void
333 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
334     struct rack_sendmap *rsm, uint32_t ts);
335 static int
336 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
337     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type);
338 static int32_t tcp_addrack(module_t mod, int32_t type, void *data);
339 static void
340 rack_challenge_ack(struct mbuf *m, struct tcphdr *th,
341     struct tcpcb *tp, int32_t * ret_val);
342 static int
343 rack_do_close_wait(struct mbuf *m, struct tcphdr *th,
344     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
345     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
346 static int
347 rack_do_closing(struct mbuf *m, struct tcphdr *th,
348     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
349     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
350 static void
351 rack_do_drop(struct mbuf *m, struct tcpcb *tp);
352 static void
353 rack_do_dropafterack(struct mbuf *m, struct tcpcb *tp,
354     struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t * ret_val);
355 static void
356 rack_do_dropwithreset(struct mbuf *m, struct tcpcb *tp,
357 	struct tcphdr *th, int32_t rstreason, int32_t tlen);
358 static int
359 rack_do_established(struct mbuf *m, struct tcphdr *th,
360     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
361     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
362 static int
363 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th,
364     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
365     int32_t tlen, uint32_t tiwin, int32_t nxt_pkt);
366 static int
367 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th,
368     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
369     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
370 static int
371 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th,
372     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
373     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
374 static int
375 rack_do_lastack(struct mbuf *m, struct tcphdr *th,
376     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
377     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
378 static int
379 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th,
380     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
381     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
382 static int
383 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th,
384     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
385     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
386 static int
387 rack_drop_checks(struct tcpopt *to, struct mbuf *m,
388     struct tcphdr *th, struct tcpcb *tp, int32_t * tlenp, int32_t * thf,
389     int32_t * drop_hdrlen, int32_t * ret_val);
390 static int
391 rack_process_rst(struct mbuf *m, struct tcphdr *th,
392     struct socket *so, struct tcpcb *tp);
393 struct rack_sendmap *
394 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack,
395     uint32_t tsused);
396 static void tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt);
397 static void
398      tcp_rack_partialack(struct tcpcb *tp, struct tcphdr *th);
399 
400 static int
401 rack_ts_check(struct mbuf *m, struct tcphdr *th,
402     struct tcpcb *tp, int32_t tlen, int32_t thflags, int32_t * ret_val);
403 
404 int32_t rack_clear_counter=0;
405 
406 
407 static int
408 sysctl_rack_clear(SYSCTL_HANDLER_ARGS)
409 {
410 	uint32_t stat;
411 	int32_t error;
412 
413 	error = SYSCTL_OUT(req, &rack_clear_counter, sizeof(uint32_t));
414 	if (error || req->newptr == NULL)
415 		return error;
416 
417 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
418 	if (error)
419 		return (error);
420 	if (stat == 1) {
421 #ifdef INVARIANTS
422 		printf("Clearing RACK counters\n");
423 #endif
424 		counter_u64_zero(rack_badfr);
425 		counter_u64_zero(rack_badfr_bytes);
426 		counter_u64_zero(rack_rtm_prr_retran);
427 		counter_u64_zero(rack_rtm_prr_newdata);
428 		counter_u64_zero(rack_timestamp_mismatch);
429 		counter_u64_zero(rack_reorder_seen);
430 		counter_u64_zero(rack_tlp_tot);
431 		counter_u64_zero(rack_tlp_newdata);
432 		counter_u64_zero(rack_tlp_retran);
433 		counter_u64_zero(rack_tlp_retran_bytes);
434 		counter_u64_zero(rack_tlp_retran_fail);
435 		counter_u64_zero(rack_to_tot);
436 		counter_u64_zero(rack_to_arm_rack);
437 		counter_u64_zero(rack_to_arm_tlp);
438 		counter_u64_zero(rack_paced_segments);
439 		counter_u64_zero(rack_unpaced_segments);
440 		counter_u64_zero(rack_saw_enobuf);
441 		counter_u64_zero(rack_saw_enetunreach);
442 		counter_u64_zero(rack_to_alloc_hard);
443 		counter_u64_zero(rack_to_alloc_emerg);
444 		counter_u64_zero(rack_sack_proc_all);
445 		counter_u64_zero(rack_sack_proc_short);
446 		counter_u64_zero(rack_sack_proc_restart);
447 		counter_u64_zero(rack_to_alloc);
448 		counter_u64_zero(rack_find_high);
449 		counter_u64_zero(rack_runt_sacks);
450 		counter_u64_zero(rack_used_tlpmethod);
451 		counter_u64_zero(rack_used_tlpmethod2);
452 		counter_u64_zero(rack_enter_tlp_calc);
453 		counter_u64_zero(rack_progress_drops);
454 		counter_u64_zero(rack_tlp_does_nada);
455 	}
456 	rack_clear_counter = 0;
457 	return (0);
458 }
459 
460 
461 
462 static void
463 rack_init_sysctls()
464 {
465 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
466 	    SYSCTL_CHILDREN(rack_sysctl_root),
467 	    OID_AUTO, "rate_sample_method", CTLFLAG_RW,
468 	    &rack_rate_sample_method , USE_RTT_LOW,
469 	    "What method should we use for rate sampling 0=high, 1=low ");
470 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
471 	    SYSCTL_CHILDREN(rack_sysctl_root),
472 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
473 	    &rack_ignore_data_after_close, 0,
474 	    "Do we hold off sending a RST until all pending data is ack'd");
475 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
476 	    SYSCTL_CHILDREN(rack_sysctl_root),
477 	    OID_AUTO, "tlpmethod", CTLFLAG_RW,
478 	    &rack_tlp_threshold_use, TLP_USE_TWO_ONE,
479 	    "What method do we do for TLP time calc 0=no-de-ack-comp, 1=ID, 2=2.1, 3=2.2");
480 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
481 	    SYSCTL_CHILDREN(rack_sysctl_root),
482 	    OID_AUTO, "min_pace_time", CTLFLAG_RW,
483 	    &rack_min_pace_time, 0,
484 	    "Should we enforce a minimum pace time of 1ms");
485 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
486 	    SYSCTL_CHILDREN(rack_sysctl_root),
487 	    OID_AUTO, "min_pace_segs", CTLFLAG_RW,
488 	    &rack_min_pace_time_seg_req, 6,
489 	    "How many segments have to be in the len to enforce min-pace-time");
490 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
491 	    SYSCTL_CHILDREN(rack_sysctl_root),
492 	    OID_AUTO, "idle_reduce_high", CTLFLAG_RW,
493 	    &rack_reduce_largest_on_idle, 0,
494 	    "Should we reduce the largest cwnd seen to IW on idle reduction");
495 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
496 	    SYSCTL_CHILDREN(rack_sysctl_root),
497 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
498 	    &rack_verbose_logging, 0,
499 	    "Should RACK black box logging be verbose");
500 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
501 	    SYSCTL_CHILDREN(rack_sysctl_root),
502 	    OID_AUTO, "sackfiltering", CTLFLAG_RW,
503 	    &rack_use_sack_filter, 1,
504 	    "Do we use sack filtering?");
505 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
506 	    SYSCTL_CHILDREN(rack_sysctl_root),
507 	    OID_AUTO, "delayed_ack", CTLFLAG_RW,
508 	    &rack_delayed_ack_time, 200,
509 	    "Delayed ack time (200ms)");
510 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
511 	    SYSCTL_CHILDREN(rack_sysctl_root),
512 	    OID_AUTO, "tlpminto", CTLFLAG_RW,
513 	    &rack_tlp_min, 10,
514 	    "TLP minimum timeout per the specification (10ms)");
515 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
516 	    SYSCTL_CHILDREN(rack_sysctl_root),
517 	    OID_AUTO, "precache", CTLFLAG_RW,
518 	    &rack_precache, 0,
519 	    "Where should we precache the mcopy (0 is not at all)");
520 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
521 	    SYSCTL_CHILDREN(rack_sysctl_root),
522 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
523 	    &rack_sack_block_limit, 128,
524 	    "When do we start paying attention to small sack blocks");
525 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
526 	    SYSCTL_CHILDREN(rack_sysctl_root),
527 	    OID_AUTO, "send_oldest", CTLFLAG_RW,
528 	    &rack_always_send_oldest, 1,
529 	    "Should we always send the oldest TLP and RACK-TLP");
530 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
531 	    SYSCTL_CHILDREN(rack_sysctl_root),
532 	    OID_AUTO, "rack_tlp_in_recovery", CTLFLAG_RW,
533 	    &rack_tlp_in_recovery, 1,
534 	    "Can we do a TLP during recovery?");
535 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
536 	    SYSCTL_CHILDREN(rack_sysctl_root),
537 	    OID_AUTO, "rack_tlimit", CTLFLAG_RW,
538 	    &rack_limited_retran, 0,
539 	    "How many times can a rack timeout drive out sends");
540 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
541 	    SYSCTL_CHILDREN(rack_sysctl_root),
542 	    OID_AUTO, "minrto", CTLFLAG_RW,
543 	    &rack_rto_min, 0,
544 	    "Minimum RTO in ms -- set with caution below 1000 due to TLP");
545 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
546 	    SYSCTL_CHILDREN(rack_sysctl_root),
547 	    OID_AUTO, "maxrto", CTLFLAG_RW,
548 	    &rack_rto_max, 0,
549 	    "Maxiumum RTO in ms -- should be at least as large as min_rto");
550 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
551 	    SYSCTL_CHILDREN(rack_sysctl_root),
552 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
553 	    &rack_tlp_max_resend, 2,
554 	    "How many times does TLP retry a single segment or multiple with no ACK");
555 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
556 	    SYSCTL_CHILDREN(rack_sysctl_root),
557 	    OID_AUTO, "recovery_loss_prop", CTLFLAG_RW,
558 	    &rack_use_proportional_reduce, 0,
559 	    "Should we proportionaly reduce cwnd based on the number of losses ");
560 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
561 	    SYSCTL_CHILDREN(rack_sysctl_root),
562 	    OID_AUTO, "recovery_prop", CTLFLAG_RW,
563 	    &rack_proportional_rate, 10,
564 	    "What percent reduction per loss");
565 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
566 	    SYSCTL_CHILDREN(rack_sysctl_root),
567 	    OID_AUTO, "tlp_cwnd_flag", CTLFLAG_RW,
568 	    &rack_lower_cwnd_at_tlp, 0,
569 	    "When a TLP completes a retran should we enter recovery?");
570 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
571 	    SYSCTL_CHILDREN(rack_sysctl_root),
572 	    OID_AUTO, "hptsi_reduces", CTLFLAG_RW,
573 	    &rack_slot_reduction, 4,
574 	    "When setting a slot should we reduce by divisor");
575 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
576 	    SYSCTL_CHILDREN(rack_sysctl_root),
577 	    OID_AUTO, "hptsi_every_seg", CTLFLAG_RW,
578 	    &rack_pace_every_seg, 1,
579 	    "Should we pace out every segment hptsi");
580 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
581 	    SYSCTL_CHILDREN(rack_sysctl_root),
582 	    OID_AUTO, "hptsi_seg_max", CTLFLAG_RW,
583 	    &rack_hptsi_segments, 6,
584 	    "Should we pace out only a limited size of segments");
585 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
586 	    SYSCTL_CHILDREN(rack_sysctl_root),
587 	    OID_AUTO, "prr_sendalot", CTLFLAG_RW,
588 	    &rack_send_a_lot_in_prr, 1,
589 	    "Send a lot in prr");
590 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
591 	    SYSCTL_CHILDREN(rack_sysctl_root),
592 	    OID_AUTO, "minto", CTLFLAG_RW,
593 	    &rack_min_to, 1,
594 	    "Minimum rack timeout in milliseconds");
595 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
596 	    SYSCTL_CHILDREN(rack_sysctl_root),
597 	    OID_AUTO, "earlyrecoveryseg", CTLFLAG_RW,
598 	    &rack_early_recovery_max_seg, 6,
599 	    "Max segments in early recovery");
600 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
601 	    SYSCTL_CHILDREN(rack_sysctl_root),
602 	    OID_AUTO, "earlyrecovery", CTLFLAG_RW,
603 	    &rack_early_recovery, 1,
604 	    "Do we do early recovery with rack");
605 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
606 	    SYSCTL_CHILDREN(rack_sysctl_root),
607 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
608 	    &rack_reorder_thresh, 2,
609 	    "What factor for rack will be added when seeing reordering (shift right)");
610 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
611 	    SYSCTL_CHILDREN(rack_sysctl_root),
612 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
613 	    &rack_tlp_thresh, 1,
614 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
615 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
616 	    SYSCTL_CHILDREN(rack_sysctl_root),
617 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
618 	    &rack_reorder_fade, 0,
619 	    "Does reorder detection fade, if so how many ms (0 means never)");
620 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
621 	    SYSCTL_CHILDREN(rack_sysctl_root),
622 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
623 	    &rack_pkt_delay, 1,
624 	    "Extra RACK time (in ms) besides reordering thresh");
625 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
626 	    SYSCTL_CHILDREN(rack_sysctl_root),
627 	    OID_AUTO, "inc_var", CTLFLAG_RW,
628 	    &rack_inc_var, 0,
629 	    "Should rack add to the TLP timer the variance in rtt calculation");
630 	rack_badfr = counter_u64_alloc(M_WAITOK);
631 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
632 	    SYSCTL_CHILDREN(rack_sysctl_root),
633 	    OID_AUTO, "badfr", CTLFLAG_RD,
634 	    &rack_badfr, "Total number of bad FRs");
635 	rack_badfr_bytes = counter_u64_alloc(M_WAITOK);
636 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
637 	    SYSCTL_CHILDREN(rack_sysctl_root),
638 	    OID_AUTO, "badfr_bytes", CTLFLAG_RD,
639 	    &rack_badfr_bytes, "Total number of bad FRs");
640 	rack_rtm_prr_retran = counter_u64_alloc(M_WAITOK);
641 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
642 	    SYSCTL_CHILDREN(rack_sysctl_root),
643 	    OID_AUTO, "prrsndret", CTLFLAG_RD,
644 	    &rack_rtm_prr_retran,
645 	    "Total number of prr based retransmits");
646 	rack_rtm_prr_newdata = counter_u64_alloc(M_WAITOK);
647 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
648 	    SYSCTL_CHILDREN(rack_sysctl_root),
649 	    OID_AUTO, "prrsndnew", CTLFLAG_RD,
650 	    &rack_rtm_prr_newdata,
651 	    "Total number of prr based new transmits");
652 	rack_timestamp_mismatch = counter_u64_alloc(M_WAITOK);
653 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
654 	    SYSCTL_CHILDREN(rack_sysctl_root),
655 	    OID_AUTO, "tsnf", CTLFLAG_RD,
656 	    &rack_timestamp_mismatch,
657 	    "Total number of timestamps that we could not find the reported ts");
658 	rack_find_high = counter_u64_alloc(M_WAITOK);
659 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
660 	    SYSCTL_CHILDREN(rack_sysctl_root),
661 	    OID_AUTO, "findhigh", CTLFLAG_RD,
662 	    &rack_find_high,
663 	    "Total number of FIN causing find-high");
664 	rack_reorder_seen = counter_u64_alloc(M_WAITOK);
665 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
666 	    SYSCTL_CHILDREN(rack_sysctl_root),
667 	    OID_AUTO, "reordering", CTLFLAG_RD,
668 	    &rack_reorder_seen,
669 	    "Total number of times we added delay due to reordering");
670 	rack_tlp_tot = counter_u64_alloc(M_WAITOK);
671 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
672 	    SYSCTL_CHILDREN(rack_sysctl_root),
673 	    OID_AUTO, "tlp_to_total", CTLFLAG_RD,
674 	    &rack_tlp_tot,
675 	    "Total number of tail loss probe expirations");
676 	rack_tlp_newdata = counter_u64_alloc(M_WAITOK);
677 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
678 	    SYSCTL_CHILDREN(rack_sysctl_root),
679 	    OID_AUTO, "tlp_new", CTLFLAG_RD,
680 	    &rack_tlp_newdata,
681 	    "Total number of tail loss probe sending new data");
682 
683 	rack_tlp_retran = counter_u64_alloc(M_WAITOK);
684 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
685 	    SYSCTL_CHILDREN(rack_sysctl_root),
686 	    OID_AUTO, "tlp_retran", CTLFLAG_RD,
687 	    &rack_tlp_retran,
688 	    "Total number of tail loss probe sending retransmitted data");
689 	rack_tlp_retran_bytes = counter_u64_alloc(M_WAITOK);
690 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
691 	    SYSCTL_CHILDREN(rack_sysctl_root),
692 	    OID_AUTO, "tlp_retran_bytes", CTLFLAG_RD,
693 	    &rack_tlp_retran_bytes,
694 	    "Total bytes of tail loss probe sending retransmitted data");
695 	rack_tlp_retran_fail = counter_u64_alloc(M_WAITOK);
696 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
697 	    SYSCTL_CHILDREN(rack_sysctl_root),
698 	    OID_AUTO, "tlp_retran_fail", CTLFLAG_RD,
699 	    &rack_tlp_retran_fail,
700 	    "Total number of tail loss probe sending retransmitted data that failed (wait for t3)");
701 	rack_to_tot = counter_u64_alloc(M_WAITOK);
702 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
703 	    SYSCTL_CHILDREN(rack_sysctl_root),
704 	    OID_AUTO, "rack_to_tot", CTLFLAG_RD,
705 	    &rack_to_tot,
706 	    "Total number of times the rack to expired?");
707 	rack_to_arm_rack = counter_u64_alloc(M_WAITOK);
708 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
709 	    SYSCTL_CHILDREN(rack_sysctl_root),
710 	    OID_AUTO, "arm_rack", CTLFLAG_RD,
711 	    &rack_to_arm_rack,
712 	    "Total number of times the rack timer armed?");
713 	rack_to_arm_tlp = counter_u64_alloc(M_WAITOK);
714 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
715 	    SYSCTL_CHILDREN(rack_sysctl_root),
716 	    OID_AUTO, "arm_tlp", CTLFLAG_RD,
717 	    &rack_to_arm_tlp,
718 	    "Total number of times the tlp timer armed?");
719 	rack_paced_segments = counter_u64_alloc(M_WAITOK);
720 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
721 	    SYSCTL_CHILDREN(rack_sysctl_root),
722 	    OID_AUTO, "paced", CTLFLAG_RD,
723 	    &rack_paced_segments,
724 	    "Total number of times a segment send caused hptsi");
725 	rack_unpaced_segments = counter_u64_alloc(M_WAITOK);
726 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
727 	    SYSCTL_CHILDREN(rack_sysctl_root),
728 	    OID_AUTO, "unpaced", CTLFLAG_RD,
729 	    &rack_unpaced_segments,
730 	    "Total number of times a segment did not cause hptsi");
731 	rack_saw_enobuf = counter_u64_alloc(M_WAITOK);
732 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
733 	    SYSCTL_CHILDREN(rack_sysctl_root),
734 	    OID_AUTO, "saw_enobufs", CTLFLAG_RD,
735 	    &rack_saw_enobuf,
736 	    "Total number of times a segment did not cause hptsi");
737 	rack_saw_enetunreach = counter_u64_alloc(M_WAITOK);
738 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
739 	    SYSCTL_CHILDREN(rack_sysctl_root),
740 	    OID_AUTO, "saw_enetunreach", CTLFLAG_RD,
741 	    &rack_saw_enetunreach,
742 	    "Total number of times a segment did not cause hptsi");
743 	rack_to_alloc = counter_u64_alloc(M_WAITOK);
744 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
745 	    SYSCTL_CHILDREN(rack_sysctl_root),
746 	    OID_AUTO, "allocs", CTLFLAG_RD,
747 	    &rack_to_alloc,
748 	    "Total allocations of tracking structures");
749 	rack_to_alloc_hard = counter_u64_alloc(M_WAITOK);
750 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
751 	    SYSCTL_CHILDREN(rack_sysctl_root),
752 	    OID_AUTO, "allochard", CTLFLAG_RD,
753 	    &rack_to_alloc_hard,
754 	    "Total allocations done with sleeping the hard way");
755 	rack_to_alloc_emerg = counter_u64_alloc(M_WAITOK);
756 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
757 	    SYSCTL_CHILDREN(rack_sysctl_root),
758 	    OID_AUTO, "allocemerg", CTLFLAG_RD,
759 	    &rack_to_alloc_emerg,
760 	    "Total alocations done from emergency cache");
761 	rack_sack_proc_all = counter_u64_alloc(M_WAITOK);
762 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
763 	    SYSCTL_CHILDREN(rack_sysctl_root),
764 	    OID_AUTO, "sack_long", CTLFLAG_RD,
765 	    &rack_sack_proc_all,
766 	    "Total times we had to walk whole list for sack processing");
767 
768 	rack_sack_proc_restart = counter_u64_alloc(M_WAITOK);
769 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
770 	    SYSCTL_CHILDREN(rack_sysctl_root),
771 	    OID_AUTO, "sack_restart", CTLFLAG_RD,
772 	    &rack_sack_proc_restart,
773 	    "Total times we had to walk whole list due to a restart");
774 	rack_sack_proc_short = counter_u64_alloc(M_WAITOK);
775 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
776 	    SYSCTL_CHILDREN(rack_sysctl_root),
777 	    OID_AUTO, "sack_short", CTLFLAG_RD,
778 	    &rack_sack_proc_short,
779 	    "Total times we took shortcut for sack processing");
780 	rack_enter_tlp_calc = counter_u64_alloc(M_WAITOK);
781 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
782 	    SYSCTL_CHILDREN(rack_sysctl_root),
783 	    OID_AUTO, "tlp_calc_entered", CTLFLAG_RD,
784 	    &rack_enter_tlp_calc,
785 	    "Total times we called calc-tlp");
786 	rack_used_tlpmethod = counter_u64_alloc(M_WAITOK);
787 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
788 	    SYSCTL_CHILDREN(rack_sysctl_root),
789 	    OID_AUTO, "hit_tlp_method", CTLFLAG_RD,
790 	    &rack_used_tlpmethod,
791 	    "Total number of runt sacks");
792 	rack_used_tlpmethod2 = counter_u64_alloc(M_WAITOK);
793 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
794 	    SYSCTL_CHILDREN(rack_sysctl_root),
795 	    OID_AUTO, "hit_tlp_method2", CTLFLAG_RD,
796 	    &rack_used_tlpmethod2,
797 	    "Total number of runt sacks 2");
798 	rack_runt_sacks = counter_u64_alloc(M_WAITOK);
799 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
800 	    SYSCTL_CHILDREN(rack_sysctl_root),
801 	    OID_AUTO, "runtsacks", CTLFLAG_RD,
802 	    &rack_runt_sacks,
803 	    "Total number of runt sacks");
804 	rack_progress_drops = counter_u64_alloc(M_WAITOK);
805 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
806 	    SYSCTL_CHILDREN(rack_sysctl_root),
807 	    OID_AUTO, "prog_drops", CTLFLAG_RD,
808 	    &rack_progress_drops,
809 	    "Total number of progress drops");
810 	rack_input_idle_reduces = counter_u64_alloc(M_WAITOK);
811 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
812 	    SYSCTL_CHILDREN(rack_sysctl_root),
813 	    OID_AUTO, "idle_reduce_oninput", CTLFLAG_RD,
814 	    &rack_input_idle_reduces,
815 	    "Total number of idle reductions on input");
816 	rack_tlp_does_nada = counter_u64_alloc(M_WAITOK);
817 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
818 	    SYSCTL_CHILDREN(rack_sysctl_root),
819 	    OID_AUTO, "tlp_nada", CTLFLAG_RD,
820 	    &rack_tlp_does_nada,
821 	    "Total number of nada tlp calls");
822 	COUNTER_ARRAY_ALLOC(rack_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
823 	SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
824 	    OID_AUTO, "outsize", CTLFLAG_RD,
825 	    rack_out_size, TCP_MSS_ACCT_SIZE, "MSS send sizes");
826 	COUNTER_ARRAY_ALLOC(rack_opts_arry, RACK_OPTS_SIZE, M_WAITOK);
827 	SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
828 	    OID_AUTO, "opts", CTLFLAG_RD,
829 	    rack_opts_arry, RACK_OPTS_SIZE, "RACK Option Stats");
830 	SYSCTL_ADD_PROC(&rack_sysctl_ctx,
831 	    SYSCTL_CHILDREN(rack_sysctl_root),
832 	    OID_AUTO, "clear", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
833 	    &rack_clear_counter, 0, sysctl_rack_clear, "IU", "Clear counters");
834 }
835 
836 static inline int32_t
837 rack_progress_timeout_check(struct tcpcb *tp)
838 {
839 	if (tp->t_maxunacktime && tp->t_acktime && TSTMP_GT(ticks, tp->t_acktime)) {
840 		if ((ticks - tp->t_acktime) >= tp->t_maxunacktime) {
841 			/*
842 			 * There is an assumption that the caller
843 			 * will drop the connection so we will
844 			 * increment the counters here.
845 			 */
846 			struct tcp_rack *rack;
847 			rack = (struct tcp_rack *)tp->t_fb_ptr;
848 			counter_u64_add(rack_progress_drops, 1);
849 #ifdef NETFLIX_STATS
850 			TCPSTAT_INC(tcps_progdrops);
851 #endif
852 			rack_log_progress_event(rack, tp, ticks, PROGRESS_DROP, __LINE__);
853 			return (1);
854 		}
855 	}
856 	return (0);
857 }
858 
859 
860 static void
861 rack_log_to_start(struct tcp_rack *rack, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
862 {
863 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
864 		union tcp_log_stackspecific log;
865 
866 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
867 		log.u_bbr.flex1 = TICKS_2_MSEC(rack->rc_tp->t_srtt >> TCP_RTT_SHIFT);
868 		log.u_bbr.flex2 = to;
869 		log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
870 		log.u_bbr.flex4 = slot;
871 		log.u_bbr.flex5 = rack->rc_inp->inp_hptsslot;
872 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
873 		log.u_bbr.flex8 = which;
874 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
875 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
876 		TCP_LOG_EVENT(rack->rc_tp, NULL,
877 		    &rack->rc_inp->inp_socket->so_rcv,
878 		    &rack->rc_inp->inp_socket->so_snd,
879 		    BBR_LOG_TIMERSTAR, 0,
880 		    0, &log, false);
881 	}
882 }
883 
884 static void
885 rack_log_to_event(struct tcp_rack *rack, int32_t to_num)
886 {
887 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
888 		union tcp_log_stackspecific log;
889 
890 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
891 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
892 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
893 		log.u_bbr.flex8 = to_num;
894 		log.u_bbr.flex1 = rack->r_ctl.rc_rack_min_rtt;
895 		log.u_bbr.flex2 = rack->rc_rack_rtt;
896 		TCP_LOG_EVENT(rack->rc_tp, NULL,
897 		    &rack->rc_inp->inp_socket->so_rcv,
898 		    &rack->rc_inp->inp_socket->so_snd,
899 		    BBR_LOG_RTO, 0,
900 		    0, &log, false);
901 	}
902 }
903 
904 static void
905 rack_log_rtt_upd(struct tcpcb *tp, struct tcp_rack *rack, int32_t t,
906     uint32_t o_srtt, uint32_t o_var)
907 {
908 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
909 		union tcp_log_stackspecific log;
910 
911 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
912 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
913 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
914 		log.u_bbr.flex1 = t;
915 		log.u_bbr.flex2 = o_srtt;
916 		log.u_bbr.flex3 = o_var;
917 		log.u_bbr.flex4 = rack->r_ctl.rack_rs.rs_rtt_lowest;
918 		log.u_bbr.flex5 = rack->r_ctl.rack_rs.rs_rtt_highest;
919 		log.u_bbr.flex6 = rack->r_ctl.rack_rs.rs_rtt_cnt;
920 		log.u_bbr.rttProp = rack->r_ctl.rack_rs.rs_rtt_tot;
921 		log.u_bbr.flex8 = rack->r_ctl.rc_rate_sample_method;
922 		TCP_LOG_EVENT(tp, NULL,
923 		    &rack->rc_inp->inp_socket->so_rcv,
924 		    &rack->rc_inp->inp_socket->so_snd,
925 		    BBR_LOG_BBRRTT, 0,
926 		    0, &log, false);
927 	}
928 }
929 
930 static void
931 rack_log_rtt_sample(struct tcp_rack *rack, uint32_t rtt)
932 {
933 	/*
934 	 * Log the rtt sample we are
935 	 * applying to the srtt algorithm in
936 	 * useconds.
937 	 */
938 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
939 		union tcp_log_stackspecific log;
940 		struct timeval tv;
941 
942 		/* Convert our ms to a microsecond */
943 		log.u_bbr.flex1 = rtt * 1000;
944 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
945 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
946 		    &rack->rc_inp->inp_socket->so_rcv,
947 		    &rack->rc_inp->inp_socket->so_snd,
948 		    TCP_LOG_RTT, 0,
949 		    0, &log, false, &tv);
950 	}
951 }
952 
953 
954 static inline void
955 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line)
956 {
957 	if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
958 		union tcp_log_stackspecific log;
959 
960 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
961 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
962 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
963 		log.u_bbr.flex1 = line;
964 		log.u_bbr.flex2 = tick;
965 		log.u_bbr.flex3 = tp->t_maxunacktime;
966 		log.u_bbr.flex4 = tp->t_acktime;
967 		log.u_bbr.flex8 = event;
968 		TCP_LOG_EVENT(tp, NULL,
969 		    &rack->rc_inp->inp_socket->so_rcv,
970 		    &rack->rc_inp->inp_socket->so_snd,
971 		    BBR_LOG_PROGRESS, 0,
972 		    0, &log, false);
973 	}
974 }
975 
976 static void
977 rack_log_type_bbrsnd(struct tcp_rack *rack, uint32_t len, uint32_t slot, uint32_t cts)
978 {
979 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
980 		union tcp_log_stackspecific log;
981 
982 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
983 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
984 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
985 		log.u_bbr.flex1 = slot;
986 		log.u_bbr.flex7 = (0x0000ffff & rack->r_ctl.rc_hpts_flags);
987 		log.u_bbr.flex8 = rack->rc_in_persist;
988 		TCP_LOG_EVENT(rack->rc_tp, NULL,
989 		    &rack->rc_inp->inp_socket->so_rcv,
990 		    &rack->rc_inp->inp_socket->so_snd,
991 		    BBR_LOG_BBRSND, 0,
992 		    0, &log, false);
993 	}
994 }
995 
996 static void
997 rack_log_doseg_done(struct tcp_rack *rack, uint32_t cts, int32_t nxt_pkt, int32_t did_out, int way_out)
998 {
999 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1000 		union tcp_log_stackspecific log;
1001 		log.u_bbr.flex1 = did_out;
1002 		log.u_bbr.flex2 = nxt_pkt;
1003 		log.u_bbr.flex3 = way_out;
1004 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
1005 		log.u_bbr.flex7 = rack->r_wanted_output;
1006 		log.u_bbr.flex8 = rack->rc_in_persist;
1007 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1008 		    &rack->rc_inp->inp_socket->so_rcv,
1009 		    &rack->rc_inp->inp_socket->so_snd,
1010 		    BBR_LOG_DOSEG_DONE, 0,
1011 		    0, &log, false);
1012 	}
1013 }
1014 
1015 
1016 static void
1017 rack_log_type_just_return(struct tcp_rack *rack, uint32_t cts, uint32_t tlen, uint32_t slot, uint8_t hpts_calling)
1018 {
1019 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1020 		union tcp_log_stackspecific log;
1021 
1022 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1023 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
1024 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
1025 		log.u_bbr.flex1 = slot;
1026 		log.u_bbr.flex2 = rack->r_ctl.rc_hpts_flags;
1027 		log.u_bbr.flex7 = hpts_calling;
1028 		log.u_bbr.flex8 = rack->rc_in_persist;
1029 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1030 		    &rack->rc_inp->inp_socket->so_rcv,
1031 		    &rack->rc_inp->inp_socket->so_snd,
1032 		    BBR_LOG_JUSTRET, 0,
1033 		    tlen, &log, false);
1034 	}
1035 }
1036 
1037 static void
1038 rack_log_to_cancel(struct tcp_rack *rack, int32_t hpts_removed, int line)
1039 {
1040 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1041 		union tcp_log_stackspecific log;
1042 
1043 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1044 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
1045 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
1046 		log.u_bbr.flex1 = line;
1047 		log.u_bbr.flex2 = 0;
1048 		log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
1049 		log.u_bbr.flex4 = 0;
1050 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
1051 		log.u_bbr.flex8 = hpts_removed;
1052 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1053 		    &rack->rc_inp->inp_socket->so_rcv,
1054 		    &rack->rc_inp->inp_socket->so_snd,
1055 		    BBR_LOG_TIMERCANC, 0,
1056 		    0, &log, false);
1057 	}
1058 }
1059 
1060 static void
1061 rack_log_to_processing(struct tcp_rack *rack, uint32_t cts, int32_t ret, int32_t timers)
1062 {
1063 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1064 		union tcp_log_stackspecific log;
1065 
1066 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
1067 		log.u_bbr.flex1 = timers;
1068 		log.u_bbr.flex2 = ret;
1069 		log.u_bbr.flex3 = rack->r_ctl.rc_timer_exp;
1070 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
1071 		log.u_bbr.flex5 = cts;
1072 		TCP_LOG_EVENT(rack->rc_tp, NULL,
1073 		    &rack->rc_inp->inp_socket->so_rcv,
1074 		    &rack->rc_inp->inp_socket->so_snd,
1075 		    BBR_LOG_TO_PROCESS, 0,
1076 		    0, &log, false);
1077 	}
1078 }
1079 
1080 static void
1081 rack_counter_destroy()
1082 {
1083 	counter_u64_free(rack_badfr);
1084 	counter_u64_free(rack_badfr_bytes);
1085 	counter_u64_free(rack_rtm_prr_retran);
1086 	counter_u64_free(rack_rtm_prr_newdata);
1087 	counter_u64_free(rack_timestamp_mismatch);
1088 	counter_u64_free(rack_reorder_seen);
1089 	counter_u64_free(rack_tlp_tot);
1090 	counter_u64_free(rack_tlp_newdata);
1091 	counter_u64_free(rack_tlp_retran);
1092 	counter_u64_free(rack_tlp_retran_bytes);
1093 	counter_u64_free(rack_tlp_retran_fail);
1094 	counter_u64_free(rack_to_tot);
1095 	counter_u64_free(rack_to_arm_rack);
1096 	counter_u64_free(rack_to_arm_tlp);
1097 	counter_u64_free(rack_paced_segments);
1098 	counter_u64_free(rack_unpaced_segments);
1099 	counter_u64_free(rack_saw_enobuf);
1100 	counter_u64_free(rack_saw_enetunreach);
1101 	counter_u64_free(rack_to_alloc_hard);
1102 	counter_u64_free(rack_to_alloc_emerg);
1103 	counter_u64_free(rack_sack_proc_all);
1104 	counter_u64_free(rack_sack_proc_short);
1105 	counter_u64_free(rack_sack_proc_restart);
1106 	counter_u64_free(rack_to_alloc);
1107 	counter_u64_free(rack_find_high);
1108 	counter_u64_free(rack_runt_sacks);
1109 	counter_u64_free(rack_enter_tlp_calc);
1110 	counter_u64_free(rack_used_tlpmethod);
1111 	counter_u64_free(rack_used_tlpmethod2);
1112 	counter_u64_free(rack_progress_drops);
1113 	counter_u64_free(rack_input_idle_reduces);
1114 	counter_u64_free(rack_tlp_does_nada);
1115 	COUNTER_ARRAY_FREE(rack_out_size, TCP_MSS_ACCT_SIZE);
1116 	COUNTER_ARRAY_FREE(rack_opts_arry, RACK_OPTS_SIZE);
1117 }
1118 
1119 static struct rack_sendmap *
1120 rack_alloc(struct tcp_rack *rack)
1121 {
1122 	struct rack_sendmap *rsm;
1123 
1124 	counter_u64_add(rack_to_alloc, 1);
1125 	rack->r_ctl.rc_num_maps_alloced++;
1126 	rsm = uma_zalloc(rack_zone, M_NOWAIT);
1127 	if (rsm) {
1128 		return (rsm);
1129 	}
1130 	if (rack->rc_free_cnt) {
1131 		counter_u64_add(rack_to_alloc_emerg, 1);
1132 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
1133 		TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_next);
1134 		rack->rc_free_cnt--;
1135 		return (rsm);
1136 	}
1137 	return (NULL);
1138 }
1139 
1140 static void
1141 rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm)
1142 {
1143 	rack->r_ctl.rc_num_maps_alloced--;
1144 	if (rack->r_ctl.rc_tlpsend == rsm)
1145 		rack->r_ctl.rc_tlpsend = NULL;
1146 	if (rack->r_ctl.rc_next == rsm)
1147 		rack->r_ctl.rc_next = NULL;
1148 	if (rack->r_ctl.rc_sacklast == rsm)
1149 		rack->r_ctl.rc_sacklast = NULL;
1150 	if (rack->rc_free_cnt < rack_free_cache) {
1151 		memset(rsm, 0, sizeof(struct rack_sendmap));
1152 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_next);
1153 		rack->rc_free_cnt++;
1154 		return;
1155 	}
1156 	uma_zfree(rack_zone, rsm);
1157 }
1158 
1159 /*
1160  * CC wrapper hook functions
1161  */
1162 static void
1163 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack, struct tcphdr *th, uint16_t nsegs,
1164     uint16_t type, int32_t recovery)
1165 {
1166 #ifdef NETFLIX_STATS
1167 	int32_t gput;
1168 #endif
1169 #ifdef NETFLIX_CWV
1170 	u_long old_cwnd = tp->snd_cwnd;
1171 #endif
1172 
1173 	INP_WLOCK_ASSERT(tp->t_inpcb);
1174 	tp->ccv->nsegs = nsegs;
1175 	tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
1176 	if ((recovery) && (rack->r_ctl.rc_early_recovery_segs)) {
1177 		uint32_t max;
1178 
1179 		max = rack->r_ctl.rc_early_recovery_segs * tp->t_maxseg;
1180 		if (tp->ccv->bytes_this_ack > max) {
1181 			tp->ccv->bytes_this_ack = max;
1182 		}
1183 	}
1184 	if (tp->snd_cwnd <= tp->snd_wnd)
1185 		tp->ccv->flags |= CCF_CWND_LIMITED;
1186 	else
1187 		tp->ccv->flags &= ~CCF_CWND_LIMITED;
1188 
1189 	if (type == CC_ACK) {
1190 #ifdef NETFLIX_STATS
1191 		stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
1192 		    ((int32_t) tp->snd_cwnd) - tp->snd_wnd);
1193 		if ((tp->t_flags & TF_GPUTINPROG) &&
1194 		    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
1195 			gput = (((int64_t) (th->th_ack - tp->gput_seq)) << 3) /
1196 			    max(1, tcp_ts_getticks() - tp->gput_ts);
1197 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
1198 			    gput);
1199 			/*
1200 			 * XXXLAS: This is a temporary hack, and should be
1201 			 * chained off VOI_TCP_GPUT when stats(9) grows an
1202 			 * API to deal with chained VOIs.
1203 			 */
1204 			if (tp->t_stats_gput_prev > 0)
1205 				stats_voi_update_abs_s32(tp->t_stats,
1206 				    VOI_TCP_GPUT_ND,
1207 				    ((gput - tp->t_stats_gput_prev) * 100) /
1208 				    tp->t_stats_gput_prev);
1209 			tp->t_flags &= ~TF_GPUTINPROG;
1210 			tp->t_stats_gput_prev = gput;
1211 #ifdef NETFLIX_CWV
1212 			if (tp->t_maxpeakrate) {
1213 				/*
1214 				 * We update t_peakrate_thr. This gives us roughly
1215 				 * one update per round trip time.
1216 				 */
1217 				tcp_update_peakrate_thr(tp);
1218 			}
1219 #endif
1220 		}
1221 #endif
1222 		if (tp->snd_cwnd > tp->snd_ssthresh) {
1223 			tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
1224 			    nsegs * V_tcp_abc_l_var * tp->t_maxseg);
1225 			if (tp->t_bytes_acked >= tp->snd_cwnd) {
1226 				tp->t_bytes_acked -= tp->snd_cwnd;
1227 				tp->ccv->flags |= CCF_ABC_SENTAWND;
1228 			}
1229 		} else {
1230 			tp->ccv->flags &= ~CCF_ABC_SENTAWND;
1231 			tp->t_bytes_acked = 0;
1232 		}
1233 	}
1234 	if (CC_ALGO(tp)->ack_received != NULL) {
1235 		/* XXXLAS: Find a way to live without this */
1236 		tp->ccv->curack = th->th_ack;
1237 		CC_ALGO(tp)->ack_received(tp->ccv, type);
1238 	}
1239 #ifdef NETFLIX_STATS
1240 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, tp->snd_cwnd);
1241 #endif
1242 	if (rack->r_ctl.rc_rack_largest_cwnd < tp->snd_cwnd) {
1243 		rack->r_ctl.rc_rack_largest_cwnd = tp->snd_cwnd;
1244 	}
1245 #ifdef NETFLIX_CWV
1246 	if (tp->cwv_enabled) {
1247 		/*
1248 		 * Per RFC 7661: The behaviour in the non-validated phase is
1249 		 * specified as: o  A sender determines whether to increase
1250 		 * the cwnd based upon whether it is cwnd-limited (see
1251 		 * Section 4.5.3): * A sender that is cwnd-limited MAY use
1252 		 * the standard TCP method to increase cwnd (i.e., the
1253 		 * standard method permits a TCP sender that fully utilises
1254 		 * the cwnd to increase the cwnd each time it receives an
1255 		 * ACK). * A sender that is not cwnd-limited MUST NOT
1256 		 * increase the cwnd when ACK packets are received in this
1257 		 * phase (i.e., needs to avoid growing the cwnd when it has
1258 		 * not recently sent using the current size of cwnd).
1259 		 */
1260 		if ((tp->snd_cwnd > old_cwnd) &&
1261 		    (tp->cwv_cwnd_valid == 0) &&
1262 		    (!(tp->ccv->flags & CCF_CWND_LIMITED))) {
1263 			tp->snd_cwnd = old_cwnd;
1264 		}
1265 		/* Try to update pipeAck and NCWV state */
1266 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
1267 		    !IN_RECOVERY(tp->t_flags)) {
1268 			uint32_t data = sbavail(&(tp->t_inpcb->inp_socket->so_snd));
1269 
1270 			tcp_newcwv_update_pipeack(tp, data);
1271 		}
1272 	}
1273 	/* we enforce max peak rate if it is set. */
1274 	if (tp->t_peakrate_thr && tp->snd_cwnd > tp->t_peakrate_thr) {
1275 		tp->snd_cwnd = tp->t_peakrate_thr;
1276 	}
1277 #endif
1278 }
1279 
1280 static void
1281 tcp_rack_partialack(struct tcpcb *tp, struct tcphdr *th)
1282 {
1283 	struct tcp_rack *rack;
1284 
1285 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1286 	INP_WLOCK_ASSERT(tp->t_inpcb);
1287 	if (rack->r_ctl.rc_prr_sndcnt > 0)
1288 		rack->r_wanted_output++;
1289 }
1290 
1291 static void
1292 rack_post_recovery(struct tcpcb *tp, struct tcphdr *th)
1293 {
1294 	struct tcp_rack *rack;
1295 
1296 	INP_WLOCK_ASSERT(tp->t_inpcb);
1297 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1298 	if (CC_ALGO(tp)->post_recovery != NULL) {
1299 		tp->ccv->curack = th->th_ack;
1300 		CC_ALGO(tp)->post_recovery(tp->ccv);
1301 	}
1302 	/*
1303 	 * Here we can in theory adjust cwnd to be based on the number of
1304 	 * losses in the window (rack->r_ctl.rc_loss_count). This is done
1305 	 * based on the rack_use_proportional flag.
1306 	 */
1307 	if (rack->r_ctl.rc_prop_reduce && rack->r_ctl.rc_prop_rate) {
1308 		int32_t reduce;
1309 
1310 		reduce = (rack->r_ctl.rc_loss_count * rack->r_ctl.rc_prop_rate);
1311 		if (reduce > 50) {
1312 			reduce = 50;
1313 		}
1314 		tp->snd_cwnd -= ((reduce * tp->snd_cwnd) / 100);
1315 	} else {
1316 		if (tp->snd_cwnd > tp->snd_ssthresh) {
1317 			/* Drop us down to the ssthresh (1/2 cwnd at loss) */
1318 			tp->snd_cwnd = tp->snd_ssthresh;
1319 		}
1320 	}
1321 	if (rack->r_ctl.rc_prr_sndcnt > 0) {
1322 		/* Suck the next prr cnt back into cwnd */
1323 		tp->snd_cwnd += rack->r_ctl.rc_prr_sndcnt;
1324 		rack->r_ctl.rc_prr_sndcnt = 0;
1325 	}
1326 	EXIT_RECOVERY(tp->t_flags);
1327 
1328 
1329 #ifdef NETFLIX_CWV
1330 	if (tp->cwv_enabled) {
1331 		if ((tp->cwv_cwnd_valid == 0) &&
1332 		    (tp->snd_cwv.in_recovery))
1333 			tcp_newcwv_end_recovery(tp);
1334 	}
1335 #endif
1336 }
1337 
1338 static void
1339 rack_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
1340 {
1341 	struct tcp_rack *rack;
1342 
1343 	INP_WLOCK_ASSERT(tp->t_inpcb);
1344 
1345 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1346 	switch (type) {
1347 	case CC_NDUPACK:
1348 /*		rack->r_ctl.rc_ssthresh_set = 1;*/
1349 		if (!IN_FASTRECOVERY(tp->t_flags)) {
1350 			rack->r_ctl.rc_tlp_rtx_out = 0;
1351 			rack->r_ctl.rc_prr_delivered = 0;
1352 			rack->r_ctl.rc_prr_out = 0;
1353 			rack->r_ctl.rc_loss_count = 0;
1354 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
1355 			rack->r_ctl.rc_prr_recovery_fs = tp->snd_max - tp->snd_una;
1356 			tp->snd_recover = tp->snd_max;
1357 			if (tp->t_flags & TF_ECN_PERMIT)
1358 				tp->t_flags |= TF_ECN_SND_CWR;
1359 		}
1360 		break;
1361 	case CC_ECN:
1362 		if (!IN_CONGRECOVERY(tp->t_flags)) {
1363 			TCPSTAT_INC(tcps_ecn_rcwnd);
1364 			tp->snd_recover = tp->snd_max;
1365 			if (tp->t_flags & TF_ECN_PERMIT)
1366 				tp->t_flags |= TF_ECN_SND_CWR;
1367 		}
1368 		break;
1369 	case CC_RTO:
1370 		tp->t_dupacks = 0;
1371 		tp->t_bytes_acked = 0;
1372 		EXIT_RECOVERY(tp->t_flags);
1373 		tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1374 		    tp->t_maxseg) * tp->t_maxseg;
1375 		tp->snd_cwnd = tp->t_maxseg;
1376 		break;
1377 	case CC_RTO_ERR:
1378 		TCPSTAT_INC(tcps_sndrexmitbad);
1379 		/* RTO was unnecessary, so reset everything. */
1380 		tp->snd_cwnd = tp->snd_cwnd_prev;
1381 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
1382 		tp->snd_recover = tp->snd_recover_prev;
1383 		if (tp->t_flags & TF_WASFRECOVERY)
1384 			ENTER_FASTRECOVERY(tp->t_flags);
1385 		if (tp->t_flags & TF_WASCRECOVERY)
1386 			ENTER_CONGRECOVERY(tp->t_flags);
1387 		tp->snd_nxt = tp->snd_max;
1388 		tp->t_badrxtwin = 0;
1389 		break;
1390 	}
1391 
1392 	if (CC_ALGO(tp)->cong_signal != NULL) {
1393 		if (th != NULL)
1394 			tp->ccv->curack = th->th_ack;
1395 		CC_ALGO(tp)->cong_signal(tp->ccv, type);
1396 	}
1397 #ifdef NETFLIX_CWV
1398 	if (tp->cwv_enabled) {
1399 		if (tp->snd_cwv.in_recovery == 0 && IN_RECOVERY(tp->t_flags)) {
1400 			tcp_newcwv_enter_recovery(tp);
1401 		}
1402 		if (type == CC_RTO) {
1403 			tcp_newcwv_reset(tp);
1404 		}
1405 	}
1406 #endif
1407 }
1408 
1409 
1410 
1411 static inline void
1412 rack_cc_after_idle(struct tcpcb *tp, int reduce_largest)
1413 {
1414 	uint32_t i_cwnd;
1415 
1416 	INP_WLOCK_ASSERT(tp->t_inpcb);
1417 
1418 #ifdef NETFLIX_STATS
1419 	TCPSTAT_INC(tcps_idle_restarts);
1420 	if (tp->t_state == TCPS_ESTABLISHED)
1421 		TCPSTAT_INC(tcps_idle_estrestarts);
1422 #endif
1423 	if (CC_ALGO(tp)->after_idle != NULL)
1424 		CC_ALGO(tp)->after_idle(tp->ccv);
1425 
1426 	if (tp->snd_cwnd == 1)
1427 		i_cwnd = tp->t_maxseg;		/* SYN(-ACK) lost */
1428 	else
1429 		i_cwnd = tcp_compute_initwnd(tcp_maxseg(tp));
1430 
1431 	if (reduce_largest) {
1432 		/*
1433 		 * Do we reduce the largest cwnd to make
1434 		 * rack play nice on restart hptsi wise?
1435 		 */
1436 		if (((struct tcp_rack *)tp->t_fb_ptr)->r_ctl.rc_rack_largest_cwnd  > i_cwnd)
1437 			((struct tcp_rack *)tp->t_fb_ptr)->r_ctl.rc_rack_largest_cwnd = i_cwnd;
1438 	}
1439 	/*
1440 	 * Being idle is no differnt than the initial window. If the cc
1441 	 * clamps it down below the initial window raise it to the initial
1442 	 * window.
1443 	 */
1444 	if (tp->snd_cwnd < i_cwnd) {
1445 		tp->snd_cwnd = i_cwnd;
1446 	}
1447 }
1448 
1449 
1450 /*
1451  * Indicate whether this ack should be delayed.  We can delay the ack if
1452  * following conditions are met:
1453  *	- There is no delayed ack timer in progress.
1454  *	- Our last ack wasn't a 0-sized window. We never want to delay
1455  *	  the ack that opens up a 0-sized window.
1456  *	- LRO wasn't used for this segment. We make sure by checking that the
1457  *	  segment size is not larger than the MSS.
1458  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
1459  *	  connection.
1460  */
1461 #define DELAY_ACK(tp, tlen)			 \
1462 	(((tp->t_flags & TF_RXWIN0SENT) == 0) && \
1463 	((tp->t_flags & TF_DELACK) == 0) && 	 \
1464 	(tlen <= tp->t_maxseg) &&		 \
1465 	(tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
1466 
1467 static inline void
1468 rack_calc_rwin(struct socket *so, struct tcpcb *tp)
1469 {
1470 	int32_t win;
1471 
1472 	/*
1473 	 * Calculate amount of space in receive window, and then do TCP
1474 	 * input processing. Receive window is amount of space in rcv queue,
1475 	 * but not less than advertised window.
1476 	 */
1477 	win = sbspace(&so->so_rcv);
1478 	if (win < 0)
1479 		win = 0;
1480 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1481 }
1482 
1483 static void
1484 rack_do_drop(struct mbuf *m, struct tcpcb *tp)
1485 {
1486 	/*
1487 	 * Drop space held by incoming segment and return.
1488 	 */
1489 	if (tp != NULL)
1490 		INP_WUNLOCK(tp->t_inpcb);
1491 	if (m)
1492 		m_freem(m);
1493 }
1494 
1495 static void
1496 rack_do_dropwithreset(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th,
1497     int32_t rstreason, int32_t tlen)
1498 {
1499 	if (tp != NULL) {
1500 		tcp_dropwithreset(m, th, tp, tlen, rstreason);
1501 		INP_WUNLOCK(tp->t_inpcb);
1502 	} else
1503 		tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1504 }
1505 
1506 /*
1507  * The value in ret_val informs the caller
1508  * if we dropped the tcb (and lock) or not.
1509  * 1 = we dropped it, 0 = the TCB is still locked
1510  * and valid.
1511  */
1512 static void
1513 rack_do_dropafterack(struct mbuf *m, struct tcpcb *tp, struct tcphdr *th, int32_t thflags, int32_t tlen, int32_t * ret_val)
1514 {
1515 	/*
1516 	 * Generate an ACK dropping incoming segment if it occupies sequence
1517 	 * space, where the ACK reflects our state.
1518 	 *
1519 	 * We can now skip the test for the RST flag since all paths to this
1520 	 * code happen after packets containing RST have been dropped.
1521 	 *
1522 	 * In the SYN-RECEIVED state, don't send an ACK unless the segment
1523 	 * we received passes the SYN-RECEIVED ACK test. If it fails send a
1524 	 * RST.  This breaks the loop in the "LAND" DoS attack, and also
1525 	 * prevents an ACK storm between two listening ports that have been
1526 	 * sent forged SYN segments, each with the source address of the
1527 	 * other.
1528 	 */
1529 	struct tcp_rack *rack;
1530 
1531 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
1532 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
1533 	    SEQ_GT(th->th_ack, tp->snd_max))) {
1534 		*ret_val = 1;
1535 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
1536 		return;
1537 	} else
1538 		*ret_val = 0;
1539 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1540 	rack->r_wanted_output++;
1541 	tp->t_flags |= TF_ACKNOW;
1542 	if (m)
1543 		m_freem(m);
1544 }
1545 
1546 
1547 static int
1548 rack_process_rst(struct mbuf *m, struct tcphdr *th, struct socket *so, struct tcpcb *tp)
1549 {
1550 	/*
1551 	 * RFC5961 Section 3.2
1552 	 *
1553 	 * - RST drops connection only if SEG.SEQ == RCV.NXT. - If RST is in
1554 	 * window, we send challenge ACK.
1555 	 *
1556 	 * Note: to take into account delayed ACKs, we should test against
1557 	 * last_ack_sent instead of rcv_nxt. Note 2: we handle special case
1558 	 * of closed window, not covered by the RFC.
1559 	 */
1560 	int dropped = 0;
1561 
1562 	if ((SEQ_GEQ(th->th_seq, (tp->last_ack_sent - 1)) &&
1563 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
1564 	    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
1565 
1566 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1567 		KASSERT(tp->t_state != TCPS_SYN_SENT,
1568 		    ("%s: TH_RST for TCPS_SYN_SENT th %p tp %p",
1569 		    __func__, th, tp));
1570 
1571 		if (V_tcp_insecure_rst ||
1572 		    (tp->last_ack_sent == th->th_seq) ||
1573 		    (tp->rcv_nxt == th->th_seq) ||
1574 		    ((tp->last_ack_sent - 1) == th->th_seq)) {
1575 			TCPSTAT_INC(tcps_drops);
1576 			/* Drop the connection. */
1577 			switch (tp->t_state) {
1578 			case TCPS_SYN_RECEIVED:
1579 				so->so_error = ECONNREFUSED;
1580 				goto close;
1581 			case TCPS_ESTABLISHED:
1582 			case TCPS_FIN_WAIT_1:
1583 			case TCPS_FIN_WAIT_2:
1584 			case TCPS_CLOSE_WAIT:
1585 			case TCPS_CLOSING:
1586 			case TCPS_LAST_ACK:
1587 				so->so_error = ECONNRESET;
1588 		close:
1589 				tcp_state_change(tp, TCPS_CLOSED);
1590 				/* FALLTHROUGH */
1591 			default:
1592 				tp = tcp_close(tp);
1593 			}
1594 			dropped = 1;
1595 			rack_do_drop(m, tp);
1596 		} else {
1597 			TCPSTAT_INC(tcps_badrst);
1598 			/* Send challenge ACK. */
1599 			tcp_respond(tp, mtod(m, void *), th, m,
1600 			    tp->rcv_nxt, tp->snd_nxt, TH_ACK);
1601 			tp->last_ack_sent = tp->rcv_nxt;
1602 		}
1603 	} else {
1604 		m_freem(m);
1605 	}
1606 	return (dropped);
1607 }
1608 
1609 /*
1610  * The value in ret_val informs the caller
1611  * if we dropped the tcb (and lock) or not.
1612  * 1 = we dropped it, 0 = the TCB is still locked
1613  * and valid.
1614  */
1615 static void
1616 rack_challenge_ack(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * ret_val)
1617 {
1618 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1619 
1620 	TCPSTAT_INC(tcps_badsyn);
1621 	if (V_tcp_insecure_syn &&
1622 	    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1623 	    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1624 		tp = tcp_drop(tp, ECONNRESET);
1625 		*ret_val = 1;
1626 		rack_do_drop(m, tp);
1627 	} else {
1628 		/* Send challenge ACK. */
1629 		tcp_respond(tp, mtod(m, void *), th, m, tp->rcv_nxt,
1630 		    tp->snd_nxt, TH_ACK);
1631 		tp->last_ack_sent = tp->rcv_nxt;
1632 		m = NULL;
1633 		*ret_val = 0;
1634 		rack_do_drop(m, NULL);
1635 	}
1636 }
1637 
1638 /*
1639  * rack_ts_check returns 1 for you should not proceed. It places
1640  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
1641  * that the TCB is unlocked and probably dropped. The 0 indicates the
1642  * TCB is still valid and locked.
1643  */
1644 static int
1645 rack_ts_check(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t tlen, int32_t thflags, int32_t * ret_val)
1646 {
1647 
1648 	/* Check to see if ts_recent is over 24 days old.  */
1649 	if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
1650 		/*
1651 		 * Invalidate ts_recent.  If this segment updates ts_recent,
1652 		 * the age will be reset later and ts_recent will get a
1653 		 * valid value.  If it does not, setting ts_recent to zero
1654 		 * will at least satisfy the requirement that zero be placed
1655 		 * in the timestamp echo reply when ts_recent isn't valid.
1656 		 * The age isn't reset until we get a valid ts_recent
1657 		 * because we don't want out-of-order segments to be dropped
1658 		 * when ts_recent is old.
1659 		 */
1660 		tp->ts_recent = 0;
1661 	} else {
1662 		TCPSTAT_INC(tcps_rcvduppack);
1663 		TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1664 		TCPSTAT_INC(tcps_pawsdrop);
1665 		*ret_val = 0;
1666 		if (tlen) {
1667 			rack_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
1668 		} else {
1669 			rack_do_drop(m, NULL);
1670 		}
1671 		return (1);
1672 	}
1673 	return (0);
1674 }
1675 
1676 /*
1677  * rack_drop_checks returns 1 for you should not proceed. It places
1678  * in ret_val what should be returned 1/0 by the caller. The 1 indicates
1679  * that the TCB is unlocked and probably dropped. The 0 indicates the
1680  * TCB is still valid and locked.
1681  */
1682 static int
1683 rack_drop_checks(struct tcpopt *to, struct mbuf *m, struct tcphdr *th, struct tcpcb *tp, int32_t * tlenp,  int32_t * thf, int32_t * drop_hdrlen, int32_t * ret_val)
1684 {
1685 	int32_t todrop;
1686 	int32_t thflags;
1687 	int32_t tlen;
1688 
1689 	thflags = *thf;
1690 	tlen = *tlenp;
1691 	todrop = tp->rcv_nxt - th->th_seq;
1692 	if (todrop > 0) {
1693 		if (thflags & TH_SYN) {
1694 			thflags &= ~TH_SYN;
1695 			th->th_seq++;
1696 			if (th->th_urp > 1)
1697 				th->th_urp--;
1698 			else
1699 				thflags &= ~TH_URG;
1700 			todrop--;
1701 		}
1702 		/*
1703 		 * Following if statement from Stevens, vol. 2, p. 960.
1704 		 */
1705 		if (todrop > tlen
1706 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1707 			/*
1708 			 * Any valid FIN must be to the left of the window.
1709 			 * At this point the FIN must be a duplicate or out
1710 			 * of sequence; drop it.
1711 			 */
1712 			thflags &= ~TH_FIN;
1713 			/*
1714 			 * Send an ACK to resynchronize and drop any data.
1715 			 * But keep on processing for RST or ACK.
1716 			 */
1717 			tp->t_flags |= TF_ACKNOW;
1718 			todrop = tlen;
1719 			TCPSTAT_INC(tcps_rcvduppack);
1720 			TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1721 		} else {
1722 			TCPSTAT_INC(tcps_rcvpartduppack);
1723 			TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1724 		}
1725 		*drop_hdrlen += todrop;	/* drop from the top afterwards */
1726 		th->th_seq += todrop;
1727 		tlen -= todrop;
1728 		if (th->th_urp > todrop)
1729 			th->th_urp -= todrop;
1730 		else {
1731 			thflags &= ~TH_URG;
1732 			th->th_urp = 0;
1733 		}
1734 	}
1735 	/*
1736 	 * If segment ends after window, drop trailing data (and PUSH and
1737 	 * FIN); if nothing left, just ACK.
1738 	 */
1739 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1740 	if (todrop > 0) {
1741 		TCPSTAT_INC(tcps_rcvpackafterwin);
1742 		if (todrop >= tlen) {
1743 			TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1744 			/*
1745 			 * If window is closed can only take segments at
1746 			 * window edge, and have to drop data and PUSH from
1747 			 * incoming segments.  Continue processing, but
1748 			 * remember to ack.  Otherwise, drop segment and
1749 			 * ack.
1750 			 */
1751 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1752 				tp->t_flags |= TF_ACKNOW;
1753 				TCPSTAT_INC(tcps_rcvwinprobe);
1754 			} else {
1755 				rack_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
1756 				return (1);
1757 			}
1758 		} else
1759 			TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1760 		m_adj(m, -todrop);
1761 		tlen -= todrop;
1762 		thflags &= ~(TH_PUSH | TH_FIN);
1763 	}
1764 	*thf = thflags;
1765 	*tlenp = tlen;
1766 	return (0);
1767 }
1768 
1769 static struct rack_sendmap *
1770 rack_find_lowest_rsm(struct tcp_rack *rack)
1771 {
1772 	struct rack_sendmap *rsm;
1773 
1774 	/*
1775 	 * Walk the time-order transmitted list looking for an rsm that is
1776 	 * not acked. This will be the one that was sent the longest time
1777 	 * ago that is still outstanding.
1778 	 */
1779 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
1780 		if (rsm->r_flags & RACK_ACKED) {
1781 			continue;
1782 		}
1783 		goto finish;
1784 	}
1785 finish:
1786 	return (rsm);
1787 }
1788 
1789 static struct rack_sendmap *
1790 rack_find_high_nonack(struct tcp_rack *rack, struct rack_sendmap *rsm)
1791 {
1792 	struct rack_sendmap *prsm;
1793 
1794 	/*
1795 	 * Walk the sequence order list backward until we hit and arrive at
1796 	 * the highest seq not acked. In theory when this is called it
1797 	 * should be the last segment (which it was not).
1798 	 */
1799 	counter_u64_add(rack_find_high, 1);
1800 	prsm = rsm;
1801 	TAILQ_FOREACH_REVERSE_FROM(prsm, &rack->r_ctl.rc_map, rack_head, r_next) {
1802 		if (prsm->r_flags & (RACK_ACKED | RACK_HAS_FIN)) {
1803 			continue;
1804 		}
1805 		return (prsm);
1806 	}
1807 	return (NULL);
1808 }
1809 
1810 
1811 static uint32_t
1812 rack_calc_thresh_rack(struct tcp_rack *rack, uint32_t srtt, uint32_t cts)
1813 {
1814 	int32_t lro;
1815 	uint32_t thresh;
1816 
1817 	/*
1818 	 * lro is the flag we use to determine if we have seen reordering.
1819 	 * If it gets set we have seen reordering. The reorder logic either
1820 	 * works in one of two ways:
1821 	 *
1822 	 * If reorder-fade is configured, then we track the last time we saw
1823 	 * re-ordering occur. If we reach the point where enough time as
1824 	 * passed we no longer consider reordering has occuring.
1825 	 *
1826 	 * Or if reorder-face is 0, then once we see reordering we consider
1827 	 * the connection to alway be subject to reordering and just set lro
1828 	 * to 1.
1829 	 *
1830 	 * In the end if lro is non-zero we add the extra time for
1831 	 * reordering in.
1832 	 */
1833 	if (srtt == 0)
1834 		srtt = 1;
1835 	if (rack->r_ctl.rc_reorder_ts) {
1836 		if (rack->r_ctl.rc_reorder_fade) {
1837 			if (SEQ_GEQ(cts, rack->r_ctl.rc_reorder_ts)) {
1838 				lro = cts - rack->r_ctl.rc_reorder_ts;
1839 				if (lro == 0) {
1840 					/*
1841 					 * No time as passed since the last
1842 					 * reorder, mark it as reordering.
1843 					 */
1844 					lro = 1;
1845 				}
1846 			} else {
1847 				/* Negative time? */
1848 				lro = 0;
1849 			}
1850 			if (lro > rack->r_ctl.rc_reorder_fade) {
1851 				/* Turn off reordering seen too */
1852 				rack->r_ctl.rc_reorder_ts = 0;
1853 				lro = 0;
1854 			}
1855 		} else {
1856 			/* Reodering does not fade */
1857 			lro = 1;
1858 		}
1859 	} else {
1860 		lro = 0;
1861 	}
1862 	thresh = srtt + rack->r_ctl.rc_pkt_delay;
1863 	if (lro) {
1864 		/* It must be set, if not you get 1/4 rtt */
1865 		if (rack->r_ctl.rc_reorder_shift)
1866 			thresh += (srtt >> rack->r_ctl.rc_reorder_shift);
1867 		else
1868 			thresh += (srtt >> 2);
1869 	} else {
1870 		thresh += 1;
1871 	}
1872 	/* We don't let the rack timeout be above a RTO */
1873 
1874 	if (thresh > TICKS_2_MSEC(rack->rc_tp->t_rxtcur)) {
1875 		thresh = TICKS_2_MSEC(rack->rc_tp->t_rxtcur);
1876 	}
1877 	/* And we don't want it above the RTO max either */
1878 	if (thresh > rack_rto_max) {
1879 		thresh = rack_rto_max;
1880 	}
1881 	return (thresh);
1882 }
1883 
1884 static uint32_t
1885 rack_calc_thresh_tlp(struct tcpcb *tp, struct tcp_rack *rack,
1886 		     struct rack_sendmap *rsm, uint32_t srtt)
1887 {
1888 	struct rack_sendmap *prsm;
1889 	uint32_t thresh, len;
1890 	int maxseg;
1891 
1892 	if (srtt == 0)
1893 		srtt = 1;
1894 	if (rack->r_ctl.rc_tlp_threshold)
1895 		thresh = srtt + (srtt / rack->r_ctl.rc_tlp_threshold);
1896 	else
1897 		thresh = (srtt * 2);
1898 
1899 	/* Get the previous sent packet, if any  */
1900 	maxseg = tcp_maxseg(tp);
1901 	counter_u64_add(rack_enter_tlp_calc, 1);
1902 	len = rsm->r_end - rsm->r_start;
1903 	if (rack->rack_tlp_threshold_use == TLP_USE_ID) {
1904 		/* Exactly like the ID */
1905 		if (((tp->snd_max - tp->snd_una) - rack->r_ctl.rc_sacked + rack->r_ctl.rc_holes_rxt) <= maxseg) {
1906 			uint32_t alt_thresh;
1907 			/*
1908 			 * Compensate for delayed-ack with the d-ack time.
1909 			 */
1910 			counter_u64_add(rack_used_tlpmethod, 1);
1911 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
1912 			if (alt_thresh > thresh)
1913 				thresh = alt_thresh;
1914 		}
1915 	} else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_ONE) {
1916 		/* 2.1 behavior */
1917 		prsm = TAILQ_PREV(rsm, rack_head, r_tnext);
1918 		if (prsm && (len <= maxseg)) {
1919 			/*
1920 			 * Two packets outstanding, thresh should be (2*srtt) +
1921 			 * possible inter-packet delay (if any).
1922 			 */
1923 			uint32_t inter_gap = 0;
1924 			int idx, nidx;
1925 
1926 			counter_u64_add(rack_used_tlpmethod, 1);
1927 			idx = rsm->r_rtr_cnt - 1;
1928 			nidx = prsm->r_rtr_cnt - 1;
1929 			if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
1930 				/* Yes it was sent later (or at the same time) */
1931 				inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
1932 			}
1933 			thresh += inter_gap;
1934 		} else 	if (len <= maxseg) {
1935 			/*
1936 			 * Possibly compensate for delayed-ack.
1937 			 */
1938 			uint32_t alt_thresh;
1939 
1940 			counter_u64_add(rack_used_tlpmethod2, 1);
1941 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
1942 			if (alt_thresh > thresh)
1943 				thresh = alt_thresh;
1944 		}
1945 	} else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_TWO) {
1946 		/* 2.2 behavior */
1947 		if (len <= maxseg) {
1948 			uint32_t alt_thresh;
1949 			/*
1950 			 * Compensate for delayed-ack with the d-ack time.
1951 			 */
1952 			counter_u64_add(rack_used_tlpmethod, 1);
1953 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
1954 			if (alt_thresh > thresh)
1955 				thresh = alt_thresh;
1956 		}
1957 	}
1958  	/* Not above an RTO */
1959 	if (thresh > TICKS_2_MSEC(tp->t_rxtcur)) {
1960 		thresh = TICKS_2_MSEC(tp->t_rxtcur);
1961 	}
1962 	/* Not above a RTO max */
1963 	if (thresh > rack_rto_max) {
1964 		thresh = rack_rto_max;
1965 	}
1966 	/* Apply user supplied min TLP */
1967 	if (thresh < rack_tlp_min) {
1968 		thresh = rack_tlp_min;
1969 	}
1970 	return (thresh);
1971 }
1972 
1973 static struct rack_sendmap *
1974 rack_check_recovery_mode(struct tcpcb *tp, uint32_t tsused)
1975 {
1976 	/*
1977 	 * Check to see that we don't need to fall into recovery. We will
1978 	 * need to do so if our oldest transmit is past the time we should
1979 	 * have had an ack.
1980 	 */
1981 	struct tcp_rack *rack;
1982 	struct rack_sendmap *rsm;
1983 	int32_t idx;
1984 	uint32_t srtt_cur, srtt, thresh;
1985 
1986 	rack = (struct tcp_rack *)tp->t_fb_ptr;
1987 	if (TAILQ_EMPTY(&rack->r_ctl.rc_map)) {
1988 		return (NULL);
1989 	}
1990 	srtt_cur = tp->t_srtt >> TCP_RTT_SHIFT;
1991 	srtt = TICKS_2_MSEC(srtt_cur);
1992 	if (rack->rc_rack_rtt && (srtt > rack->rc_rack_rtt))
1993 		srtt = rack->rc_rack_rtt;
1994 
1995 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
1996 	if (rsm == NULL)
1997 		return (NULL);
1998 
1999 	if (rsm->r_flags & RACK_ACKED) {
2000 		rsm = rack_find_lowest_rsm(rack);
2001 		if (rsm == NULL)
2002 			return (NULL);
2003 	}
2004 	idx = rsm->r_rtr_cnt - 1;
2005 	thresh = rack_calc_thresh_rack(rack, srtt, tsused);
2006 	if (tsused < rsm->r_tim_lastsent[idx]) {
2007 		return (NULL);
2008 	}
2009 	if ((tsused - rsm->r_tim_lastsent[idx]) < thresh) {
2010 		return (NULL);
2011 	}
2012 	/* Ok if we reach here we are over-due */
2013 	rack->r_ctl.rc_rsm_start = rsm->r_start;
2014 	rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
2015 	rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
2016 	rack_cong_signal(tp, NULL, CC_NDUPACK);
2017 	return (rsm);
2018 }
2019 
2020 static uint32_t
2021 rack_get_persists_timer_val(struct tcpcb *tp, struct tcp_rack *rack)
2022 {
2023 	int32_t t;
2024 	int32_t tt;
2025 	uint32_t ret_val;
2026 
2027 	t = TICKS_2_MSEC((tp->t_srtt >> TCP_RTT_SHIFT) + ((tp->t_rttvar * 4) >> TCP_RTT_SHIFT));
2028 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
2029 	    tcp_persmin, tcp_persmax);
2030 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
2031 		tp->t_rxtshift++;
2032 	rack->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
2033 	ret_val = (uint32_t)tt;
2034 	return (ret_val);
2035 }
2036 
2037 static uint32_t
2038 rack_timer_start(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2039 {
2040 	/*
2041 	 * Start the FR timer, we do this based on getting the first one in
2042 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
2043 	 * events we need to stop the running timer (if its running) before
2044 	 * starting the new one.
2045 	 */
2046 	uint32_t thresh, exp, to, srtt, time_since_sent;
2047 	uint32_t srtt_cur;
2048 	int32_t idx;
2049 	int32_t is_tlp_timer = 0;
2050 	struct rack_sendmap *rsm;
2051 
2052 	if (rack->t_timers_stopped) {
2053 		/* All timers have been stopped none are to run */
2054 		return (0);
2055 	}
2056 	if (rack->rc_in_persist) {
2057 		/* We can't start any timer in persists */
2058 		return (rack_get_persists_timer_val(tp, rack));
2059 	}
2060 	if (tp->t_state < TCPS_ESTABLISHED)
2061 		goto activate_rxt;
2062 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2063 	if (rsm == NULL) {
2064 		/* Nothing on the send map */
2065 activate_rxt:
2066 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
2067 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
2068 			to = TICKS_2_MSEC(tp->t_rxtcur);
2069 			if (to == 0)
2070 				to = 1;
2071 			return (to);
2072 		}
2073 		return (0);
2074 	}
2075 	if (rsm->r_flags & RACK_ACKED) {
2076 		rsm = rack_find_lowest_rsm(rack);
2077 		if (rsm == NULL) {
2078 			/* No lowest? */
2079 			goto activate_rxt;
2080 		}
2081 	}
2082 	/* Convert from ms to usecs */
2083 	if (rsm->r_flags & RACK_SACK_PASSED) {
2084 		if ((tp->t_flags & TF_SENTFIN) &&
2085 		    ((tp->snd_max - tp->snd_una) == 1) &&
2086 		    (rsm->r_flags & RACK_HAS_FIN)) {
2087 			/*
2088 			 * We don't start a rack timer if all we have is a
2089 			 * FIN outstanding.
2090 			 */
2091 			goto activate_rxt;
2092 		}
2093 		if (tp->t_srtt) {
2094 			srtt_cur = (tp->t_srtt >> TCP_RTT_SHIFT);
2095 			srtt = TICKS_2_MSEC(srtt_cur);
2096 		} else
2097 			srtt = RACK_INITIAL_RTO;
2098 
2099 		thresh = rack_calc_thresh_rack(rack, srtt, cts);
2100 		idx = rsm->r_rtr_cnt - 1;
2101 		exp = rsm->r_tim_lastsent[idx] + thresh;
2102 		if (SEQ_GEQ(exp, cts)) {
2103 			to = exp - cts;
2104 			if (to < rack->r_ctl.rc_min_to) {
2105 				to = rack->r_ctl.rc_min_to;
2106 			}
2107 		} else {
2108 			to = rack->r_ctl.rc_min_to;
2109 		}
2110 	} else {
2111 		/* Ok we need to do a TLP not RACK */
2112 		if ((rack->rc_tlp_in_progress != 0) ||
2113 		    (rack->r_ctl.rc_tlp_rtx_out != 0)) {
2114 			/*
2115 			 * The previous send was a TLP or a tlp_rtx is in
2116 			 * process.
2117 			 */
2118 			goto activate_rxt;
2119 		}
2120 		rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
2121 		if (rsm == NULL) {
2122 			/* We found no rsm to TLP with. */
2123 			goto activate_rxt;
2124 		}
2125 		if (rsm->r_flags & RACK_HAS_FIN) {
2126 			/* If its a FIN we dont do TLP */
2127 			rsm = NULL;
2128 			goto activate_rxt;
2129 		}
2130 		idx = rsm->r_rtr_cnt - 1;
2131 		if (TSTMP_GT(cts,  rsm->r_tim_lastsent[idx]))
2132 			time_since_sent = cts - rsm->r_tim_lastsent[idx];
2133 		else
2134 			time_since_sent = 0;
2135 		is_tlp_timer = 1;
2136 		if (tp->t_srtt) {
2137 			srtt_cur = (tp->t_srtt >> TCP_RTT_SHIFT);
2138 			srtt = TICKS_2_MSEC(srtt_cur);
2139 		} else
2140 			srtt = RACK_INITIAL_RTO;
2141 		thresh = rack_calc_thresh_tlp(tp, rack, rsm, srtt);
2142 		if (thresh > time_since_sent)
2143 			to = thresh - time_since_sent;
2144 		else
2145 			to = rack->r_ctl.rc_min_to;
2146 		if (to > TCPTV_REXMTMAX) {
2147 			/*
2148 			 * If the TLP time works out to larger than the max
2149 			 * RTO lets not do TLP.. just RTO.
2150 			 */
2151 			goto activate_rxt;
2152 		}
2153 		if (rsm->r_start != rack->r_ctl.rc_last_tlp_seq) {
2154 			/*
2155 			 * The tail is no longer the last one I did a probe
2156 			 * on
2157 			 */
2158 			rack->r_ctl.rc_tlp_seg_send_cnt = 0;
2159 			rack->r_ctl.rc_last_tlp_seq = rsm->r_start;
2160 		}
2161 	}
2162 	if (is_tlp_timer == 0) {
2163 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
2164 	} else {
2165 		if ((rack->r_ctl.rc_tlp_send_cnt > rack_tlp_max_resend) ||
2166 		    (rack->r_ctl.rc_tlp_seg_send_cnt > rack_tlp_max_resend)) {
2167 			/*
2168 			 * We have exceeded how many times we can retran the
2169 			 * current TLP timer, switch to the RTO timer.
2170 			 */
2171 			goto activate_rxt;
2172 		} else {
2173 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
2174 		}
2175 	}
2176 	if (to == 0)
2177 		to = 1;
2178 	return (to);
2179 }
2180 
2181 static void
2182 rack_enter_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2183 {
2184 	if (rack->rc_in_persist == 0) {
2185 		if (((tp->t_flags & TF_SENTFIN) == 0) &&
2186 		    (tp->snd_max - tp->snd_una) >= sbavail(&rack->rc_inp->inp_socket->so_snd))
2187 			/* Must need to send more data to enter persist */
2188 			return;
2189 		rack->r_ctl.rc_went_idle_time = cts;
2190 		rack_timer_cancel(tp, rack, cts, __LINE__);
2191 		tp->t_rxtshift = 0;
2192 		rack->rc_in_persist = 1;
2193 	}
2194 }
2195 
2196 static void
2197 rack_exit_persist(struct tcpcb *tp, struct tcp_rack *rack)
2198 {
2199 	if (rack->rc_inp->inp_in_hpts)  {
2200 		tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
2201 		rack->r_ctl.rc_hpts_flags  = 0;
2202 	}
2203 	rack->rc_in_persist = 0;
2204 	rack->r_ctl.rc_went_idle_time = 0;
2205 	tp->t_flags &= ~TF_FORCEDATA;
2206 	tp->t_rxtshift = 0;
2207 }
2208 
2209 static void
2210 rack_start_hpts_timer(struct tcp_rack *rack, struct tcpcb *tp, uint32_t cts, int32_t line,
2211     int32_t slot, uint32_t tot_len_this_send, int32_t frm_out_sbavail)
2212 {
2213 	struct inpcb *inp;
2214 	uint32_t delayed_ack = 0;
2215 	uint32_t hpts_timeout;
2216 	uint8_t stopped;
2217 	uint32_t left = 0;
2218 
2219 	inp = tp->t_inpcb;
2220 	if (inp->inp_in_hpts) {
2221 		/* A previous call is already set up */
2222 		return;
2223 	}
2224 	if (tp->t_state == TCPS_CLOSED) {
2225 		return;
2226 	}
2227 	stopped = rack->rc_tmr_stopped;
2228 	if (stopped && TSTMP_GT(rack->r_ctl.rc_timer_exp, cts)) {
2229 		left = rack->r_ctl.rc_timer_exp - cts;
2230 	}
2231 	rack->r_ctl.rc_timer_exp = 0;
2232 	if (rack->rc_inp->inp_in_hpts == 0) {
2233 		rack->r_ctl.rc_hpts_flags = 0;
2234 	}
2235 	if (slot) {
2236 		/* We are hptsi too */
2237 		rack->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
2238 	} else if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
2239 		/*
2240 		 * We are still left on the hpts when the to goes
2241 		 * it will be for output.
2242 		 */
2243 		if (TSTMP_GT(cts, rack->r_ctl.rc_last_output_to))
2244 			slot = cts - rack->r_ctl.rc_last_output_to;
2245 		else
2246 			slot = 1;
2247 	}
2248 	if ((tp->snd_wnd == 0) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2249 		/* No send window.. we must enter persist */
2250 		rack_enter_persist(tp, rack, cts);
2251 	} else if ((frm_out_sbavail &&
2252 		    (frm_out_sbavail > (tp->snd_max - tp->snd_una)) &&
2253 		    (tp->snd_wnd < tp->t_maxseg)) &&
2254 	    TCPS_HAVEESTABLISHED(tp->t_state)) {
2255 		/*
2256 		 * If we have no window or we can't send a segment (and have
2257 		 * data to send.. we cheat here and frm_out_sbavail is
2258 		 * passed in with the sbavail(sb) only from bbr_output) and
2259 		 * we are established, then we must enter persits (if not
2260 		 * already in persits).
2261 		 */
2262 		rack_enter_persist(tp, rack, cts);
2263 	}
2264 	hpts_timeout = rack_timer_start(tp, rack, cts);
2265 	if (tp->t_flags & TF_DELACK) {
2266 		delayed_ack = TICKS_2_MSEC(tcp_delacktime);
2267 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_DELACK;
2268 	}
2269 	if (delayed_ack && ((hpts_timeout == 0) ||
2270 			    (delayed_ack < hpts_timeout)))
2271 		hpts_timeout = delayed_ack;
2272 	else
2273 		rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
2274 	/*
2275 	 * If no timers are going to run and we will fall off the hptsi
2276 	 * wheel, we resort to a keep-alive timer if its configured.
2277 	 */
2278 	if ((hpts_timeout == 0) &&
2279 	    (slot == 0)) {
2280 		if ((tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
2281 		    (tp->t_state <= TCPS_CLOSING)) {
2282 			/*
2283 			 * Ok we have no timer (persists, rack, tlp, rxt  or
2284 			 * del-ack), we don't have segments being paced. So
2285 			 * all that is left is the keepalive timer.
2286 			 */
2287 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
2288 				/* Get the established keep-alive time */
2289 				hpts_timeout = TP_KEEPIDLE(tp);
2290 			} else {
2291 				/* Get the initial setup keep-alive time */
2292 				hpts_timeout = TP_KEEPINIT(tp);
2293 			}
2294 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
2295 		}
2296 	}
2297 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
2298 	    (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
2299 		/*
2300 		 * RACK, TLP, persists and RXT timers all are restartable
2301 		 * based on actions input .. i.e we received a packet (ack
2302 		 * or sack) and that changes things (rw, or snd_una etc).
2303 		 * Thus we can restart them with a new value. For
2304 		 * keep-alive, delayed_ack we keep track of what was left
2305 		 * and restart the timer with a smaller value.
2306 		 */
2307 		if (left < hpts_timeout)
2308 			hpts_timeout = left;
2309 	}
2310 	if (hpts_timeout) {
2311 		/*
2312 		 * Hack alert for now we can't time-out over 2,147,483
2313 		 * seconds (a bit more than 596 hours), which is probably ok
2314 		 * :).
2315 		 */
2316 		if (hpts_timeout > 0x7ffffffe)
2317 			hpts_timeout = 0x7ffffffe;
2318 		rack->r_ctl.rc_timer_exp = cts + hpts_timeout;
2319 	}
2320 	if (slot) {
2321 		rack->r_ctl.rc_last_output_to = cts + slot;
2322 		if ((hpts_timeout == 0) || (hpts_timeout > slot)) {
2323 			if (rack->rc_inp->inp_in_hpts == 0)
2324 				tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(slot));
2325 			rack_log_to_start(rack, cts, hpts_timeout, slot, 1);
2326 		} else {
2327 			/*
2328 			 * Arrange for the hpts to kick back in after the
2329 			 * t-o if the t-o does not cause a send.
2330 			 */
2331 			if (rack->rc_inp->inp_in_hpts == 0)
2332 				tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(hpts_timeout));
2333 			rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
2334 		}
2335 	} else if (hpts_timeout) {
2336 		if (rack->rc_inp->inp_in_hpts == 0)
2337 			tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(hpts_timeout));
2338 		rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
2339 	} else {
2340 		/* No timer starting */
2341 #ifdef INVARIANTS
2342 		if (SEQ_GT(tp->snd_max, tp->snd_una)) {
2343 			panic("tp:%p rack:%p tlts:%d cts:%u slot:%u pto:%u -- no timer started?",
2344 			    tp, rack, tot_len_this_send, cts, slot, hpts_timeout);
2345 		}
2346 #endif
2347 	}
2348 	rack->rc_tmr_stopped = 0;
2349 	if (slot)
2350 		rack_log_type_bbrsnd(rack, tot_len_this_send, slot, cts);
2351 }
2352 
2353 /*
2354  * RACK Timer, here we simply do logging and house keeping.
2355  * the normal rack_output() function will call the
2356  * appropriate thing to check if we need to do a RACK retransmit.
2357  * We return 1, saying don't proceed with rack_output only
2358  * when all timers have been stopped (destroyed PCB?).
2359  */
2360 static int
2361 rack_timeout_rack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2362 {
2363 	/*
2364 	 * This timer simply provides an internal trigger to send out data.
2365 	 * The check_recovery_mode call will see if there are needed
2366 	 * retransmissions, if so we will enter fast-recovery. The output
2367 	 * call may or may not do the same thing depending on sysctl
2368 	 * settings.
2369 	 */
2370 	struct rack_sendmap *rsm;
2371 	int32_t recovery;
2372 
2373 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2374 		return (1);
2375 	}
2376 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
2377 		/* Its not time yet */
2378 		return (0);
2379 	}
2380 	rack_log_to_event(rack, RACK_TO_FRM_RACK);
2381 	recovery = IN_RECOVERY(tp->t_flags);
2382 	counter_u64_add(rack_to_tot, 1);
2383 	if (rack->r_state && (rack->r_state != tp->t_state))
2384 		rack_set_state(tp, rack);
2385 	rsm = rack_check_recovery_mode(tp, cts);
2386 	if (rsm) {
2387 		uint32_t rtt;
2388 
2389 		rtt = rack->rc_rack_rtt;
2390 		if (rtt == 0)
2391 			rtt = 1;
2392 		if ((recovery == 0) &&
2393 		    (rack->r_ctl.rc_prr_sndcnt < tp->t_maxseg)) {
2394 			/*
2395 			 * The rack-timeout that enter's us into recovery
2396 			 * will force out one MSS and set us up so that we
2397 			 * can do one more send in 2*rtt (transitioning the
2398 			 * rack timeout into a rack-tlp).
2399 			 */
2400 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
2401 		} else if ((rack->r_ctl.rc_prr_sndcnt < tp->t_maxseg) &&
2402 		    ((rsm->r_end - rsm->r_start) > rack->r_ctl.rc_prr_sndcnt)) {
2403 			/*
2404 			 * When a rack timer goes, we have to send at
2405 			 * least one segment. They will be paced a min of 1ms
2406 			 * apart via the next rack timer (or further
2407 			 * if the rack timer dictates it).
2408 			 */
2409 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
2410 		}
2411 	} else {
2412 		/* This is a case that should happen rarely if ever */
2413 		counter_u64_add(rack_tlp_does_nada, 1);
2414 #ifdef TCP_BLACKBOX
2415 		tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
2416 #endif
2417 		rack->r_ctl.rc_resend = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2418 	}
2419 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
2420 	return (0);
2421 }
2422 
2423 /*
2424  * TLP Timer, here we simply setup what segment we want to
2425  * have the TLP expire on, the normal rack_output() will then
2426  * send it out.
2427  *
2428  * We return 1, saying don't proceed with rack_output only
2429  * when all timers have been stopped (destroyed PCB?).
2430  */
2431 static int
2432 rack_timeout_tlp(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2433 {
2434 	/*
2435 	 * Tail Loss Probe.
2436 	 */
2437 	struct rack_sendmap *rsm = NULL;
2438 	struct socket *so;
2439 	uint32_t amm, old_prr_snd = 0;
2440 	uint32_t out, avail;
2441 
2442 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2443 		return (1);
2444 	}
2445 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
2446 		/* Its not time yet */
2447 		return (0);
2448 	}
2449 	if (rack_progress_timeout_check(tp)) {
2450 		tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
2451 		return (1);
2452 	}
2453 	/*
2454 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
2455 	 * need to figure out how to force a full MSS segment out.
2456 	 */
2457 	rack_log_to_event(rack, RACK_TO_FRM_TLP);
2458 	counter_u64_add(rack_tlp_tot, 1);
2459 	if (rack->r_state && (rack->r_state != tp->t_state))
2460 		rack_set_state(tp, rack);
2461 	so = tp->t_inpcb->inp_socket;
2462 	avail = sbavail(&so->so_snd);
2463 	out = tp->snd_max - tp->snd_una;
2464 	rack->rc_timer_up = 1;
2465 	/*
2466 	 * If we are in recovery we can jazz out a segment if new data is
2467 	 * present simply by setting rc_prr_sndcnt to a segment.
2468 	 */
2469 	if ((avail > out) &&
2470 	    ((rack_always_send_oldest == 0) || (TAILQ_EMPTY(&rack->r_ctl.rc_tmap)))) {
2471 		/* New data is available */
2472 		amm = avail - out;
2473 		if (amm > tp->t_maxseg) {
2474 			amm = tp->t_maxseg;
2475 		} else if ((amm < tp->t_maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
2476 			/* not enough to fill a MTU and no-delay is off */
2477 			goto need_retran;
2478 		}
2479 		if (IN_RECOVERY(tp->t_flags)) {
2480 			/* Unlikely */
2481 			old_prr_snd = rack->r_ctl.rc_prr_sndcnt;
2482 			if (out + amm <= tp->snd_wnd)
2483 				rack->r_ctl.rc_prr_sndcnt = amm;
2484 			else
2485 				goto need_retran;
2486 		} else {
2487 			/* Set the send-new override */
2488 			if (out + amm <= tp->snd_wnd)
2489 				rack->r_ctl.rc_tlp_new_data = amm;
2490 			else
2491 				goto need_retran;
2492 		}
2493 		rack->r_ctl.rc_tlp_seg_send_cnt = 0;
2494 		rack->r_ctl.rc_last_tlp_seq = tp->snd_max;
2495 		rack->r_ctl.rc_tlpsend = NULL;
2496 		counter_u64_add(rack_tlp_newdata, 1);
2497 		goto send;
2498 	}
2499 need_retran:
2500 	/*
2501 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
2502 	 * optionally the first un-acked segment.
2503 	 */
2504 	if (rack_always_send_oldest)
2505 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
2506 	else {
2507 		rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_map, rack_sendmap, r_next);
2508 		if (rsm && (rsm->r_flags & (RACK_ACKED | RACK_HAS_FIN))) {
2509 			rsm = rack_find_high_nonack(rack, rsm);
2510 		}
2511 	}
2512 	if (rsm == NULL) {
2513 		counter_u64_add(rack_tlp_does_nada, 1);
2514 #ifdef TCP_BLACKBOX
2515 		tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
2516 #endif
2517 		goto out;
2518 	}
2519 	if ((rsm->r_end - rsm->r_start) > tp->t_maxseg) {
2520 		/*
2521 		 * We need to split this the last segment in two.
2522 		 */
2523 		int32_t idx;
2524 		struct rack_sendmap *nrsm;
2525 
2526 		nrsm = rack_alloc(rack);
2527 		if (nrsm == NULL) {
2528 			/*
2529 			 * No memory to split, we will just exit and punt
2530 			 * off to the RXT timer.
2531 			 */
2532 			counter_u64_add(rack_tlp_does_nada, 1);
2533 			goto out;
2534 		}
2535 		nrsm->r_start = (rsm->r_end - tp->t_maxseg);
2536 		nrsm->r_end = rsm->r_end;
2537 		nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
2538 		nrsm->r_flags = rsm->r_flags;
2539 		nrsm->r_sndcnt = rsm->r_sndcnt;
2540 		nrsm->r_rtr_bytes = 0;
2541 		rsm->r_end = nrsm->r_start;
2542 		for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
2543 			nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
2544 		}
2545 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
2546 		if (rsm->r_in_tmap) {
2547 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
2548 			nrsm->r_in_tmap = 1;
2549 		}
2550 		rsm->r_flags &= (~RACK_HAS_FIN);
2551 		rsm = nrsm;
2552 	}
2553 	rack->r_ctl.rc_tlpsend = rsm;
2554 	rack->r_ctl.rc_tlp_rtx_out = 1;
2555 	if (rsm->r_start == rack->r_ctl.rc_last_tlp_seq) {
2556 		rack->r_ctl.rc_tlp_seg_send_cnt++;
2557 		tp->t_rxtshift++;
2558 	} else {
2559 		rack->r_ctl.rc_last_tlp_seq = rsm->r_start;
2560 		rack->r_ctl.rc_tlp_seg_send_cnt = 1;
2561 	}
2562 send:
2563 	rack->r_ctl.rc_tlp_send_cnt++;
2564 	if (rack->r_ctl.rc_tlp_send_cnt > rack_tlp_max_resend) {
2565 		/*
2566 		 * Can't [re]/transmit a segment we have not heard from the
2567 		 * peer in max times. We need the retransmit timer to take
2568 		 * over.
2569 		 */
2570 restore:
2571 		rack->r_ctl.rc_tlpsend = NULL;
2572 		if (rsm)
2573 			rsm->r_flags &= ~RACK_TLP;
2574 		rack->r_ctl.rc_prr_sndcnt = old_prr_snd;
2575 		counter_u64_add(rack_tlp_retran_fail, 1);
2576 		goto out;
2577 	} else if (rsm) {
2578 		rsm->r_flags |= RACK_TLP;
2579 	}
2580 	if (rsm && (rsm->r_start == rack->r_ctl.rc_last_tlp_seq) &&
2581 	    (rack->r_ctl.rc_tlp_seg_send_cnt > rack_tlp_max_resend)) {
2582 		/*
2583 		 * We don't want to send a single segment more than the max
2584 		 * either.
2585 		 */
2586 		goto restore;
2587 	}
2588 	rack->r_timer_override = 1;
2589 	rack->r_tlp_running = 1;
2590 	rack->rc_tlp_in_progress = 1;
2591 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
2592 	return (0);
2593 out:
2594 	rack->rc_timer_up = 0;
2595 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
2596 	return (0);
2597 }
2598 
2599 /*
2600  * Delayed ack Timer, here we simply need to setup the
2601  * ACK_NOW flag and remove the DELACK flag. From there
2602  * the output routine will send the ack out.
2603  *
2604  * We only return 1, saying don't proceed, if all timers
2605  * are stopped (destroyed PCB?).
2606  */
2607 static int
2608 rack_timeout_delack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2609 {
2610 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2611 		return (1);
2612 	}
2613 	rack_log_to_event(rack, RACK_TO_FRM_DELACK);
2614 	tp->t_flags &= ~TF_DELACK;
2615 	tp->t_flags |= TF_ACKNOW;
2616 	TCPSTAT_INC(tcps_delack);
2617 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
2618 	return (0);
2619 }
2620 
2621 /*
2622  * Persists timer, here we simply need to setup the
2623  * FORCE-DATA flag the output routine will send
2624  * the one byte send.
2625  *
2626  * We only return 1, saying don't proceed, if all timers
2627  * are stopped (destroyed PCB?).
2628  */
2629 static int
2630 rack_timeout_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2631 {
2632 	struct inpcb *inp;
2633 	int32_t retval = 0;
2634 
2635 	inp = tp->t_inpcb;
2636 
2637 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2638 		return (1);
2639 	}
2640 	if (rack->rc_in_persist == 0)
2641 		return (0);
2642 	if (rack_progress_timeout_check(tp)) {
2643 		tcp_set_inp_to_drop(inp, ETIMEDOUT);
2644 		return (1);
2645 	}
2646 	KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
2647 	/*
2648 	 * Persistence timer into zero window. Force a byte to be output, if
2649 	 * possible.
2650 	 */
2651 	TCPSTAT_INC(tcps_persisttimeo);
2652 	/*
2653 	 * Hack: if the peer is dead/unreachable, we do not time out if the
2654 	 * window is closed.  After a full backoff, drop the connection if
2655 	 * the idle time (no responses to probes) reaches the maximum
2656 	 * backoff that we would use if retransmitting.
2657 	 */
2658 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
2659 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
2660 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
2661 		TCPSTAT_INC(tcps_persistdrop);
2662 		retval = 1;
2663 		tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
2664 		goto out;
2665 	}
2666 	if ((sbavail(&rack->rc_inp->inp_socket->so_snd) == 0) &&
2667 	    tp->snd_una == tp->snd_max)
2668 		rack_exit_persist(tp, rack);
2669 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
2670 	/*
2671 	 * If the user has closed the socket then drop a persisting
2672 	 * connection after a much reduced timeout.
2673 	 */
2674 	if (tp->t_state > TCPS_CLOSE_WAIT &&
2675 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
2676 		retval = 1;
2677 		TCPSTAT_INC(tcps_persistdrop);
2678 		tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
2679 		goto out;
2680 	}
2681 	tp->t_flags |= TF_FORCEDATA;
2682 out:
2683 	rack_log_to_event(rack, RACK_TO_FRM_PERSIST);
2684 	return (retval);
2685 }
2686 
2687 /*
2688  * If a keepalive goes off, we had no other timers
2689  * happening. We always return 1 here since this
2690  * routine either drops the connection or sends
2691  * out a segment with respond.
2692  */
2693 static int
2694 rack_timeout_keepalive(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2695 {
2696 	struct tcptemp *t_template;
2697 	struct inpcb *inp;
2698 
2699 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2700 		return (1);
2701 	}
2702 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
2703 	inp = tp->t_inpcb;
2704 	rack_log_to_event(rack, RACK_TO_FRM_KEEP);
2705 	/*
2706 	 * Keep-alive timer went off; send something or drop connection if
2707 	 * idle for too long.
2708 	 */
2709 	TCPSTAT_INC(tcps_keeptimeo);
2710 	if (tp->t_state < TCPS_ESTABLISHED)
2711 		goto dropit;
2712 	if ((tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
2713 	    tp->t_state <= TCPS_CLOSING) {
2714 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
2715 			goto dropit;
2716 		/*
2717 		 * Send a packet designed to force a response if the peer is
2718 		 * up and reachable: either an ACK if the connection is
2719 		 * still alive, or an RST if the peer has closed the
2720 		 * connection due to timeout or reboot. Using sequence
2721 		 * number tp->snd_una-1 causes the transmitted zero-length
2722 		 * segment to lie outside the receive window; by the
2723 		 * protocol spec, this requires the correspondent TCP to
2724 		 * respond.
2725 		 */
2726 		TCPSTAT_INC(tcps_keepprobe);
2727 		t_template = tcpip_maketemplate(inp);
2728 		if (t_template) {
2729 			tcp_respond(tp, t_template->tt_ipgen,
2730 			    &t_template->tt_t, (struct mbuf *)NULL,
2731 			    tp->rcv_nxt, tp->snd_una - 1, 0);
2732 			free(t_template, M_TEMP);
2733 		}
2734 	}
2735 	rack_start_hpts_timer(rack, tp, cts, __LINE__, 0, 0, 0);
2736 	return (1);
2737 dropit:
2738 	TCPSTAT_INC(tcps_keepdrops);
2739 	tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
2740 	return (1);
2741 }
2742 
2743 /*
2744  * Retransmit helper function, clear up all the ack
2745  * flags and take care of important book keeping.
2746  */
2747 static void
2748 rack_remxt_tmr(struct tcpcb *tp)
2749 {
2750 	/*
2751 	 * The retransmit timer went off, all sack'd blocks must be
2752 	 * un-acked.
2753 	 */
2754 	struct rack_sendmap *rsm, *trsm = NULL;
2755 	struct tcp_rack *rack;
2756 	int32_t cnt = 0;
2757 
2758 	rack = (struct tcp_rack *)tp->t_fb_ptr;
2759 	rack_timer_cancel(tp, rack, tcp_ts_getticks(), __LINE__);
2760 	rack_log_to_event(rack, RACK_TO_FRM_TMR);
2761 	if (rack->r_state && (rack->r_state != tp->t_state))
2762 		rack_set_state(tp, rack);
2763 	/*
2764 	 * Ideally we would like to be able to
2765 	 * mark SACK-PASS on anything not acked here.
2766 	 * However, if we do that we would burst out
2767 	 * all that data 1ms apart. This would be unwise,
2768 	 * so for now we will just let the normal rxt timer
2769 	 * and tlp timer take care of it.
2770 	 */
2771 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_map, r_next) {
2772 		if (rsm->r_flags & RACK_ACKED) {
2773 			cnt++;
2774 			rsm->r_sndcnt = 0;
2775 			if (rsm->r_in_tmap == 0) {
2776 				/* We must re-add it back to the tlist */
2777 				if (trsm == NULL) {
2778 					TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
2779 				} else {
2780 					TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, trsm, rsm, r_tnext);
2781 				}
2782 				rsm->r_in_tmap = 1;
2783 				trsm = rsm;
2784 			}
2785 		}
2786 		rsm->r_flags &= ~(RACK_ACKED | RACK_SACK_PASSED | RACK_WAS_SACKPASS);
2787 	}
2788 	/* Clear the count (we just un-acked them) */
2789 	rack->r_ctl.rc_sacked = 0;
2790 	/* Clear the tlp rtx mark */
2791 	rack->r_ctl.rc_tlp_rtx_out = 0;
2792 	rack->r_ctl.rc_tlp_seg_send_cnt = 0;
2793 	rack->r_ctl.rc_resend = TAILQ_FIRST(&rack->r_ctl.rc_map);
2794 	/* Setup so we send one segment */
2795 	if (rack->r_ctl.rc_prr_sndcnt < tp->t_maxseg)
2796 		rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
2797 	rack->r_timer_override = 1;
2798 }
2799 
2800 /*
2801  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
2802  * we will setup to retransmit the lowest seq number outstanding.
2803  */
2804 static int
2805 rack_timeout_rxt(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
2806 {
2807 	int32_t rexmt;
2808 	struct inpcb *inp;
2809 	int32_t retval = 0;
2810 
2811 	inp = tp->t_inpcb;
2812 	if (tp->t_timers->tt_flags & TT_STOPPED) {
2813 		return (1);
2814 	}
2815 	if (rack_progress_timeout_check(tp)) {
2816 		tcp_set_inp_to_drop(inp, ETIMEDOUT);
2817 		return (1);
2818 	}
2819 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
2820 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
2821 	    (tp->snd_una == tp->snd_max)) {
2822 		/* Nothing outstanding .. nothing to do */
2823 		return (0);
2824 	}
2825 	/*
2826 	 * Retransmission timer went off.  Message has not been acked within
2827 	 * retransmit interval.  Back off to a longer retransmit interval
2828 	 * and retransmit one segment.
2829 	 */
2830 	if (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {
2831 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
2832 		TCPSTAT_INC(tcps_timeoutdrop);
2833 		retval = 1;
2834 		tcp_set_inp_to_drop(rack->rc_inp,
2835 		    (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
2836 		goto out;
2837 	}
2838 	rack_remxt_tmr(tp);
2839 	if (tp->t_state == TCPS_SYN_SENT) {
2840 		/*
2841 		 * If the SYN was retransmitted, indicate CWND to be limited
2842 		 * to 1 segment in cc_conn_init().
2843 		 */
2844 		tp->snd_cwnd = 1;
2845 	} else if (tp->t_rxtshift == 1) {
2846 		/*
2847 		 * first retransmit; record ssthresh and cwnd so they can be
2848 		 * recovered if this turns out to be a "bad" retransmit. A
2849 		 * retransmit is considered "bad" if an ACK for this segment
2850 		 * is received within RTT/2 interval; the assumption here is
2851 		 * that the ACK was already in flight.  See "On Estimating
2852 		 * End-to-End Network Path Properties" by Allman and Paxson
2853 		 * for more details.
2854 		 */
2855 		tp->snd_cwnd_prev = tp->snd_cwnd;
2856 		tp->snd_ssthresh_prev = tp->snd_ssthresh;
2857 		tp->snd_recover_prev = tp->snd_recover;
2858 		if (IN_FASTRECOVERY(tp->t_flags))
2859 			tp->t_flags |= TF_WASFRECOVERY;
2860 		else
2861 			tp->t_flags &= ~TF_WASFRECOVERY;
2862 		if (IN_CONGRECOVERY(tp->t_flags))
2863 			tp->t_flags |= TF_WASCRECOVERY;
2864 		else
2865 			tp->t_flags &= ~TF_WASCRECOVERY;
2866 		tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
2867 		tp->t_flags |= TF_PREVVALID;
2868 	} else
2869 		tp->t_flags &= ~TF_PREVVALID;
2870 	TCPSTAT_INC(tcps_rexmttimeo);
2871 	if ((tp->t_state == TCPS_SYN_SENT) ||
2872 	    (tp->t_state == TCPS_SYN_RECEIVED))
2873 		rexmt = MSEC_2_TICKS(RACK_INITIAL_RTO * tcp_syn_backoff[tp->t_rxtshift]);
2874 	else
2875 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
2876 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
2877 	   max(MSEC_2_TICKS(rack_rto_min), rexmt),
2878 	   MSEC_2_TICKS(rack_rto_max));
2879 	/*
2880 	 * We enter the path for PLMTUD if connection is established or, if
2881 	 * connection is FIN_WAIT_1 status, reason for the last is that if
2882 	 * amount of data we send is very small, we could send it in couple
2883 	 * of packets and process straight to FIN. In that case we won't
2884 	 * catch ESTABLISHED state.
2885 	 */
2886 	if (V_tcp_pmtud_blackhole_detect && (((tp->t_state == TCPS_ESTABLISHED))
2887 	    || (tp->t_state == TCPS_FIN_WAIT_1))) {
2888 #ifdef INET6
2889 		int32_t isipv6;
2890 #endif
2891 
2892 		/*
2893 		 * Idea here is that at each stage of mtu probe (usually,
2894 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
2895 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
2896 		 * should take care of that.
2897 		 */
2898 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
2899 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
2900 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
2901 		    tp->t_rxtshift % 2 == 0)) {
2902 			/*
2903 			 * Enter Path MTU Black-hole Detection mechanism: -
2904 			 * Disable Path MTU Discovery (IP "DF" bit). -
2905 			 * Reduce MTU to lower value than what we negotiated
2906 			 * with peer.
2907 			 */
2908 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
2909 				/* Record that we may have found a black hole. */
2910 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
2911 				/* Keep track of previous MSS. */
2912 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
2913 			}
2914 
2915 			/*
2916 			 * Reduce the MSS to blackhole value or to the
2917 			 * default in an attempt to retransmit.
2918 			 */
2919 #ifdef INET6
2920 			isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? 1 : 0;
2921 			if (isipv6 &&
2922 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
2923 				/* Use the sysctl tuneable blackhole MSS. */
2924 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
2925 				TCPSTAT_INC(tcps_pmtud_blackhole_activated);
2926 			} else if (isipv6) {
2927 				/* Use the default MSS. */
2928 				tp->t_maxseg = V_tcp_v6mssdflt;
2929 				/*
2930 				 * Disable Path MTU Discovery when we switch
2931 				 * to minmss.
2932 				 */
2933 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
2934 				TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
2935 			}
2936 #endif
2937 #if defined(INET6) && defined(INET)
2938 			else
2939 #endif
2940 #ifdef INET
2941 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
2942 				/* Use the sysctl tuneable blackhole MSS. */
2943 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
2944 				TCPSTAT_INC(tcps_pmtud_blackhole_activated);
2945 			} else {
2946 				/* Use the default MSS. */
2947 				tp->t_maxseg = V_tcp_mssdflt;
2948 				/*
2949 				 * Disable Path MTU Discovery when we switch
2950 				 * to minmss.
2951 				 */
2952 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
2953 				TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
2954 			}
2955 #endif
2956 		} else {
2957 			/*
2958 			 * If further retransmissions are still unsuccessful
2959 			 * with a lowered MTU, maybe this isn't a blackhole
2960 			 * and we restore the previous MSS and blackhole
2961 			 * detection flags. The limit '6' is determined by
2962 			 * giving each probe stage (1448, 1188, 524) 2
2963 			 * chances to recover.
2964 			 */
2965 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
2966 			    (tp->t_rxtshift >= 6)) {
2967 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
2968 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
2969 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
2970 				TCPSTAT_INC(tcps_pmtud_blackhole_failed);
2971 			}
2972 		}
2973 	}
2974 	/*
2975 	 * Disable RFC1323 and SACK if we haven't got any response to our
2976 	 * third SYN to work-around some broken terminal servers (most of
2977 	 * which have hopefully been retired) that have bad VJ header
2978 	 * compression code which trashes TCP segments containing
2979 	 * unknown-to-them TCP options.
2980 	 */
2981 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
2982 	    (tp->t_rxtshift == 3))
2983 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
2984 	/*
2985 	 * If we backed off this far, our srtt estimate is probably bogus.
2986 	 * Clobber it so we'll take the next rtt measurement as our srtt;
2987 	 * move the current srtt into rttvar to keep the current retransmit
2988 	 * times until then.
2989 	 */
2990 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
2991 #ifdef INET6
2992 		if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
2993 			in6_losing(tp->t_inpcb);
2994 		else
2995 #endif
2996 			in_losing(tp->t_inpcb);
2997 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
2998 		tp->t_srtt = 0;
2999 	}
3000 	if (rack_use_sack_filter)
3001 		sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
3002 	tp->snd_recover = tp->snd_max;
3003 	tp->t_flags |= TF_ACKNOW;
3004 	tp->t_rtttime = 0;
3005 	rack_cong_signal(tp, NULL, CC_RTO);
3006 out:
3007 	return (retval);
3008 }
3009 
3010 static int
3011 rack_process_timers(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t hpts_calling)
3012 {
3013 	int32_t ret = 0;
3014 	int32_t timers = (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
3015 
3016 	if (timers == 0) {
3017 		return (0);
3018 	}
3019 	if (tp->t_state == TCPS_LISTEN) {
3020 		/* no timers on listen sockets */
3021 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
3022 			return (0);
3023 		return (1);
3024 	}
3025 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
3026 		uint32_t left;
3027 
3028 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
3029 			ret = -1;
3030 			rack_log_to_processing(rack, cts, ret, 0);
3031 			return (0);
3032 		}
3033 		if (hpts_calling == 0) {
3034 			ret = -2;
3035 			rack_log_to_processing(rack, cts, ret, 0);
3036 			return (0);
3037 		}
3038 		/*
3039 		 * Ok our timer went off early and we are not paced false
3040 		 * alarm, go back to sleep.
3041 		 */
3042 		ret = -3;
3043 		left = rack->r_ctl.rc_timer_exp - cts;
3044 		tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(left));
3045 		rack_log_to_processing(rack, cts, ret, left);
3046 		rack->rc_last_pto_set = 0;
3047 		return (1);
3048 	}
3049 	rack->rc_tmr_stopped = 0;
3050 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
3051 	if (timers & PACE_TMR_DELACK) {
3052 		ret = rack_timeout_delack(tp, rack, cts);
3053 	} else if (timers & PACE_TMR_RACK) {
3054 		ret = rack_timeout_rack(tp, rack, cts);
3055 	} else if (timers & PACE_TMR_TLP) {
3056 		ret = rack_timeout_tlp(tp, rack, cts);
3057 	} else if (timers & PACE_TMR_RXT) {
3058 		ret = rack_timeout_rxt(tp, rack, cts);
3059 	} else if (timers & PACE_TMR_PERSIT) {
3060 		ret = rack_timeout_persist(tp, rack, cts);
3061 	} else if (timers & PACE_TMR_KEEP) {
3062 		ret = rack_timeout_keepalive(tp, rack, cts);
3063 	}
3064 	rack_log_to_processing(rack, cts, ret, timers);
3065 	return (ret);
3066 }
3067 
3068 static void
3069 rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line)
3070 {
3071 	uint8_t hpts_removed = 0;
3072 
3073 	if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
3074 	    TSTMP_GEQ(cts, rack->r_ctl.rc_last_output_to)) {
3075 		tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
3076 		hpts_removed = 1;
3077 	}
3078 	if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
3079 		rack->rc_tmr_stopped = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
3080 		if (rack->rc_inp->inp_in_hpts &&
3081 		    ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)) {
3082 			/*
3083 			 * Canceling timer's when we have no output being
3084 			 * paced. We also must remove ourselves from the
3085 			 * hpts.
3086 			 */
3087 			tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
3088 			hpts_removed = 1;
3089 		}
3090 		rack_log_to_cancel(rack, hpts_removed, line);
3091 		rack->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
3092 	}
3093 }
3094 
3095 static void
3096 rack_timer_stop(struct tcpcb *tp, uint32_t timer_type)
3097 {
3098 	return;
3099 }
3100 
3101 static int
3102 rack_stopall(struct tcpcb *tp)
3103 {
3104 	struct tcp_rack *rack;
3105 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3106 	rack->t_timers_stopped = 1;
3107 	return (0);
3108 }
3109 
3110 static void
3111 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
3112 {
3113 	return;
3114 }
3115 
3116 static int
3117 rack_timer_active(struct tcpcb *tp, uint32_t timer_type)
3118 {
3119 	return (0);
3120 }
3121 
3122 static void
3123 rack_stop_all_timers(struct tcpcb *tp)
3124 {
3125 	struct tcp_rack *rack;
3126 
3127 	/*
3128 	 * Assure no timers are running.
3129 	 */
3130 	if (tcp_timer_active(tp, TT_PERSIST)) {
3131 		/* We enter in persists, set the flag appropriately */
3132 		rack = (struct tcp_rack *)tp->t_fb_ptr;
3133 		rack->rc_in_persist = 1;
3134 	}
3135 	tcp_timer_suspend(tp, TT_PERSIST);
3136 	tcp_timer_suspend(tp, TT_REXMT);
3137 	tcp_timer_suspend(tp, TT_KEEP);
3138 	tcp_timer_suspend(tp, TT_DELACK);
3139 }
3140 
3141 static void
3142 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
3143     struct rack_sendmap *rsm, uint32_t ts)
3144 {
3145 	int32_t idx;
3146 
3147 	rsm->r_rtr_cnt++;
3148 	rsm->r_sndcnt++;
3149 	if (rsm->r_rtr_cnt > RACK_NUM_OF_RETRANS) {
3150 		rsm->r_rtr_cnt = RACK_NUM_OF_RETRANS;
3151 		rsm->r_flags |= RACK_OVERMAX;
3152 	}
3153 	if ((rsm->r_rtr_cnt > 1) && (rack->r_tlp_running == 0)) {
3154 		rack->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
3155 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
3156 	}
3157 	idx = rsm->r_rtr_cnt - 1;
3158 	rsm->r_tim_lastsent[idx] = ts;
3159 	if (rsm->r_flags & RACK_ACKED) {
3160 		/* Problably MTU discovery messing with us */
3161 		rsm->r_flags &= ~RACK_ACKED;
3162 		rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
3163 	}
3164 	if (rsm->r_in_tmap) {
3165 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3166 	}
3167 	TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3168 	rsm->r_in_tmap = 1;
3169 	if (rsm->r_flags & RACK_SACK_PASSED) {
3170 		/* We have retransmitted due to the SACK pass */
3171 		rsm->r_flags &= ~RACK_SACK_PASSED;
3172 		rsm->r_flags |= RACK_WAS_SACKPASS;
3173 	}
3174 	/* Update memory for next rtr */
3175 	rack->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
3176 }
3177 
3178 
3179 static uint32_t
3180 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
3181     struct rack_sendmap *rsm, uint32_t ts, int32_t * lenp)
3182 {
3183 	/*
3184 	 * We (re-)transmitted starting at rsm->r_start for some length
3185 	 * (possibly less than r_end.
3186 	 */
3187 	struct rack_sendmap *nrsm;
3188 	uint32_t c_end;
3189 	int32_t len;
3190 	int32_t idx;
3191 
3192 	len = *lenp;
3193 	c_end = rsm->r_start + len;
3194 	if (SEQ_GEQ(c_end, rsm->r_end)) {
3195 		/*
3196 		 * We retransmitted the whole piece or more than the whole
3197 		 * slopping into the next rsm.
3198 		 */
3199 		rack_update_rsm(tp, rack, rsm, ts);
3200 		if (c_end == rsm->r_end) {
3201 			*lenp = 0;
3202 			return (0);
3203 		} else {
3204 			int32_t act_len;
3205 
3206 			/* Hangs over the end return whats left */
3207 			act_len = rsm->r_end - rsm->r_start;
3208 			*lenp = (len - act_len);
3209 			return (rsm->r_end);
3210 		}
3211 		/* We don't get out of this block. */
3212 	}
3213 	/*
3214 	 * Here we retransmitted less than the whole thing which means we
3215 	 * have to split this into what was transmitted and what was not.
3216 	 */
3217 	nrsm = rack_alloc(rack);
3218 	if (nrsm == NULL) {
3219 		/*
3220 		 * We can't get memory, so lets not proceed.
3221 		 */
3222 		*lenp = 0;
3223 		return (0);
3224 	}
3225 	/*
3226 	 * So here we are going to take the original rsm and make it what we
3227 	 * retransmitted. nrsm will be the tail portion we did not
3228 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
3229 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
3230 	 * 1, 6 and the new piece will be 6, 11.
3231 	 */
3232 	nrsm->r_start = c_end;
3233 	nrsm->r_end = rsm->r_end;
3234 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
3235 	nrsm->r_flags = rsm->r_flags;
3236 	nrsm->r_sndcnt = rsm->r_sndcnt;
3237 	nrsm->r_rtr_bytes = 0;
3238 	rsm->r_end = c_end;
3239 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
3240 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
3241 	}
3242 	TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
3243 	if (rsm->r_in_tmap) {
3244 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
3245 		nrsm->r_in_tmap = 1;
3246 	}
3247 	rsm->r_flags &= (~RACK_HAS_FIN);
3248 	rack_update_rsm(tp, rack, rsm, ts);
3249 	*lenp = 0;
3250 	return (0);
3251 }
3252 
3253 
3254 static void
3255 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
3256     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t ts,
3257     uint8_t pass, struct rack_sendmap *hintrsm)
3258 {
3259 	struct tcp_rack *rack;
3260 	struct rack_sendmap *rsm, *nrsm;
3261 	register uint32_t snd_max, snd_una;
3262 	int32_t idx;
3263 
3264 	/*
3265 	 * Add to the RACK log of packets in flight or retransmitted. If
3266 	 * there is a TS option we will use the TS echoed, if not we will
3267 	 * grab a TS.
3268 	 *
3269 	 * Retransmissions will increment the count and move the ts to its
3270 	 * proper place. Note that if options do not include TS's then we
3271 	 * won't be able to effectively use the ACK for an RTT on a retran.
3272 	 *
3273 	 * Notes about r_start and r_end. Lets consider a send starting at
3274 	 * sequence 1 for 10 bytes. In such an example the r_start would be
3275 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
3276 	 * This means that r_end is actually the first sequence for the next
3277 	 * slot (11).
3278 	 *
3279 	 */
3280 	/*
3281 	 * If err is set what do we do XXXrrs? should we not add the thing?
3282 	 * -- i.e. return if err != 0 or should we pretend we sent it? --
3283 	 * i.e. proceed with add ** do this for now.
3284 	 */
3285 	INP_WLOCK_ASSERT(tp->t_inpcb);
3286 	if (err)
3287 		/*
3288 		 * We don't log errors -- we could but snd_max does not
3289 		 * advance in this case either.
3290 		 */
3291 		return;
3292 
3293 	if (th_flags & TH_RST) {
3294 		/*
3295 		 * We don't log resets and we return immediately from
3296 		 * sending
3297 		 */
3298 		return;
3299 	}
3300 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3301 	snd_una = tp->snd_una;
3302 	if (SEQ_LEQ((seq_out + len), snd_una)) {
3303 		/* Are sending an old segment to induce an ack (keep-alive)? */
3304 		return;
3305 	}
3306 	if (SEQ_LT(seq_out, snd_una)) {
3307 		/* huh? should we panic? */
3308 		uint32_t end;
3309 
3310 		end = seq_out + len;
3311 		seq_out = snd_una;
3312 		len = end - seq_out;
3313 	}
3314 	snd_max = tp->snd_max;
3315 	if (th_flags & (TH_SYN | TH_FIN)) {
3316 		/*
3317 		 * The call to rack_log_output is made before bumping
3318 		 * snd_max. This means we can record one extra byte on a SYN
3319 		 * or FIN if seq_out is adding more on and a FIN is present
3320 		 * (and we are not resending).
3321 		 */
3322 		if (th_flags & TH_SYN)
3323 			len++;
3324 		if (th_flags & TH_FIN)
3325 			len++;
3326 		if (SEQ_LT(snd_max, tp->snd_nxt)) {
3327 			/*
3328 			 * The add/update as not been done for the FIN/SYN
3329 			 * yet.
3330 			 */
3331 			snd_max = tp->snd_nxt;
3332 		}
3333 	}
3334 	if (len == 0) {
3335 		/* We don't log zero window probes */
3336 		return;
3337 	}
3338 	rack->r_ctl.rc_time_last_sent = ts;
3339 	if (IN_RECOVERY(tp->t_flags)) {
3340 		rack->r_ctl.rc_prr_out += len;
3341 	}
3342 	/* First question is it a retransmission? */
3343 	if (seq_out == snd_max) {
3344 again:
3345 		rsm = rack_alloc(rack);
3346 		if (rsm == NULL) {
3347 			/*
3348 			 * Hmm out of memory and the tcb got destroyed while
3349 			 * we tried to wait.
3350 			 */
3351 #ifdef INVARIANTS
3352 			panic("Out of memory when we should not be rack:%p", rack);
3353 #endif
3354 			return;
3355 		}
3356 		if (th_flags & TH_FIN) {
3357 			rsm->r_flags = RACK_HAS_FIN;
3358 		} else {
3359 			rsm->r_flags = 0;
3360 		}
3361 		rsm->r_tim_lastsent[0] = ts;
3362 		rsm->r_rtr_cnt = 1;
3363 		rsm->r_rtr_bytes = 0;
3364 		if (th_flags & TH_SYN) {
3365 			/* The data space is one beyond snd_una */
3366 			rsm->r_start = seq_out + 1;
3367 			rsm->r_end = rsm->r_start + (len - 1);
3368 		} else {
3369 			/* Normal case */
3370 			rsm->r_start = seq_out;
3371 			rsm->r_end = rsm->r_start + len;
3372 		}
3373 		rsm->r_sndcnt = 0;
3374 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_map, rsm, r_next);
3375 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3376 		rsm->r_in_tmap = 1;
3377 		return;
3378 	}
3379 	/*
3380 	 * If we reach here its a retransmission and we need to find it.
3381 	 */
3382 more:
3383 	if (hintrsm && (hintrsm->r_start == seq_out)) {
3384 		rsm = hintrsm;
3385 		hintrsm = NULL;
3386 	} else if (rack->r_ctl.rc_next) {
3387 		/* We have a hint from a previous run */
3388 		rsm = rack->r_ctl.rc_next;
3389 	} else {
3390 		/* No hints sorry */
3391 		rsm = NULL;
3392 	}
3393 	if ((rsm) && (rsm->r_start == seq_out)) {
3394 		/*
3395 		 * We used rc_next or hintrsm  to retransmit, hopefully the
3396 		 * likely case.
3397 		 */
3398 		seq_out = rack_update_entry(tp, rack, rsm, ts, &len);
3399 		if (len == 0) {
3400 			return;
3401 		} else {
3402 			goto more;
3403 		}
3404 	}
3405 	/* Ok it was not the last pointer go through it the hard way. */
3406 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_map, r_next) {
3407 		if (rsm->r_start == seq_out) {
3408 			seq_out = rack_update_entry(tp, rack, rsm, ts, &len);
3409 			rack->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
3410 			if (len == 0) {
3411 				return;
3412 			} else {
3413 				continue;
3414 			}
3415 		}
3416 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
3417 			/* Transmitted within this piece */
3418 			/*
3419 			 * Ok we must split off the front and then let the
3420 			 * update do the rest
3421 			 */
3422 			nrsm = rack_alloc(rack);
3423 			if (nrsm == NULL) {
3424 #ifdef INVARIANTS
3425 				panic("Ran out of memory that was preallocated? rack:%p", rack);
3426 #endif
3427 				rack_update_rsm(tp, rack, rsm, ts);
3428 				return;
3429 			}
3430 			/*
3431 			 * copy rsm to nrsm and then trim the front of rsm
3432 			 * to not include this part.
3433 			 */
3434 			nrsm->r_start = seq_out;
3435 			nrsm->r_end = rsm->r_end;
3436 			nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
3437 			nrsm->r_flags = rsm->r_flags;
3438 			nrsm->r_sndcnt = rsm->r_sndcnt;
3439 			nrsm->r_rtr_bytes = 0;
3440 			for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
3441 				nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
3442 			}
3443 			rsm->r_end = nrsm->r_start;
3444 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
3445 			if (rsm->r_in_tmap) {
3446 				TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
3447 				nrsm->r_in_tmap = 1;
3448 			}
3449 			rsm->r_flags &= (~RACK_HAS_FIN);
3450 			seq_out = rack_update_entry(tp, rack, nrsm, ts, &len);
3451 			if (len == 0) {
3452 				return;
3453 			}
3454 		}
3455 	}
3456 	/*
3457 	 * Hmm not found in map did they retransmit both old and on into the
3458 	 * new?
3459 	 */
3460 	if (seq_out == tp->snd_max) {
3461 		goto again;
3462 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
3463 #ifdef INVARIANTS
3464 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
3465 		    seq_out, len, tp->snd_una, tp->snd_max);
3466 		printf("Starting Dump of all rack entries\n");
3467 		TAILQ_FOREACH(rsm, &rack->r_ctl.rc_map, r_next) {
3468 			printf("rsm:%p start:%u end:%u\n",
3469 			    rsm, rsm->r_start, rsm->r_end);
3470 		}
3471 		printf("Dump complete\n");
3472 		panic("seq_out not found rack:%p tp:%p",
3473 		    rack, tp);
3474 #endif
3475 	} else {
3476 #ifdef INVARIANTS
3477 		/*
3478 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
3479 		 * flag)
3480 		 */
3481 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
3482 		    seq_out, len, tp->snd_max, tp);
3483 #endif
3484 	}
3485 }
3486 
3487 /*
3488  * Record one of the RTT updates from an ack into
3489  * our sample structure.
3490  */
3491 static void
3492 tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt)
3493 {
3494 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
3495 	    (rack->r_ctl.rack_rs.rs_rtt_lowest > rtt)) {
3496 		rack->r_ctl.rack_rs.rs_rtt_lowest = rtt;
3497 	}
3498 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
3499 	    (rack->r_ctl.rack_rs.rs_rtt_highest < rtt)) {
3500 		rack->r_ctl.rack_rs.rs_rtt_highest = rtt;
3501 	}
3502 	rack->r_ctl.rack_rs.rs_flags = RACK_RTT_VALID;
3503 	rack->r_ctl.rack_rs.rs_rtt_tot += rtt;
3504 	rack->r_ctl.rack_rs.rs_rtt_cnt++;
3505 }
3506 
3507 /*
3508  * Collect new round-trip time estimate
3509  * and update averages and current timeout.
3510  */
3511 static void
3512 tcp_rack_xmit_timer_commit(struct tcp_rack *rack, struct tcpcb *tp)
3513 {
3514 	int32_t delta;
3515 	uint32_t o_srtt, o_var;
3516 	int32_t rtt;
3517 
3518 	if (rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY)
3519 		/* No valid sample */
3520 		return;
3521 	if (rack->r_ctl.rc_rate_sample_method == USE_RTT_LOW) {
3522 		/* We are to use the lowest RTT seen in a single ack */
3523 		rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
3524 	} else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_HIGH) {
3525 		/* We are to use the highest RTT seen in a single ack */
3526 		rtt = rack->r_ctl.rack_rs.rs_rtt_highest;
3527 	} else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_AVG) {
3528 		/* We are to use the average RTT seen in a single ack */
3529 		rtt = (int32_t)(rack->r_ctl.rack_rs.rs_rtt_tot /
3530 				(uint64_t)rack->r_ctl.rack_rs.rs_rtt_cnt);
3531 	} else {
3532 #ifdef INVARIANTS
3533 		panic("Unknown rtt variant %d", rack->r_ctl.rc_rate_sample_method);
3534 #endif
3535 		return;
3536 	}
3537 	if (rtt == 0)
3538 		rtt = 1;
3539 	rack_log_rtt_sample(rack, rtt);
3540 	o_srtt = tp->t_srtt;
3541 	o_var = tp->t_rttvar;
3542 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3543 	if (tp->t_srtt != 0) {
3544 		/*
3545 		 * srtt is stored as fixed point with 5 bits after the
3546 		 * binary point (i.e., scaled by 8).  The following magic is
3547 		 * equivalent to the smoothing algorithm in rfc793 with an
3548 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
3549 		 * Adjust rtt to origin 0.
3550 		 */
3551 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3552 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3553 
3554 		tp->t_srtt += delta;
3555 		if (tp->t_srtt <= 0)
3556 			tp->t_srtt = 1;
3557 
3558 		/*
3559 		 * We accumulate a smoothed rtt variance (actually, a
3560 		 * smoothed mean difference), then set the retransmit timer
3561 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
3562 		 * is stored as fixed point with 4 bits after the binary
3563 		 * point (scaled by 16).  The following is equivalent to
3564 		 * rfc793 smoothing with an alpha of .75 (rttvar =
3565 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
3566 		 * wired-in beta.
3567 		 */
3568 		if (delta < 0)
3569 			delta = -delta;
3570 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3571 		tp->t_rttvar += delta;
3572 		if (tp->t_rttvar <= 0)
3573 			tp->t_rttvar = 1;
3574 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3575 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3576 	} else {
3577 		/*
3578 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
3579 		 * variance to half the rtt (so our first retransmit happens
3580 		 * at 3*rtt).
3581 		 */
3582 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
3583 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3584 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3585 	}
3586 	TCPSTAT_INC(tcps_rttupdated);
3587 	rack_log_rtt_upd(tp, rack, rtt, o_srtt, o_var);
3588 	tp->t_rttupdated++;
3589 #ifdef NETFLIX_STATS
3590 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt));
3591 #endif
3592 	tp->t_rxtshift = 0;
3593 
3594 	/*
3595 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
3596 	 * way we do the smoothing, srtt and rttvar will each average +1/2
3597 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
3598 	 * tick of rounding and 1 extra tick because of +-1/2 tick
3599 	 * uncertainty in the firing of the timer.  The bias will give us
3600 	 * exactly the 1.5 tick we need.  But, because the bias is
3601 	 * statistical, we have to test that we don't drop below the minimum
3602 	 * feasible timer (which is 2 ticks).
3603 	 */
3604 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3605 	   max(MSEC_2_TICKS(rack_rto_min), rtt + 2), MSEC_2_TICKS(rack_rto_max));
3606 	tp->t_softerror = 0;
3607 }
3608 
3609 static void
3610 rack_earlier_retran(struct tcpcb *tp, struct rack_sendmap *rsm,
3611     uint32_t t, uint32_t cts)
3612 {
3613 	/*
3614 	 * For this RSM, we acknowledged the data from a previous
3615 	 * transmission, not the last one we made. This means we did a false
3616 	 * retransmit.
3617 	 */
3618 	struct tcp_rack *rack;
3619 
3620 	if (rsm->r_flags & RACK_HAS_FIN) {
3621 		/*
3622 		 * The sending of the FIN often is multiple sent when we
3623 		 * have everything outstanding ack'd. We ignore this case
3624 		 * since its over now.
3625 		 */
3626 		return;
3627 	}
3628 	if (rsm->r_flags & RACK_TLP) {
3629 		/*
3630 		 * We expect TLP's to have this occur.
3631 		 */
3632 		return;
3633 	}
3634 	rack = (struct tcp_rack *)tp->t_fb_ptr;
3635 	/* should we undo cc changes and exit recovery? */
3636 	if (IN_RECOVERY(tp->t_flags)) {
3637 		if (rack->r_ctl.rc_rsm_start == rsm->r_start) {
3638 			/*
3639 			 * Undo what we ratched down and exit recovery if
3640 			 * possible
3641 			 */
3642 			EXIT_RECOVERY(tp->t_flags);
3643 			tp->snd_recover = tp->snd_una;
3644 			if (rack->r_ctl.rc_cwnd_at > tp->snd_cwnd)
3645 				tp->snd_cwnd = rack->r_ctl.rc_cwnd_at;
3646 			if (rack->r_ctl.rc_ssthresh_at > tp->snd_ssthresh)
3647 				tp->snd_ssthresh = rack->r_ctl.rc_ssthresh_at;
3648 		}
3649 	}
3650 	if (rsm->r_flags & RACK_WAS_SACKPASS) {
3651 		/*
3652 		 * We retransmitted based on a sack and the earlier
3653 		 * retransmission ack'd it - re-ordering is occuring.
3654 		 */
3655 		counter_u64_add(rack_reorder_seen, 1);
3656 		rack->r_ctl.rc_reorder_ts = cts;
3657 	}
3658 	counter_u64_add(rack_badfr, 1);
3659 	counter_u64_add(rack_badfr_bytes, (rsm->r_end - rsm->r_start));
3660 }
3661 
3662 
3663 static int
3664 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
3665     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type)
3666 {
3667 	int32_t i;
3668 	uint32_t t;
3669 
3670 	if (rsm->r_flags & RACK_ACKED)
3671 		/* Already done */
3672 		return (0);
3673 
3674 
3675 	if ((rsm->r_rtr_cnt == 1) ||
3676 	    ((ack_type == CUM_ACKED) &&
3677 	    (to->to_flags & TOF_TS) &&
3678 	    (to->to_tsecr) &&
3679 	    (rsm->r_tim_lastsent[rsm->r_rtr_cnt - 1] == to->to_tsecr))
3680 	    ) {
3681 		/*
3682 		 * We will only find a matching timestamp if its cum-acked.
3683 		 * But if its only one retransmission its for-sure matching
3684 		 * :-)
3685 		 */
3686 		t = cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
3687 		if ((int)t <= 0)
3688 			t = 1;
3689 		if (!tp->t_rttlow || tp->t_rttlow > t)
3690 			tp->t_rttlow = t;
3691 		if (!rack->r_ctl.rc_rack_min_rtt ||
3692 		    SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3693 			rack->r_ctl.rc_rack_min_rtt = t;
3694 			if (rack->r_ctl.rc_rack_min_rtt == 0) {
3695 				rack->r_ctl.rc_rack_min_rtt = 1;
3696 			}
3697 		}
3698 		tcp_rack_xmit_timer(rack, TCP_TS_TO_TICKS(t) + 1);
3699 		if ((rsm->r_flags & RACK_TLP) &&
3700 		    (!IN_RECOVERY(tp->t_flags))) {
3701 			/* Segment was a TLP and our retrans matched */
3702 			if (rack->r_ctl.rc_tlp_cwnd_reduce) {
3703 				rack->r_ctl.rc_rsm_start = tp->snd_max;
3704 				rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
3705 				rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
3706 				rack_cong_signal(tp, NULL, CC_NDUPACK);
3707 				/*
3708 				 * When we enter recovery we need to assure
3709 				 * we send one packet.
3710 				 */
3711 				rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
3712 			} else
3713 				rack->r_ctl.rc_tlp_rtx_out = 0;
3714 		}
3715 		if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
3716 			/* New more recent rack_tmit_time */
3717 			rack->r_ctl.rc_rack_tmit_time = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
3718 			rack->rc_rack_rtt = t;
3719 		}
3720 		return (1);
3721 	}
3722 	/*
3723 	 * We clear the soft/rxtshift since we got an ack.
3724 	 * There is no assurance we will call the commit() function
3725 	 * so we need to clear these to avoid incorrect handling.
3726 	 */
3727 	tp->t_rxtshift = 0;
3728 	tp->t_softerror = 0;
3729 	if ((to->to_flags & TOF_TS) &&
3730 	    (ack_type == CUM_ACKED) &&
3731 	    (to->to_tsecr) &&
3732 	    ((rsm->r_flags & (RACK_DEFERRED | RACK_OVERMAX)) == 0)) {
3733 		/*
3734 		 * Now which timestamp does it match? In this block the ACK
3735 		 * must be coming from a previous transmission.
3736 		 */
3737 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
3738 			if (rsm->r_tim_lastsent[i] == to->to_tsecr) {
3739 				t = cts - rsm->r_tim_lastsent[i];
3740 				if ((int)t <= 0)
3741 					t = 1;
3742 				if ((i + 1) < rsm->r_rtr_cnt) {
3743 					/* Likely */
3744 					rack_earlier_retran(tp, rsm, t, cts);
3745 				}
3746 				if (!tp->t_rttlow || tp->t_rttlow > t)
3747 					tp->t_rttlow = t;
3748 				if (!rack->r_ctl.rc_rack_min_rtt || SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3749 					rack->r_ctl.rc_rack_min_rtt = t;
3750 					if (rack->r_ctl.rc_rack_min_rtt == 0) {
3751 						rack->r_ctl.rc_rack_min_rtt = 1;
3752 					}
3753 				}
3754                                 /*
3755 				 * Note the following calls to
3756 				 * tcp_rack_xmit_timer() are being commented
3757 				 * out for now. They give us no more accuracy
3758 				 * and often lead to a wrong choice. We have
3759 				 * enough samples that have not been
3760 				 * retransmitted. I leave the commented out
3761 				 * code in here in case in the future we
3762 				 * decide to add it back (though I can't forsee
3763 				 * doing that). That way we will easily see
3764 				 * where they need to be placed.
3765 				 */
3766 				if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time,
3767 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
3768 					/* New more recent rack_tmit_time */
3769 					rack->r_ctl.rc_rack_tmit_time = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
3770 					rack->rc_rack_rtt = t;
3771 				}
3772 				return (1);
3773 			}
3774 		}
3775 		goto ts_not_found;
3776 	} else {
3777 		/*
3778 		 * Ok its a SACK block that we retransmitted. or a windows
3779 		 * machine without timestamps. We can tell nothing from the
3780 		 * time-stamp since its not there or the time the peer last
3781 		 * recieved a segment that moved forward its cum-ack point.
3782 		 */
3783 ts_not_found:
3784 		i = rsm->r_rtr_cnt - 1;
3785 		t = cts - rsm->r_tim_lastsent[i];
3786 		if ((int)t <= 0)
3787 			t = 1;
3788 		if (rack->r_ctl.rc_rack_min_rtt && SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3789 			/*
3790 			 * We retransmitted and the ack came back in less
3791 			 * than the smallest rtt we have observed. We most
3792 			 * likey did an improper retransmit as outlined in
3793 			 * 4.2 Step 3 point 2 in the rack-draft.
3794 			 */
3795 			i = rsm->r_rtr_cnt - 2;
3796 			t = cts - rsm->r_tim_lastsent[i];
3797 			rack_earlier_retran(tp, rsm, t, cts);
3798 		} else if (rack->r_ctl.rc_rack_min_rtt) {
3799 			/*
3800 			 * We retransmitted it and the retransmit did the
3801 			 * job.
3802 			 */
3803 			if (!rack->r_ctl.rc_rack_min_rtt ||
3804 			    SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
3805 				rack->r_ctl.rc_rack_min_rtt = t;
3806 				if (rack->r_ctl.rc_rack_min_rtt == 0) {
3807 					rack->r_ctl.rc_rack_min_rtt = 1;
3808 				}
3809 			}
3810 			if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, rsm->r_tim_lastsent[i])) {
3811 				/* New more recent rack_tmit_time */
3812 				rack->r_ctl.rc_rack_tmit_time = rsm->r_tim_lastsent[i];
3813 				rack->rc_rack_rtt = t;
3814 			}
3815 			return (1);
3816 		}
3817 	}
3818 	return (0);
3819 }
3820 
3821 /*
3822  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
3823  */
3824 static void
3825 rack_log_sack_passed(struct tcpcb *tp,
3826     struct tcp_rack *rack, struct rack_sendmap *rsm)
3827 {
3828 	struct rack_sendmap *nrsm;
3829 	uint32_t ts;
3830 	int32_t idx;
3831 
3832 	idx = rsm->r_rtr_cnt - 1;
3833 	ts = rsm->r_tim_lastsent[idx];
3834 	nrsm = rsm;
3835 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &rack->r_ctl.rc_tmap,
3836 	    rack_head, r_tnext) {
3837 		if (nrsm == rsm) {
3838 			/* Skip orginal segment he is acked */
3839 			continue;
3840 		}
3841 		if (nrsm->r_flags & RACK_ACKED) {
3842 			/* Skip ack'd segments */
3843 			continue;
3844 		}
3845 		idx = nrsm->r_rtr_cnt - 1;
3846 		if (ts == nrsm->r_tim_lastsent[idx]) {
3847 			/*
3848 			 * For this case lets use seq no, if we sent in a
3849 			 * big block (TSO) we would have a bunch of segments
3850 			 * sent at the same time.
3851 			 *
3852 			 * We would only get a report if its SEQ is earlier.
3853 			 * If we have done multiple retransmits the times
3854 			 * would not be equal.
3855 			 */
3856 			if (SEQ_LT(nrsm->r_start, rsm->r_start)) {
3857 				nrsm->r_flags |= RACK_SACK_PASSED;
3858 				nrsm->r_flags &= ~RACK_WAS_SACKPASS;
3859 			}
3860 		} else {
3861 			/*
3862 			 * Here they were sent at different times, not a big
3863 			 * block. Since we transmitted this one later and
3864 			 * see it sack'd then this must also be missing (or
3865 			 * we would have gotten a sack block for it)
3866 			 */
3867 			nrsm->r_flags |= RACK_SACK_PASSED;
3868 			nrsm->r_flags &= ~RACK_WAS_SACKPASS;
3869 		}
3870 	}
3871 }
3872 
3873 static uint32_t
3874 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack, struct sackblk *sack,
3875     struct tcpopt *to, struct rack_sendmap **prsm, uint32_t cts)
3876 {
3877 	int32_t idx;
3878 	int32_t times = 0;
3879 	uint32_t start, end, changed = 0;
3880 	struct rack_sendmap *rsm, *nrsm;
3881 	int32_t used_ref = 1;
3882 
3883 	start = sack->start;
3884 	end = sack->end;
3885 	rsm = *prsm;
3886 	if (rsm && SEQ_LT(start, rsm->r_start)) {
3887 		TAILQ_FOREACH_REVERSE_FROM(rsm, &rack->r_ctl.rc_map, rack_head, r_next) {
3888 			if (SEQ_GEQ(start, rsm->r_start) &&
3889 			    SEQ_LT(start, rsm->r_end)) {
3890 				goto do_rest_ofb;
3891 			}
3892 		}
3893 	}
3894 	if (rsm == NULL) {
3895 start_at_beginning:
3896 		rsm = NULL;
3897 		used_ref = 0;
3898 	}
3899 	/* First lets locate the block where this guy is */
3900 	TAILQ_FOREACH_FROM(rsm, &rack->r_ctl.rc_map, r_next) {
3901 		if (SEQ_GEQ(start, rsm->r_start) &&
3902 		    SEQ_LT(start, rsm->r_end)) {
3903 			break;
3904 		}
3905 	}
3906 do_rest_ofb:
3907 	if (rsm == NULL) {
3908 		/*
3909 		 * This happens when we get duplicate sack blocks with the
3910 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
3911 		 * will not change there location so we would just start at
3912 		 * the end of the first one and get lost.
3913 		 */
3914 		if (tp->t_flags & TF_SENTFIN) {
3915 			/*
3916 			 * Check to see if we have not logged the FIN that
3917 			 * went out.
3918 			 */
3919 			nrsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_map, rack_sendmap, r_next);
3920 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
3921 				/*
3922 				 * Ok we did not get the FIN logged.
3923 				 */
3924 				nrsm->r_end++;
3925 				rsm = nrsm;
3926 				goto do_rest_ofb;
3927 			}
3928 		}
3929 		if (times == 1) {
3930 #ifdef INVARIANTS
3931 			panic("tp:%p rack:%p sack:%p to:%p prsm:%p",
3932 			    tp, rack, sack, to, prsm);
3933 #else
3934 			goto out;
3935 #endif
3936 		}
3937 		times++;
3938 		counter_u64_add(rack_sack_proc_restart, 1);
3939 		goto start_at_beginning;
3940 	}
3941 	/* Ok we have an ACK for some piece of rsm */
3942 	if (rsm->r_start != start) {
3943 		/*
3944 		 * Need to split this in two pieces the before and after.
3945 		 */
3946 		nrsm = rack_alloc(rack);
3947 		if (nrsm == NULL) {
3948 			/*
3949 			 * failed XXXrrs what can we do but loose the sack
3950 			 * info?
3951 			 */
3952 			goto out;
3953 		}
3954 		nrsm->r_start = start;
3955 		nrsm->r_rtr_bytes = 0;
3956 		nrsm->r_end = rsm->r_end;
3957 		nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
3958 		nrsm->r_flags = rsm->r_flags;
3959 		nrsm->r_sndcnt = rsm->r_sndcnt;
3960 		for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
3961 			nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
3962 		}
3963 		rsm->r_end = nrsm->r_start;
3964 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
3965 		if (rsm->r_in_tmap) {
3966 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
3967 			nrsm->r_in_tmap = 1;
3968 		}
3969 		rsm->r_flags &= (~RACK_HAS_FIN);
3970 		rsm = nrsm;
3971 	}
3972 	if (SEQ_GEQ(end, rsm->r_end)) {
3973 		/*
3974 		 * The end of this block is either beyond this guy or right
3975 		 * at this guy.
3976 		 */
3977 
3978 		if ((rsm->r_flags & RACK_ACKED) == 0) {
3979 			rack_update_rtt(tp, rack, rsm, to, cts, SACKED);
3980 			changed += (rsm->r_end - rsm->r_start);
3981 			rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
3982 			rack_log_sack_passed(tp, rack, rsm);
3983 			/* Is Reordering occuring? */
3984 			if (rsm->r_flags & RACK_SACK_PASSED) {
3985 				counter_u64_add(rack_reorder_seen, 1);
3986 				rack->r_ctl.rc_reorder_ts = cts;
3987 			}
3988 			rsm->r_flags |= RACK_ACKED;
3989 			rsm->r_flags &= ~RACK_TLP;
3990 			if (rsm->r_in_tmap) {
3991 				TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
3992 				rsm->r_in_tmap = 0;
3993 			}
3994 		}
3995 		if (end == rsm->r_end) {
3996 			/* This block only - done */
3997 			goto out;
3998 		}
3999 		/* There is more not coverend by this rsm move on */
4000 		start = rsm->r_end;
4001 		nrsm = TAILQ_NEXT(rsm, r_next);
4002 		rsm = nrsm;
4003 		times = 0;
4004 		goto do_rest_ofb;
4005 	}
4006 	/* Ok we need to split off this one at the tail */
4007 	nrsm = rack_alloc(rack);
4008 	if (nrsm == NULL) {
4009 		/* failed rrs what can we do but loose the sack info? */
4010 		goto out;
4011 	}
4012 	/* Clone it */
4013 	nrsm->r_start = end;
4014 	nrsm->r_end = rsm->r_end;
4015 	nrsm->r_rtr_bytes = 0;
4016 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4017 	nrsm->r_flags = rsm->r_flags;
4018 	nrsm->r_sndcnt = rsm->r_sndcnt;
4019 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4020 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4021 	}
4022 	/* The sack block does not cover this guy fully */
4023 	rsm->r_flags &= (~RACK_HAS_FIN);
4024 	rsm->r_end = end;
4025 	TAILQ_INSERT_AFTER(&rack->r_ctl.rc_map, rsm, nrsm, r_next);
4026 	if (rsm->r_in_tmap) {
4027 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4028 		nrsm->r_in_tmap = 1;
4029 	}
4030 	if (rsm->r_flags & RACK_ACKED) {
4031 		/* Been here done that */
4032 		goto out;
4033 	}
4034 	rack_update_rtt(tp, rack, rsm, to, cts, SACKED);
4035 	changed += (rsm->r_end - rsm->r_start);
4036 	rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
4037 	rack_log_sack_passed(tp, rack, rsm);
4038 	/* Is Reordering occuring? */
4039 	if (rsm->r_flags & RACK_SACK_PASSED) {
4040 		counter_u64_add(rack_reorder_seen, 1);
4041 		rack->r_ctl.rc_reorder_ts = cts;
4042 	}
4043 	rsm->r_flags |= RACK_ACKED;
4044 	rsm->r_flags &= ~RACK_TLP;
4045 	if (rsm->r_in_tmap) {
4046 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4047 		rsm->r_in_tmap = 0;
4048 	}
4049 out:
4050 	if (used_ref == 0) {
4051 		counter_u64_add(rack_sack_proc_all, 1);
4052 	} else {
4053 		counter_u64_add(rack_sack_proc_short, 1);
4054 	}
4055 	/* Save off where we last were */
4056 	if (rsm)
4057 		rack->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
4058 	else
4059 		rack->r_ctl.rc_sacklast = NULL;
4060 	*prsm = rsm;
4061 	return (changed);
4062 }
4063 
4064 static void inline
4065 rack_peer_reneges(struct tcp_rack *rack, struct rack_sendmap *rsm, tcp_seq th_ack)
4066 {
4067 	struct rack_sendmap *tmap;
4068 
4069 	tmap = NULL;
4070 	while (rsm && (rsm->r_flags & RACK_ACKED)) {
4071 		/* Its no longer sacked, mark it so */
4072 		rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
4073 #ifdef INVARIANTS
4074 		if (rsm->r_in_tmap) {
4075 			panic("rack:%p rsm:%p flags:0x%x in tmap?",
4076 			      rack, rsm, rsm->r_flags);
4077 		}
4078 #endif
4079 		rsm->r_flags &= ~(RACK_ACKED|RACK_SACK_PASSED|RACK_WAS_SACKPASS);
4080 		/* Rebuild it into our tmap */
4081 		if (tmap == NULL) {
4082 			TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4083 			tmap = rsm;
4084 		} else {
4085 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, tmap, rsm, r_tnext);
4086 			tmap = rsm;
4087 		}
4088 		tmap->r_in_tmap = 1;
4089 		rsm = TAILQ_NEXT(rsm, r_next);
4090 	}
4091 	/*
4092 	 * Now lets possibly clear the sack filter so we start
4093 	 * recognizing sacks that cover this area.
4094 	 */
4095 	if (rack_use_sack_filter)
4096 		sack_filter_clear(&rack->r_ctl.rack_sf, th_ack);
4097 
4098 }
4099 
4100 static void
4101 rack_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
4102 {
4103 	uint32_t changed, last_seq, entered_recovery = 0;
4104 	struct tcp_rack *rack;
4105 	struct rack_sendmap *rsm;
4106 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
4107 	register uint32_t th_ack;
4108 	int32_t i, j, k, num_sack_blks = 0;
4109 	uint32_t cts, acked, ack_point, sack_changed = 0;
4110 
4111 	INP_WLOCK_ASSERT(tp->t_inpcb);
4112 	if (th->th_flags & TH_RST) {
4113 		/* We don't log resets */
4114 		return;
4115 	}
4116 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4117 	cts = tcp_ts_getticks();
4118 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
4119 	changed = 0;
4120 	th_ack = th->th_ack;
4121 
4122 	if (SEQ_GT(th_ack, tp->snd_una)) {
4123 		rack_log_progress_event(rack, tp, ticks, PROGRESS_UPDATE, __LINE__);
4124 		tp->t_acktime = ticks;
4125 	}
4126 	if (rsm && SEQ_GT(th_ack, rsm->r_start))
4127 		changed = th_ack - rsm->r_start;
4128 	if (changed) {
4129 		/*
4130 		 * The ACK point is advancing to th_ack, we must drop off
4131 		 * the packets in the rack log and calculate any eligble
4132 		 * RTT's.
4133 		 */
4134 		rack->r_wanted_output++;
4135 more:
4136 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
4137 		if (rsm == NULL) {
4138 			if ((th_ack - 1) == tp->iss) {
4139 				/*
4140 				 * For the SYN incoming case we will not
4141 				 * have called tcp_output for the sending of
4142 				 * the SYN, so there will be no map. All
4143 				 * other cases should probably be a panic.
4144 				 */
4145 				goto proc_sack;
4146 			}
4147 			if (tp->t_flags & TF_SENTFIN) {
4148 				/* if we send a FIN we will not hav a map */
4149 				goto proc_sack;
4150 			}
4151 #ifdef INVARIANTS
4152 			panic("No rack map tp:%p for th:%p state:%d rack:%p snd_una:%u snd_max:%u snd_nxt:%u chg:%d\n",
4153 			    tp,
4154 			    th, tp->t_state, rack,
4155 			    tp->snd_una, tp->snd_max, tp->snd_nxt, changed);
4156 #endif
4157 			goto proc_sack;
4158 		}
4159 		if (SEQ_LT(th_ack, rsm->r_start)) {
4160 			/* Huh map is missing this */
4161 #ifdef INVARIANTS
4162 			printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d\n",
4163 			    rsm->r_start,
4164 			    th_ack, tp->t_state, rack->r_state);
4165 #endif
4166 			goto proc_sack;
4167 		}
4168 		rack_update_rtt(tp, rack, rsm, to, cts, CUM_ACKED);
4169 		/* Now do we consume the whole thing? */
4170 		if (SEQ_GEQ(th_ack, rsm->r_end)) {
4171 			/* Its all consumed. */
4172 			uint32_t left;
4173 
4174 			rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
4175 			rsm->r_rtr_bytes = 0;
4176 			TAILQ_REMOVE(&rack->r_ctl.rc_map, rsm, r_next);
4177 			if (rsm->r_in_tmap) {
4178 				TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
4179 				rsm->r_in_tmap = 0;
4180 			}
4181 			if (rack->r_ctl.rc_next == rsm) {
4182 				/* scoot along the marker */
4183 				rack->r_ctl.rc_next = TAILQ_FIRST(&rack->r_ctl.rc_map);
4184 			}
4185 			if (rsm->r_flags & RACK_ACKED) {
4186 				/*
4187 				 * It was acked on the scoreboard -- remove
4188 				 * it from total
4189 				 */
4190 				rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
4191 			} else if (rsm->r_flags & RACK_SACK_PASSED) {
4192 				/*
4193 				 * There are acked segments ACKED on the
4194 				 * scoreboard further up. We are seeing
4195 				 * reordering.
4196 				 */
4197 				counter_u64_add(rack_reorder_seen, 1);
4198 				rsm->r_flags |= RACK_ACKED;
4199 				rack->r_ctl.rc_reorder_ts = cts;
4200 			}
4201 			left = th_ack - rsm->r_end;
4202 			if (rsm->r_rtr_cnt > 1) {
4203 				/*
4204 				 * Technically we should make r_rtr_cnt be
4205 				 * monotonicly increasing and just mod it to
4206 				 * the timestamp it is replacing.. that way
4207 				 * we would have the last 3 retransmits. Now
4208 				 * rc_loss_count will be wrong if we
4209 				 * retransmit something more than 2 times in
4210 				 * recovery :(
4211 				 */
4212 				rack->r_ctl.rc_loss_count += (rsm->r_rtr_cnt - 1);
4213 			}
4214 			/* Free back to zone */
4215 			rack_free(rack, rsm);
4216 			if (left) {
4217 				goto more;
4218 			}
4219 			goto proc_sack;
4220 		}
4221 		if (rsm->r_flags & RACK_ACKED) {
4222 			/*
4223 			 * It was acked on the scoreboard -- remove it from
4224 			 * total for the part being cum-acked.
4225 			 */
4226 			rack->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
4227 		}
4228 		rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
4229 		rsm->r_rtr_bytes = 0;
4230 		rsm->r_start = th_ack;
4231 	}
4232 proc_sack:
4233 	/* Check for reneging */
4234 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
4235 	if (rsm && (rsm->r_flags & RACK_ACKED) && (th_ack == rsm->r_start)) {
4236 		/*
4237 		 * The peer has moved snd_una up to
4238 		 * the edge of this send, i.e. one
4239 		 * that it had previously acked. The only
4240 		 * way that can be true if the peer threw
4241 		 * away data (space issues) that it had
4242 		 * previously sacked (else it would have
4243 		 * given us snd_una up to (rsm->r_end).
4244 		 * We need to undo the acked markings here.
4245 		 *
4246 		 * Note we have to look to make sure th_ack is
4247 		 * our rsm->r_start in case we get an old ack
4248 		 * where th_ack is behind snd_una.
4249 		 */
4250 		rack_peer_reneges(rack, rsm, th->th_ack);
4251 	}
4252 	if ((to->to_flags & TOF_SACK) == 0) {
4253 		/* We are done nothing left to log */
4254 		goto out;
4255 	}
4256 	rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_map, rack_sendmap, r_next);
4257 	if (rsm) {
4258 		last_seq = rsm->r_end;
4259 	} else {
4260 		last_seq = tp->snd_max;
4261 	}
4262 	/* Sack block processing */
4263 	if (SEQ_GT(th_ack, tp->snd_una))
4264 		ack_point = th_ack;
4265 	else
4266 		ack_point = tp->snd_una;
4267 	for (i = 0; i < to->to_nsacks; i++) {
4268 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
4269 		    &sack, sizeof(sack));
4270 		sack.start = ntohl(sack.start);
4271 		sack.end = ntohl(sack.end);
4272 		if (SEQ_GT(sack.end, sack.start) &&
4273 		    SEQ_GT(sack.start, ack_point) &&
4274 		    SEQ_LT(sack.start, tp->snd_max) &&
4275 		    SEQ_GT(sack.end, ack_point) &&
4276 		    SEQ_LEQ(sack.end, tp->snd_max)) {
4277 			if ((rack->r_ctl.rc_num_maps_alloced > rack_sack_block_limit) &&
4278 			    (SEQ_LT(sack.end, last_seq)) &&
4279 			    ((sack.end - sack.start) < (tp->t_maxseg / 8))) {
4280 				/*
4281 				 * Not the last piece and its smaller than
4282 				 * 1/8th of a MSS. We ignore this.
4283 				 */
4284 				counter_u64_add(rack_runt_sacks, 1);
4285 				continue;
4286 			}
4287 			sack_blocks[num_sack_blks] = sack;
4288 			num_sack_blks++;
4289 #ifdef NETFLIX_STATS
4290 		} else if (SEQ_LEQ(sack.start, th_ack) &&
4291 			   SEQ_LEQ(sack.end, th_ack)) {
4292 			/*
4293 			 * Its a D-SACK block.
4294 			 */
4295 			tcp_record_dsack(sack.start, sack.end);
4296 #endif
4297 		}
4298 
4299 	}
4300 	if (num_sack_blks == 0)
4301 		goto out;
4302 	/*
4303 	 * Sort the SACK blocks so we can update the rack scoreboard with
4304 	 * just one pass.
4305 	 */
4306 	if (rack_use_sack_filter) {
4307 		num_sack_blks = sack_filter_blks(&rack->r_ctl.rack_sf, sack_blocks, num_sack_blks, th->th_ack);
4308 	}
4309 	if (num_sack_blks < 2) {
4310 		goto do_sack_work;
4311 	}
4312 	/* Sort the sacks */
4313 	for (i = 0; i < num_sack_blks; i++) {
4314 		for (j = i + 1; j < num_sack_blks; j++) {
4315 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
4316 				sack = sack_blocks[i];
4317 				sack_blocks[i] = sack_blocks[j];
4318 				sack_blocks[j] = sack;
4319 			}
4320 		}
4321 	}
4322 	/*
4323 	 * Now are any of the sack block ends the same (yes some
4324 	 * implememtations send these)?
4325 	 */
4326 again:
4327 	if (num_sack_blks > 1) {
4328 		for (i = 0; i < num_sack_blks; i++) {
4329 			for (j = i + 1; j < num_sack_blks; j++) {
4330 				if (sack_blocks[i].end == sack_blocks[j].end) {
4331 					/*
4332 					 * Ok these two have the same end we
4333 					 * want the smallest end and then
4334 					 * throw away the larger and start
4335 					 * again.
4336 					 */
4337 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
4338 						/*
4339 						 * The second block covers
4340 						 * more area use that
4341 						 */
4342 						sack_blocks[i].start = sack_blocks[j].start;
4343 					}
4344 					/*
4345 					 * Now collapse out the dup-sack and
4346 					 * lower the count
4347 					 */
4348 					for (k = (j + 1); k < num_sack_blks; k++) {
4349 						sack_blocks[j].start = sack_blocks[k].start;
4350 						sack_blocks[j].end = sack_blocks[k].end;
4351 						j++;
4352 					}
4353 					num_sack_blks--;
4354 					goto again;
4355 				}
4356 			}
4357 		}
4358 	}
4359 do_sack_work:
4360 	rsm = rack->r_ctl.rc_sacklast;
4361 	for (i = 0; i < num_sack_blks; i++) {
4362 		acked = rack_proc_sack_blk(tp, rack, &sack_blocks[i], to, &rsm, cts);
4363 		if (acked) {
4364 			rack->r_wanted_output++;
4365 			changed += acked;
4366 			sack_changed += acked;
4367 		}
4368 	}
4369 out:
4370 	if (changed) {
4371 		/* Something changed cancel the rack timer */
4372 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4373 	}
4374 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
4375 		/*
4376 		 * Ok we have a high probability that we need to go in to
4377 		 * recovery since we have data sack'd
4378 		 */
4379 		struct rack_sendmap *rsm;
4380 		uint32_t tsused;
4381 
4382 		tsused = tcp_ts_getticks();
4383 		rsm = tcp_rack_output(tp, rack, tsused);
4384 		if (rsm) {
4385 			/* Enter recovery */
4386 			rack->r_ctl.rc_rsm_start = rsm->r_start;
4387 			rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
4388 			rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
4389 			entered_recovery = 1;
4390 			rack_cong_signal(tp, NULL, CC_NDUPACK);
4391 			/*
4392 			 * When we enter recovery we need to assure we send
4393 			 * one packet.
4394 			 */
4395 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
4396 			rack->r_timer_override = 1;
4397 		}
4398 	}
4399 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
4400 		/* Deal with changed an PRR here (in recovery only) */
4401 		uint32_t pipe, snd_una;
4402 
4403 		rack->r_ctl.rc_prr_delivered += changed;
4404 		/* Compute prr_sndcnt */
4405 		if (SEQ_GT(tp->snd_una, th_ack)) {
4406 			snd_una = tp->snd_una;
4407 		} else {
4408 			snd_una = th_ack;
4409 		}
4410 		pipe = ((tp->snd_max - snd_una) - rack->r_ctl.rc_sacked) + rack->r_ctl.rc_holes_rxt;
4411 		if (pipe > tp->snd_ssthresh) {
4412 			long sndcnt;
4413 
4414 			sndcnt = rack->r_ctl.rc_prr_delivered * tp->snd_ssthresh;
4415 			if (rack->r_ctl.rc_prr_recovery_fs > 0)
4416 				sndcnt /= (long)rack->r_ctl.rc_prr_recovery_fs;
4417 			else {
4418 				rack->r_ctl.rc_prr_sndcnt = 0;
4419 				sndcnt = 0;
4420 			}
4421 			sndcnt++;
4422 			if (sndcnt > (long)rack->r_ctl.rc_prr_out)
4423 				sndcnt -= rack->r_ctl.rc_prr_out;
4424 			else
4425 				sndcnt = 0;
4426 			rack->r_ctl.rc_prr_sndcnt = sndcnt;
4427 		} else {
4428 			uint32_t limit;
4429 
4430 			if (rack->r_ctl.rc_prr_delivered > rack->r_ctl.rc_prr_out)
4431 				limit = (rack->r_ctl.rc_prr_delivered - rack->r_ctl.rc_prr_out);
4432 			else
4433 				limit = 0;
4434 			if (changed > limit)
4435 				limit = changed;
4436 			limit += tp->t_maxseg;
4437 			if (tp->snd_ssthresh > pipe) {
4438 				rack->r_ctl.rc_prr_sndcnt = min((tp->snd_ssthresh - pipe), limit);
4439 			} else {
4440 				rack->r_ctl.rc_prr_sndcnt = min(0, limit);
4441 			}
4442 		}
4443 		if (rack->r_ctl.rc_prr_sndcnt >= tp->t_maxseg) {
4444 			rack->r_timer_override = 1;
4445 		}
4446 	}
4447 }
4448 
4449 /*
4450  * Return value of 1, we do not need to call rack_process_data().
4451  * return value of 0, rack_process_data can be called.
4452  * For ret_val if its 0 the TCP is locked, if its non-zero
4453  * its unlocked and probably unsafe to touch the TCB.
4454  */
4455 static int
4456 rack_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
4457     struct tcpcb *tp, struct tcpopt *to,
4458     uint32_t tiwin, int32_t tlen,
4459     int32_t * ofia, int32_t thflags, int32_t * ret_val)
4460 {
4461 	int32_t ourfinisacked = 0;
4462 	int32_t nsegs, acked_amount;
4463 	int32_t acked;
4464 	struct mbuf *mfree;
4465 	struct tcp_rack *rack;
4466 	int32_t recovery = 0;
4467 
4468 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4469 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
4470 		rack_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
4471 		return (1);
4472 	}
4473 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
4474 		rack_log_ack(tp, to, th);
4475 	}
4476 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
4477 		/*
4478 		 * Old ack, behind (or duplicate to) the last one rcv'd
4479 		 * Note: Should mark reordering is occuring! We should also
4480 		 * look for sack blocks arriving e.g. ack 1, 4-4 then ack 1,
4481 		 * 3-3, 4-4 would be reording. As well as ack 1, 3-3 <no
4482 		 * retran and> ack 3
4483 		 */
4484 		return (0);
4485 	}
4486 	/*
4487 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
4488 	 * something we sent.
4489 	 */
4490 	if (tp->t_flags & TF_NEEDSYN) {
4491 		/*
4492 		 * T/TCP: Connection was half-synchronized, and our SYN has
4493 		 * been ACK'd (so connection is now fully synchronized).  Go
4494 		 * to non-starred state, increment snd_una for ACK of SYN,
4495 		 * and check if we can do window scaling.
4496 		 */
4497 		tp->t_flags &= ~TF_NEEDSYN;
4498 		tp->snd_una++;
4499 		/* Do window scaling? */
4500 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
4501 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
4502 			tp->rcv_scale = tp->request_r_scale;
4503 			/* Send window already scaled. */
4504 		}
4505 	}
4506 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
4507 	INP_WLOCK_ASSERT(tp->t_inpcb);
4508 
4509 	acked = BYTES_THIS_ACK(tp, th);
4510 	TCPSTAT_ADD(tcps_rcvackpack, nsegs);
4511 	TCPSTAT_ADD(tcps_rcvackbyte, acked);
4512 
4513 	/*
4514 	 * If we just performed our first retransmit, and the ACK arrives
4515 	 * within our recovery window, then it was a mistake to do the
4516 	 * retransmit in the first place.  Recover our original cwnd and
4517 	 * ssthresh, and proceed to transmit where we left off.
4518 	 */
4519 	if (tp->t_flags & TF_PREVVALID) {
4520 		tp->t_flags &= ~TF_PREVVALID;
4521 		if (tp->t_rxtshift == 1 &&
4522 		    (int)(ticks - tp->t_badrxtwin) < 0)
4523 			rack_cong_signal(tp, th, CC_RTO_ERR);
4524 	}
4525 	/*
4526 	 * If we have a timestamp reply, update smoothed round trip time. If
4527 	 * no timestamp is present but transmit timer is running and timed
4528 	 * sequence number was acked, update smoothed round trip time. Since
4529 	 * we now have an rtt measurement, cancel the timer backoff (cf.,
4530 	 * Phil Karn's retransmit alg.). Recompute the initial retransmit
4531 	 * timer.
4532 	 *
4533 	 * Some boxes send broken timestamp replies during the SYN+ACK
4534 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
4535 	 * and blow up the retransmit timer.
4536 	 */
4537 	/*
4538 	 * If all outstanding data is acked, stop retransmit timer and
4539 	 * remember to restart (more output or persist). If there is more
4540 	 * data to be acked, restart retransmit timer, using current
4541 	 * (possibly backed-off) value.
4542 	 */
4543 	if (th->th_ack == tp->snd_max) {
4544 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4545 		rack->r_wanted_output++;
4546 	}
4547 	/*
4548 	 * If no data (only SYN) was ACK'd, skip rest of ACK processing.
4549 	 */
4550 	if (acked == 0) {
4551 		if (ofia)
4552 			*ofia = ourfinisacked;
4553 		return (0);
4554 	}
4555 	if (rack->r_ctl.rc_early_recovery) {
4556 		if (IN_FASTRECOVERY(tp->t_flags)) {
4557 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
4558 				tcp_rack_partialack(tp, th);
4559 			} else {
4560 				rack_post_recovery(tp, th);
4561 				recovery = 1;
4562 			}
4563 		}
4564 	}
4565 	/*
4566 	 * Let the congestion control algorithm update congestion control
4567 	 * related information. This typically means increasing the
4568 	 * congestion window.
4569 	 */
4570 	rack_ack_received(tp, rack, th, nsegs, CC_ACK, recovery);
4571 	SOCKBUF_LOCK(&so->so_snd);
4572 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
4573 	tp->snd_wnd -= acked_amount;
4574 	mfree = sbcut_locked(&so->so_snd, acked_amount);
4575 	if ((sbused(&so->so_snd) == 0) &&
4576 	    (acked > acked_amount) &&
4577 	    (tp->t_state >= TCPS_FIN_WAIT_1)) {
4578 		ourfinisacked = 1;
4579 	}
4580 	/* NB: sowwakeup_locked() does an implicit unlock. */
4581 	sowwakeup_locked(so);
4582 	m_freem(mfree);
4583 	if (rack->r_ctl.rc_early_recovery == 0) {
4584 		if (IN_FASTRECOVERY(tp->t_flags)) {
4585 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
4586 				tcp_rack_partialack(tp, th);
4587 			} else {
4588 				rack_post_recovery(tp, th);
4589 			}
4590 		}
4591 	}
4592 	tp->snd_una = th->th_ack;
4593 	if (SEQ_GT(tp->snd_una, tp->snd_recover))
4594 		tp->snd_recover = tp->snd_una;
4595 
4596 	if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4597 		tp->snd_nxt = tp->snd_una;
4598 	}
4599 	if (tp->snd_una == tp->snd_max) {
4600 		/* Nothing left outstanding */
4601 		rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
4602 		tp->t_acktime = 0;
4603 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4604 		/* Set need output so persist might get set */
4605 		rack->r_wanted_output++;
4606 		if (rack_use_sack_filter)
4607 			sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
4608 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
4609 		    (sbavail(&so->so_snd) == 0) &&
4610 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
4611 			/*
4612 			 * The socket was gone and the
4613 			 * peer sent data, time to
4614 			 * reset him.
4615 			 */
4616 			*ret_val = 1;
4617 			tp = tcp_close(tp);
4618 			rack_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
4619 			return (1);
4620 		}
4621 	}
4622 	if (ofia)
4623 		*ofia = ourfinisacked;
4624 	return (0);
4625 }
4626 
4627 
4628 /*
4629  * Return value of 1, the TCB is unlocked and most
4630  * likely gone, return value of 0, the TCP is still
4631  * locked.
4632  */
4633 static int
4634 rack_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
4635     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
4636     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
4637 {
4638 	/*
4639 	 * Update window information. Don't look at window if no ACK: TAC's
4640 	 * send garbage on first SYN.
4641 	 */
4642 	int32_t nsegs;
4643 	int32_t tfo_syn;
4644 	struct tcp_rack *rack;
4645 
4646 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4647 	INP_WLOCK_ASSERT(tp->t_inpcb);
4648 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
4649 	if ((thflags & TH_ACK) &&
4650 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
4651 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
4652 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
4653 		/* keep track of pure window updates */
4654 		if (tlen == 0 &&
4655 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
4656 			TCPSTAT_INC(tcps_rcvwinupd);
4657 		tp->snd_wnd = tiwin;
4658 		tp->snd_wl1 = th->th_seq;
4659 		tp->snd_wl2 = th->th_ack;
4660 		if (tp->snd_wnd > tp->max_sndwnd)
4661 			tp->max_sndwnd = tp->snd_wnd;
4662 		rack->r_wanted_output++;
4663 	} else if (thflags & TH_ACK) {
4664 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
4665 			tp->snd_wnd = tiwin;
4666 			tp->snd_wl1 = th->th_seq;
4667 			tp->snd_wl2 = th->th_ack;
4668 		}
4669 	}
4670 	/* Was persist timer active and now we have window space? */
4671 	if ((rack->rc_in_persist != 0) && tp->snd_wnd) {
4672 		rack_exit_persist(tp, rack);
4673 		tp->snd_nxt = tp->snd_max;
4674 		/* Make sure we output to start the timer */
4675 		rack->r_wanted_output++;
4676 	}
4677 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
4678 		m_freem(m);
4679 		return (0);
4680 	}
4681 	/*
4682 	 * Process segments with URG.
4683 	 */
4684 	if ((thflags & TH_URG) && th->th_urp &&
4685 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4686 		/*
4687 		 * This is a kludge, but if we receive and accept random
4688 		 * urgent pointers, we'll crash in soreceive.  It's hard to
4689 		 * imagine someone actually wanting to send this much urgent
4690 		 * data.
4691 		 */
4692 		SOCKBUF_LOCK(&so->so_rcv);
4693 		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
4694 			th->th_urp = 0;	/* XXX */
4695 			thflags &= ~TH_URG;	/* XXX */
4696 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
4697 			goto dodata;	/* XXX */
4698 		}
4699 		/*
4700 		 * If this segment advances the known urgent pointer, then
4701 		 * mark the data stream.  This should not happen in
4702 		 * CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since a
4703 		 * FIN has been received from the remote side. In these
4704 		 * states we ignore the URG.
4705 		 *
4706 		 * According to RFC961 (Assigned Protocols), the urgent
4707 		 * pointer points to the last octet of urgent data.  We
4708 		 * continue, however, to consider it to indicate the first
4709 		 * octet of data past the urgent section as the original
4710 		 * spec states (in one of two places).
4711 		 */
4712 		if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
4713 			tp->rcv_up = th->th_seq + th->th_urp;
4714 			so->so_oobmark = sbavail(&so->so_rcv) +
4715 			    (tp->rcv_up - tp->rcv_nxt) - 1;
4716 			if (so->so_oobmark == 0)
4717 				so->so_rcv.sb_state |= SBS_RCVATMARK;
4718 			sohasoutofband(so);
4719 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
4720 		}
4721 		SOCKBUF_UNLOCK(&so->so_rcv);
4722 		/*
4723 		 * Remove out of band data so doesn't get presented to user.
4724 		 * This can happen independent of advancing the URG pointer,
4725 		 * but if two URG's are pending at once, some out-of-band
4726 		 * data may creep in... ick.
4727 		 */
4728 		if (th->th_urp <= (uint32_t) tlen &&
4729 		    !(so->so_options & SO_OOBINLINE)) {
4730 			/* hdr drop is delayed */
4731 			tcp_pulloutofband(so, th, m, drop_hdrlen);
4732 		}
4733 	} else {
4734 		/*
4735 		 * If no out of band data is expected, pull receive urgent
4736 		 * pointer along with the receive window.
4737 		 */
4738 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
4739 			tp->rcv_up = tp->rcv_nxt;
4740 	}
4741 dodata:				/* XXX */
4742 	INP_WLOCK_ASSERT(tp->t_inpcb);
4743 
4744 	/*
4745 	 * Process the segment text, merging it into the TCP sequencing
4746 	 * queue, and arranging for acknowledgment of receipt if necessary.
4747 	 * This process logically involves adjusting tp->rcv_wnd as data is
4748 	 * presented to the user (this happens in tcp_usrreq.c, case
4749 	 * PRU_RCVD).  If a FIN has already been received on this connection
4750 	 * then we just ignore the text.
4751 	 */
4752 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
4753 		   IS_FASTOPEN(tp->t_flags));
4754 	if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
4755 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4756 		tcp_seq save_start = th->th_seq;
4757 
4758 		m_adj(m, drop_hdrlen);	/* delayed header drop */
4759 		/*
4760 		 * Insert segment which includes th into TCP reassembly
4761 		 * queue with control block tp.  Set thflags to whether
4762 		 * reassembly now includes a segment with FIN.  This handles
4763 		 * the common case inline (segment is the next to be
4764 		 * received on an established connection, and the queue is
4765 		 * empty), avoiding linkage into and removal from the queue
4766 		 * and repetition of various conversions. Set DELACK for
4767 		 * segments received in order, but ack immediately when
4768 		 * segments are out of order (so fast retransmit can work).
4769 		 */
4770 		if (th->th_seq == tp->rcv_nxt &&
4771 		    SEGQ_EMPTY(tp) &&
4772 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
4773 		    tfo_syn)) {
4774 			if (DELAY_ACK(tp, tlen) || tfo_syn) {
4775 				rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4776 				tp->t_flags |= TF_DELACK;
4777 			} else {
4778 				rack->r_wanted_output++;
4779 				tp->t_flags |= TF_ACKNOW;
4780 			}
4781 			tp->rcv_nxt += tlen;
4782 			thflags = th->th_flags & TH_FIN;
4783 			TCPSTAT_ADD(tcps_rcvpack, nsegs);
4784 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
4785 			SOCKBUF_LOCK(&so->so_rcv);
4786 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
4787 				m_freem(m);
4788 			else
4789 				sbappendstream_locked(&so->so_rcv, m, 0);
4790 			/* NB: sorwakeup_locked() does an implicit unlock. */
4791 			sorwakeup_locked(so);
4792 		} else {
4793 			/*
4794 			 * XXX: Due to the header drop above "th" is
4795 			 * theoretically invalid by now.  Fortunately
4796 			 * m_adj() doesn't actually frees any mbufs when
4797 			 * trimming from the head.
4798 			 */
4799 			thflags = tcp_reass(tp, th, &save_start, &tlen, m);
4800 			tp->t_flags |= TF_ACKNOW;
4801 		}
4802 		if (tlen > 0)
4803 			tcp_update_sack_list(tp, save_start, save_start + tlen);
4804 	} else {
4805 		m_freem(m);
4806 		thflags &= ~TH_FIN;
4807 	}
4808 
4809 	/*
4810 	 * If FIN is received ACK the FIN and let the user know that the
4811 	 * connection is closing.
4812 	 */
4813 	if (thflags & TH_FIN) {
4814 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4815 			socantrcvmore(so);
4816 			/*
4817 			 * If connection is half-synchronized (ie NEEDSYN
4818 			 * flag on) then delay ACK, so it may be piggybacked
4819 			 * when SYN is sent. Otherwise, since we received a
4820 			 * FIN then no more input can be expected, send ACK
4821 			 * now.
4822 			 */
4823 			if (tp->t_flags & TF_NEEDSYN) {
4824 				rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4825 				tp->t_flags |= TF_DELACK;
4826 			} else {
4827 				tp->t_flags |= TF_ACKNOW;
4828 			}
4829 			tp->rcv_nxt++;
4830 		}
4831 		switch (tp->t_state) {
4832 
4833 			/*
4834 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
4835 			 * CLOSE_WAIT state.
4836 			 */
4837 		case TCPS_SYN_RECEIVED:
4838 			tp->t_starttime = ticks;
4839 			/* FALLTHROUGH */
4840 		case TCPS_ESTABLISHED:
4841 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4842 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
4843 			break;
4844 
4845 			/*
4846 			 * If still in FIN_WAIT_1 STATE FIN has not been
4847 			 * acked so enter the CLOSING state.
4848 			 */
4849 		case TCPS_FIN_WAIT_1:
4850 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4851 			tcp_state_change(tp, TCPS_CLOSING);
4852 			break;
4853 
4854 			/*
4855 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
4856 			 * starting the time-wait timer, turning off the
4857 			 * other standard timers.
4858 			 */
4859 		case TCPS_FIN_WAIT_2:
4860 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4861 			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
4862 			tcp_twstart(tp);
4863 			return (1);
4864 		}
4865 	}
4866 	/*
4867 	 * Return any desired output.
4868 	 */
4869 	if ((tp->t_flags & TF_ACKNOW) || (sbavail(&so->so_snd) > (tp->snd_max - tp->snd_una))) {
4870 		rack->r_wanted_output++;
4871 	}
4872 	INP_WLOCK_ASSERT(tp->t_inpcb);
4873 	return (0);
4874 }
4875 
4876 /*
4877  * Here nothing is really faster, its just that we
4878  * have broken out the fast-data path also just like
4879  * the fast-ack.
4880  */
4881 static int
4882 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
4883     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
4884     uint32_t tiwin, int32_t nxt_pkt)
4885 {
4886 	int32_t nsegs;
4887 	int32_t newsize = 0;	/* automatic sockbuf scaling */
4888 	struct tcp_rack *rack;
4889 #ifdef TCPDEBUG
4890 	/*
4891 	 * The size of tcp_saveipgen must be the size of the max ip header,
4892 	 * now IPv6.
4893 	 */
4894 	u_char tcp_saveipgen[IP6_HDR_LEN];
4895 	struct tcphdr tcp_savetcp;
4896 	short ostate = 0;
4897 
4898 #endif
4899 	/*
4900 	 * If last ACK falls within this segment's sequence numbers, record
4901 	 * the timestamp. NOTE that the test is modified according to the
4902 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
4903 	 */
4904 	if (__predict_false(th->th_seq != tp->rcv_nxt)) {
4905 		return (0);
4906 	}
4907 	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
4908 		return (0);
4909 	}
4910 	if (tiwin && tiwin != tp->snd_wnd) {
4911 		return (0);
4912 	}
4913 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
4914 		return (0);
4915 	}
4916 	if (__predict_false((to->to_flags & TOF_TS) &&
4917 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
4918 		return (0);
4919 	}
4920 	if (__predict_false((th->th_ack != tp->snd_una))) {
4921 		return (0);
4922 	}
4923 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
4924 		return (0);
4925 	}
4926 	if ((to->to_flags & TOF_TS) != 0 &&
4927 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
4928 		tp->ts_recent_age = tcp_ts_getticks();
4929 		tp->ts_recent = to->to_tsval;
4930 	}
4931 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4932 	/*
4933 	 * This is a pure, in-sequence data packet with nothing on the
4934 	 * reassembly queue and we have enough buffer space to take it.
4935 	 */
4936 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
4937 
4938 
4939 	/* Clean receiver SACK report if present */
4940 	if (tp->rcv_numsacks)
4941 		tcp_clean_sackreport(tp);
4942 	TCPSTAT_INC(tcps_preddat);
4943 	tp->rcv_nxt += tlen;
4944 	/*
4945 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
4946 	 */
4947 	tp->snd_wl1 = th->th_seq;
4948 	/*
4949 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
4950 	 */
4951 	tp->rcv_up = tp->rcv_nxt;
4952 	TCPSTAT_ADD(tcps_rcvpack, nsegs);
4953 	TCPSTAT_ADD(tcps_rcvbyte, tlen);
4954 #ifdef TCPDEBUG
4955 	if (so->so_options & SO_DEBUG)
4956 		tcp_trace(TA_INPUT, ostate, tp,
4957 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
4958 #endif
4959 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
4960 
4961 	/* Add data to socket buffer. */
4962 	SOCKBUF_LOCK(&so->so_rcv);
4963 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
4964 		m_freem(m);
4965 	} else {
4966 		/*
4967 		 * Set new socket buffer size. Give up when limit is
4968 		 * reached.
4969 		 */
4970 		if (newsize)
4971 			if (!sbreserve_locked(&so->so_rcv,
4972 			    newsize, so, NULL))
4973 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
4974 		m_adj(m, drop_hdrlen);	/* delayed header drop */
4975 		sbappendstream_locked(&so->so_rcv, m, 0);
4976 		rack_calc_rwin(so, tp);
4977 	}
4978 	/* NB: sorwakeup_locked() does an implicit unlock. */
4979 	sorwakeup_locked(so);
4980 	if (DELAY_ACK(tp, tlen)) {
4981 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
4982 		tp->t_flags |= TF_DELACK;
4983 	} else {
4984 		tp->t_flags |= TF_ACKNOW;
4985 		rack->r_wanted_output++;
4986 	}
4987 	if ((tp->snd_una == tp->snd_max) && rack_use_sack_filter)
4988 		sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
4989 	return (1);
4990 }
4991 
4992 /*
4993  * This subfunction is used to try to highly optimize the
4994  * fast path. We again allow window updates that are
4995  * in sequence to remain in the fast-path. We also add
4996  * in the __predict's to attempt to help the compiler.
4997  * Note that if we return a 0, then we can *not* process
4998  * it and the caller should push the packet into the
4999  * slow-path.
5000  */
5001 static int
5002 rack_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
5003     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5004     uint32_t tiwin, int32_t nxt_pkt, uint32_t cts)
5005 {
5006 	int32_t acked;
5007 	int32_t nsegs;
5008 
5009 #ifdef TCPDEBUG
5010 	/*
5011 	 * The size of tcp_saveipgen must be the size of the max ip header,
5012 	 * now IPv6.
5013 	 */
5014 	u_char tcp_saveipgen[IP6_HDR_LEN];
5015 	struct tcphdr tcp_savetcp;
5016 	short ostate = 0;
5017 
5018 #endif
5019 	struct tcp_rack *rack;
5020 
5021 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
5022 		/* Old ack, behind (or duplicate to) the last one rcv'd */
5023 		return (0);
5024 	}
5025 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
5026 		/* Above what we have sent? */
5027 		return (0);
5028 	}
5029 	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
5030 		/* We are retransmitting */
5031 		return (0);
5032 	}
5033 	if (__predict_false(tiwin == 0)) {
5034 		/* zero window */
5035 		return (0);
5036 	}
5037 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
5038 		/* We need a SYN or a FIN, unlikely.. */
5039 		return (0);
5040 	}
5041 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
5042 		/* Timestamp is behind .. old ack with seq wrap? */
5043 		return (0);
5044 	}
5045 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
5046 		/* Still recovering */
5047 		return (0);
5048 	}
5049 	rack = (struct tcp_rack *)tp->t_fb_ptr;
5050 	if (rack->r_ctl.rc_sacked) {
5051 		/* We have sack holes on our scoreboard */
5052 		return (0);
5053 	}
5054 	/* Ok if we reach here, we can process a fast-ack */
5055 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
5056 	rack_log_ack(tp, to, th);
5057 	/* Did the window get updated? */
5058 	if (tiwin != tp->snd_wnd) {
5059 		tp->snd_wnd = tiwin;
5060 		tp->snd_wl1 = th->th_seq;
5061 		if (tp->snd_wnd > tp->max_sndwnd)
5062 			tp->max_sndwnd = tp->snd_wnd;
5063 	}
5064 	if ((rack->rc_in_persist != 0) && (tp->snd_wnd >= tp->t_maxseg)) {
5065 		rack_exit_persist(tp, rack);
5066 	}
5067 	/*
5068 	 * If last ACK falls within this segment's sequence numbers, record
5069 	 * the timestamp. NOTE that the test is modified according to the
5070 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
5071 	 */
5072 	if ((to->to_flags & TOF_TS) != 0 &&
5073 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
5074 		tp->ts_recent_age = tcp_ts_getticks();
5075 		tp->ts_recent = to->to_tsval;
5076 	}
5077 	/*
5078 	 * This is a pure ack for outstanding data.
5079 	 */
5080 	TCPSTAT_INC(tcps_predack);
5081 
5082 	/*
5083 	 * "bad retransmit" recovery.
5084 	 */
5085 	if (tp->t_flags & TF_PREVVALID) {
5086 		tp->t_flags &= ~TF_PREVVALID;
5087 		if (tp->t_rxtshift == 1 &&
5088 		    (int)(ticks - tp->t_badrxtwin) < 0)
5089 			rack_cong_signal(tp, th, CC_RTO_ERR);
5090 	}
5091 	/*
5092 	 * Recalculate the transmit timer / rtt.
5093 	 *
5094 	 * Some boxes send broken timestamp replies during the SYN+ACK
5095 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
5096 	 * and blow up the retransmit timer.
5097 	 */
5098 	acked = BYTES_THIS_ACK(tp, th);
5099 
5100 #ifdef TCP_HHOOK
5101 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
5102 	hhook_run_tcp_est_in(tp, th, to);
5103 #endif
5104 
5105 	TCPSTAT_ADD(tcps_rcvackpack, nsegs);
5106 	TCPSTAT_ADD(tcps_rcvackbyte, acked);
5107 	sbdrop(&so->so_snd, acked);
5108 	/*
5109 	 * Let the congestion control algorithm update congestion control
5110 	 * related information. This typically means increasing the
5111 	 * congestion window.
5112 	 */
5113 	rack_ack_received(tp, rack, th, nsegs, CC_ACK, 0);
5114 
5115 	tp->snd_una = th->th_ack;
5116 	/*
5117 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
5118 	 */
5119 	tp->snd_wl2 = th->th_ack;
5120 	tp->t_dupacks = 0;
5121 	m_freem(m);
5122 	/* ND6_HINT(tp);	 *//* Some progress has been made. */
5123 
5124 	/*
5125 	 * If all outstanding data are acked, stop retransmit timer,
5126 	 * otherwise restart timer using current (possibly backed-off)
5127 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
5128 	 * If data are ready to send, let tcp_output decide between more
5129 	 * output or persist.
5130 	 */
5131 #ifdef TCPDEBUG
5132 	if (so->so_options & SO_DEBUG)
5133 		tcp_trace(TA_INPUT, ostate, tp,
5134 		    (void *)tcp_saveipgen,
5135 		    &tcp_savetcp, 0);
5136 #endif
5137 	if (tp->snd_una == tp->snd_max) {
5138 		rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
5139 		tp->t_acktime = 0;
5140 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
5141 	}
5142 	/* Wake up the socket if we have room to write more */
5143 	sowwakeup(so);
5144 	if (sbavail(&so->so_snd)) {
5145 		rack->r_wanted_output++;
5146 	}
5147 	return (1);
5148 }
5149 
5150 /*
5151  * Return value of 1, the TCB is unlocked and most
5152  * likely gone, return value of 0, the TCP is still
5153  * locked.
5154  */
5155 static int
5156 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
5157     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5158     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5159 {
5160 	int32_t ret_val = 0;
5161 	int32_t todrop;
5162 	int32_t ourfinisacked = 0;
5163 
5164 	rack_calc_rwin(so, tp);
5165 	/*
5166 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
5167 	 * SYN, drop the input. if seg contains a RST, then drop the
5168 	 * connection. if seg does not contain SYN, then drop it. Otherwise
5169 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
5170 	 * tp->irs if seg contains ack then advance tp->snd_una if seg
5171 	 * contains an ECE and ECN support is enabled, the stream is ECN
5172 	 * capable. if SYN has been acked change to ESTABLISHED else
5173 	 * SYN_RCVD state arrange for segment to be acked (eventually)
5174 	 * continue processing rest of data/controls, beginning with URG
5175 	 */
5176 	if ((thflags & TH_ACK) &&
5177 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
5178 	    SEQ_GT(th->th_ack, tp->snd_max))) {
5179 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5180 		return (1);
5181 	}
5182 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
5183 		TCP_PROBE5(connect__refused, NULL, tp,
5184 		    mtod(m, const char *), tp, th);
5185 		tp = tcp_drop(tp, ECONNREFUSED);
5186 		rack_do_drop(m, tp);
5187 		return (1);
5188 	}
5189 	if (thflags & TH_RST) {
5190 		rack_do_drop(m, tp);
5191 		return (1);
5192 	}
5193 	if (!(thflags & TH_SYN)) {
5194 		rack_do_drop(m, tp);
5195 		return (1);
5196 	}
5197 	tp->irs = th->th_seq;
5198 	tcp_rcvseqinit(tp);
5199 	if (thflags & TH_ACK) {
5200 		int tfo_partial = 0;
5201 
5202 		TCPSTAT_INC(tcps_connects);
5203 		soisconnected(so);
5204 #ifdef MAC
5205 		mac_socketpeer_set_from_mbuf(m, so);
5206 #endif
5207 		/* Do window scaling on this connection? */
5208 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
5209 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
5210 			tp->rcv_scale = tp->request_r_scale;
5211 		}
5212 		tp->rcv_adv += min(tp->rcv_wnd,
5213 		    TCP_MAXWIN << tp->rcv_scale);
5214 		/*
5215 		 * If not all the data that was sent in the TFO SYN
5216 		 * has been acked, resend the remainder right away.
5217 		 */
5218 		if (IS_FASTOPEN(tp->t_flags) &&
5219 		    (tp->snd_una != tp->snd_max)) {
5220 			tp->snd_nxt = th->th_ack;
5221 			tfo_partial = 1;
5222 		}
5223 		/*
5224 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
5225 		 * will be turned on later.
5226 		 */
5227 		if (DELAY_ACK(tp, tlen) && tlen != 0 && (tfo_partial == 0)) {
5228 			rack_timer_cancel(tp, (struct tcp_rack *)tp->t_fb_ptr,
5229 					  ((struct tcp_rack *)tp->t_fb_ptr)->r_ctl.rc_rcvtime, __LINE__);
5230 			tp->t_flags |= TF_DELACK;
5231 		} else {
5232 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output++;
5233 			tp->t_flags |= TF_ACKNOW;
5234 		}
5235 
5236 		if ((thflags & TH_ECE) && V_tcp_do_ecn) {
5237 			tp->t_flags |= TF_ECN_PERMIT;
5238 			TCPSTAT_INC(tcps_ecn_shs);
5239 		}
5240 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
5241 			/*
5242 			 * We advance snd_una for the
5243 			 * fast open case. If th_ack is
5244 			 * acknowledging data beyond
5245 			 * snd_una we can't just call
5246 			 * ack-processing since the
5247 			 * data stream in our send-map
5248 			 * will start at snd_una + 1 (one
5249 			 * beyond the SYN). If its just
5250 			 * equal we don't need to do that
5251 			 * and there is no send_map.
5252 			 */
5253 			tp->snd_una++;
5254 		}
5255 		/*
5256 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
5257 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
5258 		 */
5259 		tp->t_starttime = ticks;
5260 		if (tp->t_flags & TF_NEEDFIN) {
5261 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
5262 			tp->t_flags &= ~TF_NEEDFIN;
5263 			thflags &= ~TH_SYN;
5264 		} else {
5265 			tcp_state_change(tp, TCPS_ESTABLISHED);
5266 			TCP_PROBE5(connect__established, NULL, tp,
5267 			    mtod(m, const char *), tp, th);
5268 			cc_conn_init(tp);
5269 		}
5270 	} else {
5271 		/*
5272 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
5273 		 * open.  If segment contains CC option and there is a
5274 		 * cached CC, apply TAO test. If it succeeds, connection is *
5275 		 * half-synchronized. Otherwise, do 3-way handshake:
5276 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
5277 		 * there was no CC option, clear cached CC value.
5278 		 */
5279 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
5280 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
5281 	}
5282 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
5283 	INP_WLOCK_ASSERT(tp->t_inpcb);
5284 	/*
5285 	 * Advance th->th_seq to correspond to first data byte. If data,
5286 	 * trim to stay within window, dropping FIN if necessary.
5287 	 */
5288 	th->th_seq++;
5289 	if (tlen > tp->rcv_wnd) {
5290 		todrop = tlen - tp->rcv_wnd;
5291 		m_adj(m, -todrop);
5292 		tlen = tp->rcv_wnd;
5293 		thflags &= ~TH_FIN;
5294 		TCPSTAT_INC(tcps_rcvpackafterwin);
5295 		TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
5296 	}
5297 	tp->snd_wl1 = th->th_seq - 1;
5298 	tp->rcv_up = th->th_seq;
5299 	/*
5300 	 * Client side of transaction: already sent SYN and data. If the
5301 	 * remote host used T/TCP to validate the SYN, our data will be
5302 	 * ACK'd; if so, enter normal data segment processing in the middle
5303 	 * of step 5, ack processing. Otherwise, goto step 6.
5304 	 */
5305 	if (thflags & TH_ACK) {
5306 		if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
5307 			return (ret_val);
5308 		/* We may have changed to FIN_WAIT_1 above */
5309 		if (tp->t_state == TCPS_FIN_WAIT_1) {
5310 			/*
5311 			 * In FIN_WAIT_1 STATE in addition to the processing
5312 			 * for the ESTABLISHED state if our FIN is now
5313 			 * acknowledged then enter FIN_WAIT_2.
5314 			 */
5315 			if (ourfinisacked) {
5316 				/*
5317 				 * If we can't receive any more data, then
5318 				 * closing user can proceed. Starting the
5319 				 * timer is contrary to the specification,
5320 				 * but if we don't get a FIN we'll hang
5321 				 * forever.
5322 				 *
5323 				 * XXXjl: we should release the tp also, and
5324 				 * use a compressed state.
5325 				 */
5326 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5327 					soisdisconnected(so);
5328 					tcp_timer_activate(tp, TT_2MSL,
5329 					    (tcp_fast_finwait2_recycle ?
5330 					    tcp_finwait2_timeout :
5331 					    TP_MAXIDLE(tp)));
5332 				}
5333 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
5334 			}
5335 		}
5336 	}
5337 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5338 	   tiwin, thflags, nxt_pkt));
5339 }
5340 
5341 /*
5342  * Return value of 1, the TCB is unlocked and most
5343  * likely gone, return value of 0, the TCP is still
5344  * locked.
5345  */
5346 static int
5347 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
5348     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5349     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5350 {
5351 	int32_t ret_val = 0;
5352 	int32_t ourfinisacked = 0;
5353 
5354 	rack_calc_rwin(so, tp);
5355 
5356 	if ((thflags & TH_ACK) &&
5357 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
5358 	    SEQ_GT(th->th_ack, tp->snd_max))) {
5359 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5360 		return (1);
5361 	}
5362 	if (IS_FASTOPEN(tp->t_flags)) {
5363 		/*
5364 		 * When a TFO connection is in SYN_RECEIVED, the
5365 		 * only valid packets are the initial SYN, a
5366 		 * retransmit/copy of the initial SYN (possibly with
5367 		 * a subset of the original data), a valid ACK, a
5368 		 * FIN, or a RST.
5369 		 */
5370 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
5371 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5372 			return (1);
5373 		} else if (thflags & TH_SYN) {
5374 			/* non-initial SYN is ignored */
5375 			struct tcp_rack *rack;
5376 
5377 			rack = (struct tcp_rack *)tp->t_fb_ptr;
5378 			if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
5379 			    (rack->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
5380 			    (rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
5381 				rack_do_drop(m, NULL);
5382 				return (0);
5383 			}
5384 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
5385 			rack_do_drop(m, NULL);
5386 			return (0);
5387 		}
5388 	}
5389 	if (thflags & TH_RST)
5390 		return (rack_process_rst(m, th, so, tp));
5391 	/*
5392 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5393 	 * it's less than ts_recent, drop it.
5394 	 */
5395 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5396 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5397 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5398 			return (ret_val);
5399 	}
5400 	/*
5401 	 * In the SYN-RECEIVED state, validate that the packet belongs to
5402 	 * this connection before trimming the data to fit the receive
5403 	 * window.  Check the sequence number versus IRS since we know the
5404 	 * sequence numbers haven't wrapped.  This is a partial fix for the
5405 	 * "LAND" DoS attack.
5406 	 */
5407 	if (SEQ_LT(th->th_seq, tp->irs)) {
5408 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5409 		return (1);
5410 	}
5411 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5412 		return (ret_val);
5413 	}
5414 	/*
5415 	 * If last ACK falls within this segment's sequence numbers, record
5416 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5417 	 * from the latest proposal of the tcplw@cray.com list (Braden
5418 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5419 	 * with our earlier PAWS tests, so this check should be solely
5420 	 * predicated on the sequence space of this segment. 3) That we
5421 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5422 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5423 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5424 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5425 	 * p.869. In such cases, we can still calculate the RTT correctly
5426 	 * when RCV.NXT == Last.ACK.Sent.
5427 	 */
5428 	if ((to->to_flags & TOF_TS) != 0 &&
5429 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5430 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5431 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5432 		tp->ts_recent_age = tcp_ts_getticks();
5433 		tp->ts_recent = to->to_tsval;
5434 	}
5435 	/*
5436 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5437 	 * is on (half-synchronized state), then queue data for later
5438 	 * processing; else drop segment and return.
5439 	 */
5440 	if ((thflags & TH_ACK) == 0) {
5441 		if (IS_FASTOPEN(tp->t_flags)) {
5442 			tp->snd_wnd = tiwin;
5443 			cc_conn_init(tp);
5444 		}
5445 		return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5446 		    tiwin, thflags, nxt_pkt));
5447 	}
5448 	TCPSTAT_INC(tcps_connects);
5449 	soisconnected(so);
5450 	/* Do window scaling? */
5451 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
5452 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
5453 		tp->rcv_scale = tp->request_r_scale;
5454 		tp->snd_wnd = tiwin;
5455 	}
5456 	/*
5457 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
5458 	 * FIN-WAIT-1
5459 	 */
5460 	tp->t_starttime = ticks;
5461 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
5462 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
5463 		tp->t_tfo_pending = NULL;
5464 
5465 		/*
5466 		 * Account for the ACK of our SYN prior to
5467 		 * regular ACK processing below.
5468 		 */
5469 		tp->snd_una++;
5470 	}
5471 	if (tp->t_flags & TF_NEEDFIN) {
5472 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
5473 		tp->t_flags &= ~TF_NEEDFIN;
5474 	} else {
5475 		tcp_state_change(tp, TCPS_ESTABLISHED);
5476 		TCP_PROBE5(accept__established, NULL, tp,
5477 		    mtod(m, const char *), tp, th);
5478 		/*
5479 		 * TFO connections call cc_conn_init() during SYN
5480 		 * processing.  Calling it again here for such connections
5481 		 * is not harmless as it would undo the snd_cwnd reduction
5482 		 * that occurs when a TFO SYN|ACK is retransmitted.
5483 		 */
5484 		if (!IS_FASTOPEN(tp->t_flags))
5485 			cc_conn_init(tp);
5486 	}
5487 	/*
5488 	 * If segment contains data or ACK, will call tcp_reass() later; if
5489 	 * not, do so now to pass queued data to user.
5490 	 */
5491 	if (tlen == 0 && (thflags & TH_FIN) == 0)
5492 		(void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
5493 		    (struct mbuf *)0);
5494 	tp->snd_wl1 = th->th_seq - 1;
5495 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
5496 		return (ret_val);
5497 	}
5498 	if (tp->t_state == TCPS_FIN_WAIT_1) {
5499 		/* We could have went to FIN_WAIT_1 (or EST) above */
5500 		/*
5501 		 * In FIN_WAIT_1 STATE in addition to the processing for the
5502 		 * ESTABLISHED state if our FIN is now acknowledged then
5503 		 * enter FIN_WAIT_2.
5504 		 */
5505 		if (ourfinisacked) {
5506 			/*
5507 			 * If we can't receive any more data, then closing
5508 			 * user can proceed. Starting the timer is contrary
5509 			 * to the specification, but if we don't get a FIN
5510 			 * we'll hang forever.
5511 			 *
5512 			 * XXXjl: we should release the tp also, and use a
5513 			 * compressed state.
5514 			 */
5515 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5516 				soisdisconnected(so);
5517 				tcp_timer_activate(tp, TT_2MSL,
5518 				    (tcp_fast_finwait2_recycle ?
5519 				    tcp_finwait2_timeout :
5520 				    TP_MAXIDLE(tp)));
5521 			}
5522 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
5523 		}
5524 	}
5525 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5526 	    tiwin, thflags, nxt_pkt));
5527 }
5528 
5529 /*
5530  * Return value of 1, the TCB is unlocked and most
5531  * likely gone, return value of 0, the TCP is still
5532  * locked.
5533  */
5534 static int
5535 rack_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
5536     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5537     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5538 {
5539 	int32_t ret_val = 0;
5540 
5541 	/*
5542 	 * Header prediction: check for the two common cases of a
5543 	 * uni-directional data xfer.  If the packet has no control flags,
5544 	 * is in-sequence, the window didn't change and we're not
5545 	 * retransmitting, it's a candidate.  If the length is zero and the
5546 	 * ack moved forward, we're the sender side of the xfer.  Just free
5547 	 * the data acked & wake any higher level process that was blocked
5548 	 * waiting for space.  If the length is non-zero and the ack didn't
5549 	 * move, we're the receiver side.  If we're getting packets in-order
5550 	 * (the reassembly queue is empty), add the data toc The socket
5551 	 * buffer and note that we need a delayed ack. Make sure that the
5552 	 * hidden state-flags are also off. Since we check for
5553 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
5554 	 */
5555 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
5556 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
5557 	    __predict_true(SEGQ_EMPTY(tp)) &&
5558 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
5559 		struct tcp_rack *rack;
5560 
5561 		rack = (struct tcp_rack *)tp->t_fb_ptr;
5562 		if (tlen == 0) {
5563 			if (rack_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
5564 			    tiwin, nxt_pkt, rack->r_ctl.rc_rcvtime)) {
5565 				return (0);
5566 			}
5567 		} else {
5568 			if (rack_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
5569 			    tiwin, nxt_pkt)) {
5570 				return (0);
5571 			}
5572 		}
5573 	}
5574 	rack_calc_rwin(so, tp);
5575 
5576 	if (thflags & TH_RST)
5577 		return (rack_process_rst(m, th, so, tp));
5578 
5579 	/*
5580 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5581 	 * synchronized state.
5582 	 */
5583 	if (thflags & TH_SYN) {
5584 		rack_challenge_ack(m, th, tp, &ret_val);
5585 		return (ret_val);
5586 	}
5587 	/*
5588 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5589 	 * it's less than ts_recent, drop it.
5590 	 */
5591 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5592 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5593 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5594 			return (ret_val);
5595 	}
5596 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5597 		return (ret_val);
5598 	}
5599 	/*
5600 	 * If last ACK falls within this segment's sequence numbers, record
5601 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5602 	 * from the latest proposal of the tcplw@cray.com list (Braden
5603 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5604 	 * with our earlier PAWS tests, so this check should be solely
5605 	 * predicated on the sequence space of this segment. 3) That we
5606 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5607 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5608 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5609 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5610 	 * p.869. In such cases, we can still calculate the RTT correctly
5611 	 * when RCV.NXT == Last.ACK.Sent.
5612 	 */
5613 	if ((to->to_flags & TOF_TS) != 0 &&
5614 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5615 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5616 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5617 		tp->ts_recent_age = tcp_ts_getticks();
5618 		tp->ts_recent = to->to_tsval;
5619 	}
5620 	/*
5621 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5622 	 * is on (half-synchronized state), then queue data for later
5623 	 * processing; else drop segment and return.
5624 	 */
5625 	if ((thflags & TH_ACK) == 0) {
5626 		if (tp->t_flags & TF_NEEDSYN) {
5627 
5628 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5629 			    tiwin, thflags, nxt_pkt));
5630 
5631 		} else if (tp->t_flags & TF_ACKNOW) {
5632 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
5633 			return (ret_val);
5634 		} else {
5635 			rack_do_drop(m, NULL);
5636 			return (0);
5637 		}
5638 	}
5639 	/*
5640 	 * Ack processing.
5641 	 */
5642 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
5643 		return (ret_val);
5644 	}
5645 	if (sbavail(&so->so_snd)) {
5646 		if (rack_progress_timeout_check(tp)) {
5647 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
5648 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5649 			return (1);
5650 		}
5651 	}
5652 	/* State changes only happen in rack_process_data() */
5653 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5654 	    tiwin, thflags, nxt_pkt));
5655 }
5656 
5657 /*
5658  * Return value of 1, the TCB is unlocked and most
5659  * likely gone, return value of 0, the TCP is still
5660  * locked.
5661  */
5662 static int
5663 rack_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
5664     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5665     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5666 {
5667 	int32_t ret_val = 0;
5668 
5669 	rack_calc_rwin(so, tp);
5670 	if (thflags & TH_RST)
5671 		return (rack_process_rst(m, th, so, tp));
5672 	/*
5673 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5674 	 * synchronized state.
5675 	 */
5676 	if (thflags & TH_SYN) {
5677 		rack_challenge_ack(m, th, tp, &ret_val);
5678 		return (ret_val);
5679 	}
5680 	/*
5681 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5682 	 * it's less than ts_recent, drop it.
5683 	 */
5684 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5685 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5686 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5687 			return (ret_val);
5688 	}
5689 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5690 		return (ret_val);
5691 	}
5692 	/*
5693 	 * If last ACK falls within this segment's sequence numbers, record
5694 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5695 	 * from the latest proposal of the tcplw@cray.com list (Braden
5696 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5697 	 * with our earlier PAWS tests, so this check should be solely
5698 	 * predicated on the sequence space of this segment. 3) That we
5699 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5700 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5701 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5702 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5703 	 * p.869. In such cases, we can still calculate the RTT correctly
5704 	 * when RCV.NXT == Last.ACK.Sent.
5705 	 */
5706 	if ((to->to_flags & TOF_TS) != 0 &&
5707 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5708 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5709 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5710 		tp->ts_recent_age = tcp_ts_getticks();
5711 		tp->ts_recent = to->to_tsval;
5712 	}
5713 	/*
5714 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5715 	 * is on (half-synchronized state), then queue data for later
5716 	 * processing; else drop segment and return.
5717 	 */
5718 	if ((thflags & TH_ACK) == 0) {
5719 		if (tp->t_flags & TF_NEEDSYN) {
5720 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5721 			    tiwin, thflags, nxt_pkt));
5722 
5723 		} else if (tp->t_flags & TF_ACKNOW) {
5724 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
5725 			return (ret_val);
5726 		} else {
5727 			rack_do_drop(m, NULL);
5728 			return (0);
5729 		}
5730 	}
5731 	/*
5732 	 * Ack processing.
5733 	 */
5734 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
5735 		return (ret_val);
5736 	}
5737 	if (sbavail(&so->so_snd)) {
5738 		if (rack_progress_timeout_check(tp)) {
5739 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
5740 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5741 			return (1);
5742 		}
5743 	}
5744 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5745 	    tiwin, thflags, nxt_pkt));
5746 }
5747 
5748 static int
5749 rack_check_data_after_close(struct mbuf *m,
5750     struct tcpcb *tp, int32_t *tlen, struct tcphdr *th, struct socket *so)
5751 {
5752 	struct tcp_rack *rack;
5753 
5754 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
5755 	rack = (struct tcp_rack *)tp->t_fb_ptr;
5756 	if (rack->rc_allow_data_af_clo == 0) {
5757 	close_now:
5758 		tp = tcp_close(tp);
5759 		TCPSTAT_INC(tcps_rcvafterclose);
5760 		rack_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
5761 		return (1);
5762 	}
5763 	if (sbavail(&so->so_snd) == 0)
5764 		goto close_now;
5765 	/* Ok we allow data that is ignored and a followup reset */
5766 	tp->rcv_nxt = th->th_seq + *tlen;
5767 	tp->t_flags2 |= TF2_DROP_AF_DATA;
5768 	rack->r_wanted_output = 1;
5769 	*tlen = 0;
5770 	return (0);
5771 }
5772 
5773 /*
5774  * Return value of 1, the TCB is unlocked and most
5775  * likely gone, return value of 0, the TCP is still
5776  * locked.
5777  */
5778 static int
5779 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
5780     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5781     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5782 {
5783 	int32_t ret_val = 0;
5784 	int32_t ourfinisacked = 0;
5785 
5786 	rack_calc_rwin(so, tp);
5787 
5788 	if (thflags & TH_RST)
5789 		return (rack_process_rst(m, th, so, tp));
5790 	/*
5791 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5792 	 * synchronized state.
5793 	 */
5794 	if (thflags & TH_SYN) {
5795 		rack_challenge_ack(m, th, tp, &ret_val);
5796 		return (ret_val);
5797 	}
5798 	/*
5799 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5800 	 * it's less than ts_recent, drop it.
5801 	 */
5802 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5803 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5804 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5805 			return (ret_val);
5806 	}
5807 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5808 		return (ret_val);
5809 	}
5810 	/*
5811 	 * If new data are received on a connection after the user processes
5812 	 * are gone, then RST the other end.
5813 	 */
5814 	if ((so->so_state & SS_NOFDREF) && tlen) {
5815 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
5816 			return (1);
5817 	}
5818 	/*
5819 	 * If last ACK falls within this segment's sequence numbers, record
5820 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5821 	 * from the latest proposal of the tcplw@cray.com list (Braden
5822 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5823 	 * with our earlier PAWS tests, so this check should be solely
5824 	 * predicated on the sequence space of this segment. 3) That we
5825 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5826 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5827 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5828 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5829 	 * p.869. In such cases, we can still calculate the RTT correctly
5830 	 * when RCV.NXT == Last.ACK.Sent.
5831 	 */
5832 	if ((to->to_flags & TOF_TS) != 0 &&
5833 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5834 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5835 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5836 		tp->ts_recent_age = tcp_ts_getticks();
5837 		tp->ts_recent = to->to_tsval;
5838 	}
5839 	/*
5840 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5841 	 * is on (half-synchronized state), then queue data for later
5842 	 * processing; else drop segment and return.
5843 	 */
5844 	if ((thflags & TH_ACK) == 0) {
5845 		if (tp->t_flags & TF_NEEDSYN) {
5846 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5847 			    tiwin, thflags, nxt_pkt));
5848 		} else if (tp->t_flags & TF_ACKNOW) {
5849 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
5850 			return (ret_val);
5851 		} else {
5852 			rack_do_drop(m, NULL);
5853 			return (0);
5854 		}
5855 	}
5856 	/*
5857 	 * Ack processing.
5858 	 */
5859 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
5860 		return (ret_val);
5861 	}
5862 	if (ourfinisacked) {
5863 		/*
5864 		 * If we can't receive any more data, then closing user can
5865 		 * proceed. Starting the timer is contrary to the
5866 		 * specification, but if we don't get a FIN we'll hang
5867 		 * forever.
5868 		 *
5869 		 * XXXjl: we should release the tp also, and use a
5870 		 * compressed state.
5871 		 */
5872 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
5873 			soisdisconnected(so);
5874 			tcp_timer_activate(tp, TT_2MSL,
5875 			    (tcp_fast_finwait2_recycle ?
5876 			    tcp_finwait2_timeout :
5877 			    TP_MAXIDLE(tp)));
5878 		}
5879 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
5880 	}
5881 	if (sbavail(&so->so_snd)) {
5882 		if (rack_progress_timeout_check(tp)) {
5883 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
5884 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5885 			return (1);
5886 		}
5887 	}
5888 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5889 	    tiwin, thflags, nxt_pkt));
5890 }
5891 
5892 /*
5893  * Return value of 1, the TCB is unlocked and most
5894  * likely gone, return value of 0, the TCP is still
5895  * locked.
5896  */
5897 static int
5898 rack_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
5899     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
5900     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
5901 {
5902 	int32_t ret_val = 0;
5903 	int32_t ourfinisacked = 0;
5904 
5905 	rack_calc_rwin(so, tp);
5906 
5907 	if (thflags & TH_RST)
5908 		return (rack_process_rst(m, th, so, tp));
5909 	/*
5910 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
5911 	 * synchronized state.
5912 	 */
5913 	if (thflags & TH_SYN) {
5914 		rack_challenge_ack(m, th, tp, &ret_val);
5915 		return (ret_val);
5916 	}
5917 	/*
5918 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
5919 	 * it's less than ts_recent, drop it.
5920 	 */
5921 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
5922 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
5923 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
5924 			return (ret_val);
5925 	}
5926 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
5927 		return (ret_val);
5928 	}
5929 	/*
5930 	 * If new data are received on a connection after the user processes
5931 	 * are gone, then RST the other end.
5932 	 */
5933 	if ((so->so_state & SS_NOFDREF) && tlen) {
5934 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
5935 			return (1);
5936 	}
5937 	/*
5938 	 * If last ACK falls within this segment's sequence numbers, record
5939 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
5940 	 * from the latest proposal of the tcplw@cray.com list (Braden
5941 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
5942 	 * with our earlier PAWS tests, so this check should be solely
5943 	 * predicated on the sequence space of this segment. 3) That we
5944 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
5945 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
5946 	 * SEG.Len, This modified check allows us to overcome RFC1323's
5947 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
5948 	 * p.869. In such cases, we can still calculate the RTT correctly
5949 	 * when RCV.NXT == Last.ACK.Sent.
5950 	 */
5951 	if ((to->to_flags & TOF_TS) != 0 &&
5952 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
5953 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
5954 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
5955 		tp->ts_recent_age = tcp_ts_getticks();
5956 		tp->ts_recent = to->to_tsval;
5957 	}
5958 	/*
5959 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
5960 	 * is on (half-synchronized state), then queue data for later
5961 	 * processing; else drop segment and return.
5962 	 */
5963 	if ((thflags & TH_ACK) == 0) {
5964 		if (tp->t_flags & TF_NEEDSYN) {
5965 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5966 			    tiwin, thflags, nxt_pkt));
5967 		} else if (tp->t_flags & TF_ACKNOW) {
5968 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
5969 			return (ret_val);
5970 		} else {
5971 			rack_do_drop(m, NULL);
5972 			return (0);
5973 		}
5974 	}
5975 	/*
5976 	 * Ack processing.
5977 	 */
5978 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
5979 		return (ret_val);
5980 	}
5981 	if (ourfinisacked) {
5982 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
5983 		tcp_twstart(tp);
5984 		m_freem(m);
5985 		return (1);
5986 	}
5987 	if (sbavail(&so->so_snd)) {
5988 		if (rack_progress_timeout_check(tp)) {
5989 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
5990 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
5991 			return (1);
5992 		}
5993 	}
5994 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
5995 	    tiwin, thflags, nxt_pkt));
5996 }
5997 
5998 /*
5999  * Return value of 1, the TCB is unlocked and most
6000  * likely gone, return value of 0, the TCP is still
6001  * locked.
6002  */
6003 static int
6004 rack_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
6005     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
6006     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
6007 {
6008 	int32_t ret_val = 0;
6009 	int32_t ourfinisacked = 0;
6010 
6011 	rack_calc_rwin(so, tp);
6012 
6013 	if (thflags & TH_RST)
6014 		return (rack_process_rst(m, th, so, tp));
6015 	/*
6016 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
6017 	 * synchronized state.
6018 	 */
6019 	if (thflags & TH_SYN) {
6020 		rack_challenge_ack(m, th, tp, &ret_val);
6021 		return (ret_val);
6022 	}
6023 	/*
6024 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
6025 	 * it's less than ts_recent, drop it.
6026 	 */
6027 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
6028 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
6029 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
6030 			return (ret_val);
6031 	}
6032 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
6033 		return (ret_val);
6034 	}
6035 	/*
6036 	 * If new data are received on a connection after the user processes
6037 	 * are gone, then RST the other end.
6038 	 */
6039 	if ((so->so_state & SS_NOFDREF) && tlen) {
6040 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
6041 			return (1);
6042 	}
6043 	/*
6044 	 * If last ACK falls within this segment's sequence numbers, record
6045 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
6046 	 * from the latest proposal of the tcplw@cray.com list (Braden
6047 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
6048 	 * with our earlier PAWS tests, so this check should be solely
6049 	 * predicated on the sequence space of this segment. 3) That we
6050 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
6051 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
6052 	 * SEG.Len, This modified check allows us to overcome RFC1323's
6053 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
6054 	 * p.869. In such cases, we can still calculate the RTT correctly
6055 	 * when RCV.NXT == Last.ACK.Sent.
6056 	 */
6057 	if ((to->to_flags & TOF_TS) != 0 &&
6058 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
6059 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
6060 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
6061 		tp->ts_recent_age = tcp_ts_getticks();
6062 		tp->ts_recent = to->to_tsval;
6063 	}
6064 	/*
6065 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
6066 	 * is on (half-synchronized state), then queue data for later
6067 	 * processing; else drop segment and return.
6068 	 */
6069 	if ((thflags & TH_ACK) == 0) {
6070 		if (tp->t_flags & TF_NEEDSYN) {
6071 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6072 			    tiwin, thflags, nxt_pkt));
6073 		} else if (tp->t_flags & TF_ACKNOW) {
6074 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
6075 			return (ret_val);
6076 		} else {
6077 			rack_do_drop(m, NULL);
6078 			return (0);
6079 		}
6080 	}
6081 	/*
6082 	 * case TCPS_LAST_ACK: Ack processing.
6083 	 */
6084 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
6085 		return (ret_val);
6086 	}
6087 	if (ourfinisacked) {
6088 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
6089 		tp = tcp_close(tp);
6090 		rack_do_drop(m, tp);
6091 		return (1);
6092 	}
6093 	if (sbavail(&so->so_snd)) {
6094 		if (rack_progress_timeout_check(tp)) {
6095 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6096 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6097 			return (1);
6098 		}
6099 	}
6100 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6101 	    tiwin, thflags, nxt_pkt));
6102 }
6103 
6104 
6105 /*
6106  * Return value of 1, the TCB is unlocked and most
6107  * likely gone, return value of 0, the TCP is still
6108  * locked.
6109  */
6110 static int
6111 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
6112     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
6113     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
6114 {
6115 	int32_t ret_val = 0;
6116 	int32_t ourfinisacked = 0;
6117 
6118 	rack_calc_rwin(so, tp);
6119 
6120 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
6121 	if (thflags & TH_RST)
6122 		return (rack_process_rst(m, th, so, tp));
6123 	/*
6124 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
6125 	 * synchronized state.
6126 	 */
6127 	if (thflags & TH_SYN) {
6128 		rack_challenge_ack(m, th, tp, &ret_val);
6129 		return (ret_val);
6130 	}
6131 	/*
6132 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
6133 	 * it's less than ts_recent, drop it.
6134 	 */
6135 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
6136 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
6137 		if (rack_ts_check(m, th, tp, tlen, thflags, &ret_val))
6138 			return (ret_val);
6139 	}
6140 	if (rack_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
6141 		return (ret_val);
6142 	}
6143 	/*
6144 	 * If new data are received on a connection after the user processes
6145 	 * are gone, then RST the other end.
6146 	 */
6147 	if ((so->so_state & SS_NOFDREF) &&
6148 	    tlen) {
6149 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
6150 			return (1);
6151 	}
6152 	/*
6153 	 * If last ACK falls within this segment's sequence numbers, record
6154 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
6155 	 * from the latest proposal of the tcplw@cray.com list (Braden
6156 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
6157 	 * with our earlier PAWS tests, so this check should be solely
6158 	 * predicated on the sequence space of this segment. 3) That we
6159 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
6160 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
6161 	 * SEG.Len, This modified check allows us to overcome RFC1323's
6162 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
6163 	 * p.869. In such cases, we can still calculate the RTT correctly
6164 	 * when RCV.NXT == Last.ACK.Sent.
6165 	 */
6166 	if ((to->to_flags & TOF_TS) != 0 &&
6167 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
6168 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
6169 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
6170 		tp->ts_recent_age = tcp_ts_getticks();
6171 		tp->ts_recent = to->to_tsval;
6172 	}
6173 	/*
6174 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
6175 	 * is on (half-synchronized state), then queue data for later
6176 	 * processing; else drop segment and return.
6177 	 */
6178 	if ((thflags & TH_ACK) == 0) {
6179 		if (tp->t_flags & TF_NEEDSYN) {
6180 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6181 			    tiwin, thflags, nxt_pkt));
6182 		} else if (tp->t_flags & TF_ACKNOW) {
6183 			rack_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
6184 			return (ret_val);
6185 		} else {
6186 			rack_do_drop(m, NULL);
6187 			return (0);
6188 		}
6189 	}
6190 	/*
6191 	 * Ack processing.
6192 	 */
6193 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
6194 		return (ret_val);
6195 	}
6196 	if (sbavail(&so->so_snd)) {
6197 		if (rack_progress_timeout_check(tp)) {
6198 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6199 			rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6200 			return (1);
6201 		}
6202 	}
6203 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
6204 	    tiwin, thflags, nxt_pkt));
6205 }
6206 
6207 
6208 static void inline
6209 rack_clear_rate_sample(struct tcp_rack *rack)
6210 {
6211 	rack->r_ctl.rack_rs.rs_flags = RACK_RTT_EMPTY;
6212 	rack->r_ctl.rack_rs.rs_rtt_cnt = 0;
6213 	rack->r_ctl.rack_rs.rs_rtt_tot = 0;
6214 }
6215 
6216 static int
6217 rack_init(struct tcpcb *tp)
6218 {
6219 	struct tcp_rack *rack = NULL;
6220 
6221 	tp->t_fb_ptr = uma_zalloc(rack_pcb_zone, M_NOWAIT);
6222 	if (tp->t_fb_ptr == NULL) {
6223 		/*
6224 		 * We need to allocate memory but cant. The INP and INP_INFO
6225 		 * locks and they are recusive (happens during setup. So a
6226 		 * scheme to drop the locks fails :(
6227 		 *
6228 		 */
6229 		return (ENOMEM);
6230 	}
6231 	memset(tp->t_fb_ptr, 0, sizeof(struct tcp_rack));
6232 
6233 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6234 	TAILQ_INIT(&rack->r_ctl.rc_map);
6235 	TAILQ_INIT(&rack->r_ctl.rc_free);
6236 	TAILQ_INIT(&rack->r_ctl.rc_tmap);
6237 	rack->rc_tp = tp;
6238 	if (tp->t_inpcb) {
6239 		rack->rc_inp = tp->t_inpcb;
6240 	}
6241 	/* Probably not needed but lets be sure */
6242 	rack_clear_rate_sample(rack);
6243 	rack->r_cpu = 0;
6244 	rack->r_ctl.rc_reorder_fade = rack_reorder_fade;
6245 	rack->rc_allow_data_af_clo = rack_ignore_data_after_close;
6246 	rack->r_ctl.rc_tlp_threshold = rack_tlp_thresh;
6247 	rack->rc_pace_reduce = rack_slot_reduction;
6248 	if (V_tcp_delack_enabled)
6249 		tp->t_delayed_ack = 1;
6250 	else
6251 		tp->t_delayed_ack = 0;
6252 	rack->rc_pace_max_segs = rack_hptsi_segments;
6253 	rack->r_ctl.rc_early_recovery_segs = rack_early_recovery_max_seg;
6254 	rack->r_ctl.rc_reorder_shift = rack_reorder_thresh;
6255 	rack->r_ctl.rc_pkt_delay = rack_pkt_delay;
6256 	rack->r_ctl.rc_prop_reduce = rack_use_proportional_reduce;
6257 	rack->r_idle_reduce_largest  = rack_reduce_largest_on_idle;
6258 	rack->r_enforce_min_pace = rack_min_pace_time;
6259 	rack->r_min_pace_seg_thresh = rack_min_pace_time_seg_req;
6260 	rack->r_ctl.rc_prop_rate = rack_proportional_rate;
6261 	rack->r_ctl.rc_tlp_cwnd_reduce = rack_lower_cwnd_at_tlp;
6262 	rack->r_ctl.rc_early_recovery = rack_early_recovery;
6263 	rack->rc_always_pace = rack_pace_every_seg;
6264 	rack->r_ctl.rc_rate_sample_method = rack_rate_sample_method;
6265 	rack->rack_tlp_threshold_use = rack_tlp_threshold_use;
6266 	rack->r_ctl.rc_prr_sendalot = rack_send_a_lot_in_prr;
6267 	rack->r_ctl.rc_min_to = rack_min_to;
6268 	rack->r_ctl.rc_prr_inc_var = rack_inc_var;
6269 	rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6270 	if (tp->snd_una != tp->snd_max) {
6271 		/* Create a send map for the current outstanding data */
6272 		struct rack_sendmap *rsm;
6273 
6274 		rsm = rack_alloc(rack);
6275 		if (rsm == NULL) {
6276 			uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
6277 			tp->t_fb_ptr = NULL;
6278 			return (ENOMEM);
6279 		}
6280 		rsm->r_flags = RACK_OVERMAX;
6281 		rsm->r_tim_lastsent[0] = tcp_ts_getticks();
6282 		rsm->r_rtr_cnt = 1;
6283 		rsm->r_rtr_bytes = 0;
6284 		rsm->r_start = tp->snd_una;
6285 		rsm->r_end = tp->snd_max;
6286 		rsm->r_sndcnt = 0;
6287 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_map, rsm, r_next);
6288 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
6289 		rsm->r_in_tmap = 1;
6290 	}
6291 	return (0);
6292 }
6293 
6294 static int
6295 rack_handoff_ok(struct tcpcb *tp)
6296 {
6297 	if ((tp->t_state == TCPS_CLOSED) ||
6298 	    (tp->t_state == TCPS_LISTEN)) {
6299 		/* Sure no problem though it may not stick */
6300 		return (0);
6301 	}
6302 	if ((tp->t_state == TCPS_SYN_SENT) ||
6303 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
6304 		/*
6305 		 * We really don't know you have to get to ESTAB or beyond
6306 		 * to tell.
6307 		 */
6308 		return (EAGAIN);
6309 	}
6310 	if (tp->t_flags & TF_SACK_PERMIT) {
6311 		return (0);
6312 	}
6313 	/*
6314 	 * If we reach here we don't do SACK on this connection so we can
6315 	 * never do rack.
6316 	 */
6317 	return (EINVAL);
6318 }
6319 
6320 static void
6321 rack_fini(struct tcpcb *tp, int32_t tcb_is_purged)
6322 {
6323 	if (tp->t_fb_ptr) {
6324 		struct tcp_rack *rack;
6325 		struct rack_sendmap *rsm;
6326 
6327 		rack = (struct tcp_rack *)tp->t_fb_ptr;
6328 #ifdef TCP_BLACKBOX
6329 		tcp_log_flowend(tp);
6330 #endif
6331 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
6332 		while (rsm) {
6333 			TAILQ_REMOVE(&rack->r_ctl.rc_map, rsm, r_next);
6334 			uma_zfree(rack_zone, rsm);
6335 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_map);
6336 		}
6337 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
6338 		while (rsm) {
6339 			TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_next);
6340 			uma_zfree(rack_zone, rsm);
6341 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
6342 		}
6343 		rack->rc_free_cnt = 0;
6344 		uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
6345 		tp->t_fb_ptr = NULL;
6346 	}
6347 }
6348 
6349 static void
6350 rack_set_state(struct tcpcb *tp, struct tcp_rack *rack)
6351 {
6352 	switch (tp->t_state) {
6353 	case TCPS_SYN_SENT:
6354 		rack->r_state = TCPS_SYN_SENT;
6355 		rack->r_substate = rack_do_syn_sent;
6356 		break;
6357 	case TCPS_SYN_RECEIVED:
6358 		rack->r_state = TCPS_SYN_RECEIVED;
6359 		rack->r_substate = rack_do_syn_recv;
6360 		break;
6361 	case TCPS_ESTABLISHED:
6362 		rack->r_state = TCPS_ESTABLISHED;
6363 		rack->r_substate = rack_do_established;
6364 		break;
6365 	case TCPS_CLOSE_WAIT:
6366 		rack->r_state = TCPS_CLOSE_WAIT;
6367 		rack->r_substate = rack_do_close_wait;
6368 		break;
6369 	case TCPS_FIN_WAIT_1:
6370 		rack->r_state = TCPS_FIN_WAIT_1;
6371 		rack->r_substate = rack_do_fin_wait_1;
6372 		break;
6373 	case TCPS_CLOSING:
6374 		rack->r_state = TCPS_CLOSING;
6375 		rack->r_substate = rack_do_closing;
6376 		break;
6377 	case TCPS_LAST_ACK:
6378 		rack->r_state = TCPS_LAST_ACK;
6379 		rack->r_substate = rack_do_lastack;
6380 		break;
6381 	case TCPS_FIN_WAIT_2:
6382 		rack->r_state = TCPS_FIN_WAIT_2;
6383 		rack->r_substate = rack_do_fin_wait_2;
6384 		break;
6385 	case TCPS_LISTEN:
6386 	case TCPS_CLOSED:
6387 	case TCPS_TIME_WAIT:
6388 	default:
6389 #ifdef INVARIANTS
6390 		panic("tcp tp:%p state:%d sees impossible state?", tp, tp->t_state);
6391 #endif
6392 		break;
6393 	};
6394 }
6395 
6396 
6397 static void
6398 rack_timer_audit(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb)
6399 {
6400 	/*
6401 	 * We received an ack, and then did not
6402 	 * call send or were bounced out due to the
6403 	 * hpts was running. Now a timer is up as well, is
6404 	 * it the right timer?
6405 	 */
6406 	struct rack_sendmap *rsm;
6407 	int tmr_up;
6408 
6409 	tmr_up = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
6410 	if (rack->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
6411 		return;
6412 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6413 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
6414 	    (tmr_up == PACE_TMR_RXT)) {
6415 		/* Should be an RXT */
6416 		return;
6417 	}
6418 	if (rsm == NULL) {
6419 		/* Nothing outstanding? */
6420 		if (tp->t_flags & TF_DELACK) {
6421 			if (tmr_up == PACE_TMR_DELACK)
6422 				/* We are supposed to have delayed ack up and we do */
6423 				return;
6424 		} else if (sbavail(&tp->t_inpcb->inp_socket->so_snd) && (tmr_up == PACE_TMR_RXT)) {
6425 			/*
6426 			 * if we hit enobufs then we would expect the possiblity
6427 			 * of nothing outstanding and the RXT up (and the hptsi timer).
6428 			 */
6429 			return;
6430 		} else if (((tcp_always_keepalive ||
6431 			     rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
6432 			    (tp->t_state <= TCPS_CLOSING)) &&
6433 			   (tmr_up == PACE_TMR_KEEP) &&
6434 			   (tp->snd_max == tp->snd_una)) {
6435 			/* We should have keep alive up and we do */
6436 			return;
6437 		}
6438 	}
6439 	if (rsm && (rsm->r_flags & RACK_SACK_PASSED)) {
6440 		if ((tp->t_flags & TF_SENTFIN) &&
6441 		    ((tp->snd_max - tp->snd_una) == 1) &&
6442 		    (rsm->r_flags & RACK_HAS_FIN)) {
6443 			/* needs to be a RXT */
6444 			if (tmr_up == PACE_TMR_RXT)
6445 				return;
6446 		} else if (tmr_up == PACE_TMR_RACK)
6447 			return;
6448 	} else if (SEQ_GT(tp->snd_max,tp->snd_una) &&
6449 		   ((tmr_up == PACE_TMR_TLP) ||
6450 		    (tmr_up == PACE_TMR_RXT))) {
6451 		/*
6452 		 * Either a TLP or RXT is fine if no sack-passed
6453 		 * is in place and data is outstanding.
6454 		 */
6455 		return;
6456 	} else if (tmr_up == PACE_TMR_DELACK) {
6457 		/*
6458 		 * If the delayed ack was going to go off
6459 		 * before the rtx/tlp/rack timer were going to
6460 		 * expire, then that would be the timer in control.
6461 		 * Note we don't check the time here trusting the
6462 		 * code is correct.
6463 		 */
6464 		return;
6465 	}
6466 	/*
6467 	 * Ok the timer originally started is not what we want now.
6468 	 * We will force the hpts to be stopped if any, and restart
6469 	 * with the slot set to what was in the saved slot.
6470 	 */
6471 	rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
6472 	rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6473 }
6474 
6475 static void
6476 rack_hpts_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
6477     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
6478     int32_t nxt_pkt, struct timeval *tv)
6479 {
6480 	int32_t thflags, retval, did_out = 0;
6481 	int32_t way_out = 0;
6482 	uint32_t cts;
6483 	uint32_t tiwin;
6484 	struct tcpopt to;
6485 	struct tcp_rack *rack;
6486 	struct rack_sendmap *rsm;
6487 	int32_t prev_state = 0;
6488 
6489 	cts = tcp_tv_to_mssectick(tv);
6490 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6491 
6492 	kern_prefetch(rack, &prev_state);
6493 	prev_state = 0;
6494 	thflags = th->th_flags;
6495 	/*
6496 	 * If this is either a state-changing packet or current state isn't
6497 	 * established, we require a read lock on tcbinfo.  Otherwise, we
6498 	 * allow the tcbinfo to be in either locked or unlocked, as the
6499 	 * caller may have unnecessarily acquired a lock due to a race.
6500 	 */
6501 	if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
6502 	    tp->t_state != TCPS_ESTABLISHED) {
6503 		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
6504 	}
6505 	INP_WLOCK_ASSERT(tp->t_inpcb);
6506 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
6507 	    __func__));
6508 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
6509 	    __func__));
6510 	{
6511 		union tcp_log_stackspecific log;
6512 
6513 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
6514 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
6515 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
6516 		TCP_LOG_EVENT(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
6517 		    tlen, &log, true);
6518 	}
6519 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
6520 		way_out = 4;
6521 		goto done_with_input;
6522 	}
6523 	/*
6524 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
6525 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
6526 	 */
6527 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
6528 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
6529 		rack_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
6530 		return;
6531 	}
6532 	/*
6533 	 * Segment received on connection. Reset idle time and keep-alive
6534 	 * timer. XXX: This should be done after segment validation to
6535 	 * ignore broken/spoofed segs.
6536 	 */
6537 	if  (tp->t_idle_reduce && (tp->snd_max == tp->snd_una)) {
6538 #ifdef NETFLIX_CWV
6539 		if ((tp->cwv_enabled) &&
6540 		    ((tp->cwv_cwnd_valid == 0) &&
6541 		     TCPS_HAVEESTABLISHED(tp->t_state) &&
6542 		     (tp->snd_cwnd > tp->snd_cwv.init_cwnd))) {
6543 			tcp_newcwv_nvp_closedown(tp);
6544 		} else
6545 #endif
6546 		       if ((ticks - tp->t_rcvtime) >= tp->t_rxtcur) {
6547 			counter_u64_add(rack_input_idle_reduces, 1);
6548 			rack_cc_after_idle(tp,
6549 			    (rack->r_idle_reduce_largest ? 1 :0));
6550 		}
6551 	}
6552 	rack->r_ctl.rc_rcvtime = cts;
6553 	tp->t_rcvtime = ticks;
6554 
6555 #ifdef NETFLIX_CWV
6556 	if (tp->cwv_enabled) {
6557 		if ((tp->cwv_cwnd_valid == 0) &&
6558 		    TCPS_HAVEESTABLISHED(tp->t_state) &&
6559 		    (tp->snd_cwnd > tp->snd_cwv.init_cwnd))
6560 			tcp_newcwv_nvp_closedown(tp);
6561 	}
6562 #endif
6563 	/*
6564 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
6565 	 * the scale is zero.
6566 	 */
6567 	tiwin = th->th_win << tp->snd_scale;
6568 #ifdef NETFLIX_STATS
6569 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
6570 #endif
6571 	/*
6572 	 * TCP ECN processing. XXXJTL: If we ever use ECN, we need to move
6573 	 * this to occur after we've validated the segment.
6574 	 */
6575 	if (tp->t_flags & TF_ECN_PERMIT) {
6576 		if (thflags & TH_CWR)
6577 			tp->t_flags &= ~TF_ECN_SND_ECE;
6578 		switch (iptos & IPTOS_ECN_MASK) {
6579 		case IPTOS_ECN_CE:
6580 			tp->t_flags |= TF_ECN_SND_ECE;
6581 			TCPSTAT_INC(tcps_ecn_ce);
6582 			break;
6583 		case IPTOS_ECN_ECT0:
6584 			TCPSTAT_INC(tcps_ecn_ect0);
6585 			break;
6586 		case IPTOS_ECN_ECT1:
6587 			TCPSTAT_INC(tcps_ecn_ect1);
6588 			break;
6589 		}
6590 		/* Congestion experienced. */
6591 		if (thflags & TH_ECE) {
6592 			rack_cong_signal(tp, th, CC_ECN);
6593 		}
6594 	}
6595 	/*
6596 	 * Parse options on any incoming segment.
6597 	 */
6598 	tcp_dooptions(&to, (u_char *)(th + 1),
6599 	    (th->th_off << 2) - sizeof(struct tcphdr),
6600 	    (thflags & TH_SYN) ? TO_SYN : 0);
6601 
6602 	/*
6603 	 * If echoed timestamp is later than the current time, fall back to
6604 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
6605 	 * were used when this connection was established.
6606 	 */
6607 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
6608 		to.to_tsecr -= tp->ts_offset;
6609 		if (TSTMP_GT(to.to_tsecr, cts))
6610 			to.to_tsecr = 0;
6611 	}
6612 	/*
6613 	 * If its the first time in we need to take care of options and
6614 	 * verify we can do SACK for rack!
6615 	 */
6616 	if (rack->r_state == 0) {
6617 		/* Should be init'd by rack_init() */
6618 		KASSERT(rack->rc_inp != NULL,
6619 		    ("%s: rack->rc_inp unexpectedly NULL", __func__));
6620 		if (rack->rc_inp == NULL) {
6621 			rack->rc_inp = tp->t_inpcb;
6622 		}
6623 
6624 		/*
6625 		 * Process options only when we get SYN/ACK back. The SYN
6626 		 * case for incoming connections is handled in tcp_syncache.
6627 		 * According to RFC1323 the window field in a SYN (i.e., a
6628 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
6629 		 * this is traditional behavior, may need to be cleaned up.
6630 		 */
6631 		rack->r_cpu = inp_to_cpuid(tp->t_inpcb);
6632 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
6633 			if ((to.to_flags & TOF_SCALE) &&
6634 			    (tp->t_flags & TF_REQ_SCALE)) {
6635 				tp->t_flags |= TF_RCVD_SCALE;
6636 				tp->snd_scale = to.to_wscale;
6637 			}
6638 			/*
6639 			 * Initial send window.  It will be updated with the
6640 			 * next incoming segment to the scaled value.
6641 			 */
6642 			tp->snd_wnd = th->th_win;
6643 			if (to.to_flags & TOF_TS) {
6644 				tp->t_flags |= TF_RCVD_TSTMP;
6645 				tp->ts_recent = to.to_tsval;
6646 				tp->ts_recent_age = cts;
6647 			}
6648 			if (to.to_flags & TOF_MSS)
6649 				tcp_mss(tp, to.to_mss);
6650 			if ((tp->t_flags & TF_SACK_PERMIT) &&
6651 			    (to.to_flags & TOF_SACKPERM) == 0)
6652 				tp->t_flags &= ~TF_SACK_PERMIT;
6653 			if (IS_FASTOPEN(tp->t_flags)) {
6654 				if (to.to_flags & TOF_FASTOPEN) {
6655 					uint16_t mss;
6656 
6657 					if (to.to_flags & TOF_MSS)
6658 						mss = to.to_mss;
6659 					else
6660 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
6661 							mss = TCP6_MSS;
6662 						else
6663 							mss = TCP_MSS;
6664 					tcp_fastopen_update_cache(tp, mss,
6665 					    to.to_tfo_len, to.to_tfo_cookie);
6666 				} else
6667 					tcp_fastopen_disable_path(tp);
6668 			}
6669 		}
6670 		/*
6671 		 * At this point we are at the initial call. Here we decide
6672 		 * if we are doing RACK or not. We do this by seeing if
6673 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
6674 		 * we switch to the default code.
6675 		 */
6676 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
6677 			tcp_switch_back_to_default(tp);
6678 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
6679 			    tlen, iptos);
6680 			return;
6681 		}
6682 		/* Set the flag */
6683 		rack->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
6684 		tcp_set_hpts(tp->t_inpcb);
6685 		rack_stop_all_timers(tp);
6686 		sack_filter_clear(&rack->r_ctl.rack_sf, th->th_ack);
6687 	}
6688 	/*
6689 	 * This is the one exception case where we set the rack state
6690 	 * always. All other times (timers etc) we must have a rack-state
6691 	 * set (so we assure we have done the checks above for SACK).
6692 	 */
6693 	if (rack->r_state != tp->t_state)
6694 		rack_set_state(tp, rack);
6695 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&rack->r_ctl.rc_map)) != NULL)
6696 		kern_prefetch(rsm, &prev_state);
6697 	prev_state = rack->r_state;
6698 	rack->r_ctl.rc_tlp_send_cnt = 0;
6699 	rack_clear_rate_sample(rack);
6700 	retval = (*rack->r_substate) (m, th, so,
6701 	    tp, &to, drop_hdrlen,
6702 	    tlen, tiwin, thflags, nxt_pkt);
6703 #ifdef INVARIANTS
6704 	if ((retval == 0) &&
6705 	    (tp->t_inpcb == NULL)) {
6706 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
6707 		    retval, tp, prev_state);
6708 	}
6709 #endif
6710 	if (retval == 0) {
6711 		/*
6712 		 * If retval is 1 the tcb is unlocked and most likely the tp
6713 		 * is gone.
6714 		 */
6715 		INP_WLOCK_ASSERT(tp->t_inpcb);
6716 		tcp_rack_xmit_timer_commit(rack, tp);
6717 		if (((tp->snd_max - tp->snd_una) > tp->snd_wnd) &&
6718 		    (rack->rc_in_persist == 0)){
6719 			/*
6720 			 * The peer shrunk its window on us to the point
6721 			 * where we have sent too much. The only thing
6722 			 * we can do here is stop any timers and
6723 			 * enter persist. We most likely lost the last
6724 			 * bytes we sent but oh well, we will have to
6725 			 * retransmit them after the peer is caught up.
6726 			 */
6727 			if (rack->rc_inp->inp_in_hpts)
6728 				tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
6729 			rack_timer_cancel(tp, rack, cts, __LINE__);
6730 			rack_enter_persist(tp, rack, cts);
6731 			rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6732 			way_out = 3;
6733 			goto done_with_input;
6734 		}
6735 		if (nxt_pkt == 0) {
6736 			if (rack->r_wanted_output != 0) {
6737 				did_out = 1;
6738 				(void)tp->t_fb->tfb_tcp_output(tp);
6739 			}
6740 			rack_start_hpts_timer(rack, tp, cts, __LINE__, 0, 0, 0);
6741 		}
6742 		if (((rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
6743 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
6744 		     (tp->t_flags & TF_DELACK) ||
6745 		     ((tcp_always_keepalive || rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
6746 		      (tp->t_state <= TCPS_CLOSING)))) {
6747 			/* We could not send (probably in the hpts but stopped the timer earlier)? */
6748 			if ((tp->snd_max == tp->snd_una) &&
6749 			    ((tp->t_flags & TF_DELACK) == 0) &&
6750 			    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
6751 				/* keep alive not needed if we are hptsi output yet */
6752 				;
6753 			} else {
6754 				if (rack->rc_inp->inp_in_hpts)
6755 					tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
6756 				rack_start_hpts_timer(rack, tp, tcp_ts_getticks(), __LINE__, 0, 0, 0);
6757 			}
6758 			way_out = 1;
6759 		} else {
6760 			/* Do we have the correct timer running? */
6761 			rack_timer_audit(tp, rack, &so->so_snd);
6762 			way_out = 2;
6763 		}
6764 	done_with_input:
6765 		rack_log_doseg_done(rack, cts, nxt_pkt, did_out, way_out);
6766 		if (did_out)
6767 			rack->r_wanted_output = 0;
6768 #ifdef INVARIANTS
6769 		if (tp->t_inpcb == NULL) {
6770 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
6771 			      did_out,
6772 			      retval, tp, prev_state);
6773 		}
6774 #endif
6775 		INP_WUNLOCK(tp->t_inpcb);
6776 	}
6777 }
6778 
6779 void
6780 rack_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
6781     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
6782 {
6783 	struct timeval tv;
6784 #ifdef RSS
6785 	struct tcp_function_block *tfb;
6786 	struct tcp_rack *rack;
6787 	struct epoch_tracker et;
6788 
6789 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6790 	if (rack->r_state == 0) {
6791 		/*
6792 		 * Initial input (ACK to SYN-ACK etc)lets go ahead and get
6793 		 * it processed
6794 		 */
6795 		INP_INFO_RLOCK_ET(&V_tcbinfo, et);
6796 		tcp_get_usecs(&tv);
6797 		rack_hpts_do_segment(m, th, so, tp, drop_hdrlen,
6798 		    tlen, iptos, 0, &tv);
6799 		INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
6800 		return;
6801 	}
6802 	tcp_queue_to_input(tp, m, th, tlen, drop_hdrlen, iptos);
6803 	INP_WUNLOCK(tp->t_inpcb);
6804 #else
6805 	tcp_get_usecs(&tv);
6806 	rack_hpts_do_segment(m, th, so, tp, drop_hdrlen,
6807 	    tlen, iptos, 0, &tv);
6808 #endif
6809 }
6810 
6811 struct rack_sendmap *
6812 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tsused)
6813 {
6814 	struct rack_sendmap *rsm = NULL;
6815 	int32_t idx;
6816 	uint32_t srtt_cur, srtt = 0, thresh = 0, ts_low = 0;
6817 
6818 	/* Return the next guy to be re-transmitted */
6819 	if (TAILQ_EMPTY(&rack->r_ctl.rc_map)) {
6820 		return (NULL);
6821 	}
6822 	if (tp->t_flags & TF_SENTFIN) {
6823 		/* retran the end FIN? */
6824 		return (NULL);
6825 	}
6826 	/* ok lets look at this one */
6827 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6828 	if (rsm && ((rsm->r_flags & RACK_ACKED) == 0)) {
6829 		goto check_it;
6830 	}
6831 	rsm = rack_find_lowest_rsm(rack);
6832 	if (rsm == NULL) {
6833 		return (NULL);
6834 	}
6835 check_it:
6836 	srtt_cur = tp->t_srtt >> TCP_RTT_SHIFT;
6837 	srtt = TICKS_2_MSEC(srtt_cur);
6838 	if (rack->rc_rack_rtt && (srtt > rack->rc_rack_rtt))
6839 		srtt = rack->rc_rack_rtt;
6840 	if (rsm->r_flags & RACK_ACKED) {
6841 		return (NULL);
6842 	}
6843 	if ((rsm->r_flags & RACK_SACK_PASSED) == 0) {
6844 		/* Its not yet ready */
6845 		return (NULL);
6846 	}
6847 	idx = rsm->r_rtr_cnt - 1;
6848 	ts_low = rsm->r_tim_lastsent[idx];
6849 	thresh = rack_calc_thresh_rack(rack, srtt, tsused);
6850 	if (tsused <= ts_low) {
6851 		return (NULL);
6852 	}
6853 	if ((tsused - ts_low) >= thresh) {
6854 		return (rsm);
6855 	}
6856 	return (NULL);
6857 }
6858 
6859 static int
6860 rack_output(struct tcpcb *tp)
6861 {
6862 	struct socket *so;
6863 	uint32_t recwin, sendwin;
6864 	uint32_t sb_offset;
6865 	int32_t len, flags, error = 0;
6866 	struct mbuf *m;
6867 	struct mbuf *mb;
6868 	uint32_t if_hw_tsomaxsegcount = 0;
6869 	uint32_t if_hw_tsomaxsegsize;
6870 	long tot_len_this_send = 0;
6871 	struct ip *ip = NULL;
6872 #ifdef TCPDEBUG
6873 	struct ipovly *ipov = NULL;
6874 #endif
6875 	struct udphdr *udp = NULL;
6876 	struct tcp_rack *rack;
6877 	struct tcphdr *th;
6878 	uint8_t pass = 0;
6879 	uint8_t wanted_cookie = 0;
6880 	u_char opt[TCP_MAXOLEN];
6881 	unsigned ipoptlen, optlen, hdrlen, ulen=0;
6882 	uint32_t rack_seq;
6883 
6884 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
6885 	unsigned ipsec_optlen = 0;
6886 
6887 #endif
6888 	int32_t idle, sendalot;
6889 	int32_t sub_from_prr = 0;
6890 	volatile int32_t sack_rxmit;
6891 	struct rack_sendmap *rsm = NULL;
6892 	int32_t tso, mtu, would_have_fin = 0;
6893 	struct tcpopt to;
6894 	int32_t slot = 0;
6895 	uint32_t cts;
6896 	uint8_t hpts_calling, doing_tlp = 0;
6897 	int32_t do_a_prefetch;
6898 	int32_t prefetch_rsm = 0;
6899 	int32_t prefetch_so_done = 0;
6900 	struct tcp_log_buffer *lgb = NULL;
6901 	struct inpcb *inp;
6902 	struct sockbuf *sb;
6903 #ifdef INET6
6904 	struct ip6_hdr *ip6 = NULL;
6905 	int32_t isipv6;
6906 #endif
6907 	/* setup and take the cache hits here */
6908 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6909 	inp = rack->rc_inp;
6910 	so = inp->inp_socket;
6911 	sb = &so->so_snd;
6912 	kern_prefetch(sb, &do_a_prefetch);
6913 	do_a_prefetch = 1;
6914 
6915 	INP_WLOCK_ASSERT(inp);
6916 #ifdef TCP_OFFLOAD
6917 	if (tp->t_flags & TF_TOE)
6918 		return (tcp_offload_output(tp));
6919 #endif
6920 #ifdef INET6
6921 	if (rack->r_state) {
6922 		/* Use the cache line loaded if possible */
6923 		isipv6 = rack->r_is_v6;
6924 	} else {
6925 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
6926 	}
6927 #endif
6928 	cts = tcp_ts_getticks();
6929 	if (((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
6930 	    inp->inp_in_hpts) {
6931 		/*
6932 		 * We are on the hpts for some timer but not hptsi output.
6933 		 * Remove from the hpts unconditionally.
6934 		 */
6935 		rack_timer_cancel(tp, rack, cts, __LINE__);
6936 	}
6937 	/* Mark that we have called rack_output(). */
6938 	if ((rack->r_timer_override) ||
6939 	    (tp->t_flags & TF_FORCEDATA) ||
6940 	    (tp->t_state < TCPS_ESTABLISHED)) {
6941 		if (tp->t_inpcb->inp_in_hpts)
6942 			tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_OUTPUT);
6943 	} else if (tp->t_inpcb->inp_in_hpts) {
6944 		/*
6945 		 * On the hpts you can't pass even if ACKNOW is on, we will
6946 		 * when the hpts fires.
6947 		 */
6948 		counter_u64_add(rack_out_size[TCP_MSS_ACCT_INPACE], 1);
6949 		return (0);
6950 	}
6951 	hpts_calling = inp->inp_hpts_calls;
6952 	inp->inp_hpts_calls = 0;
6953 	if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
6954 		if (rack_process_timers(tp, rack, cts, hpts_calling)) {
6955 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_ATIMER], 1);
6956 			return (0);
6957 		}
6958 	}
6959 	rack->r_wanted_output = 0;
6960 	rack->r_timer_override = 0;
6961 	/*
6962 	 * For TFO connections in SYN_SENT or SYN_RECEIVED,
6963 	 * only allow the initial SYN or SYN|ACK and those sent
6964 	 * by the retransmit timer.
6965 	 */
6966 	if (IS_FASTOPEN(tp->t_flags) &&
6967 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
6968 	     (tp->t_state == TCPS_SYN_SENT)) &&
6969 	    SEQ_GT(tp->snd_max, tp->snd_una) && /* initial SYN or SYN|ACK sent */
6970 	    (tp->t_rxtshift == 0))              /* not a retransmit */
6971 		return (0);
6972 	/*
6973 	 * Determine length of data that should be transmitted, and flags
6974 	 * that will be used. If there is some data or critical controls
6975 	 * (SYN, RST) to send, then transmit; otherwise, investigate
6976 	 * further.
6977 	 */
6978 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
6979 #ifdef NETFLIX_CWV
6980 	if (tp->cwv_enabled) {
6981 		if ((tp->cwv_cwnd_valid == 0) &&
6982 		    TCPS_HAVEESTABLISHED(tp->t_state) &&
6983 		    (tp->snd_cwnd > tp->snd_cwv.init_cwnd))
6984 			tcp_newcwv_nvp_closedown(tp);
6985 	} else
6986 #endif
6987 	if (tp->t_idle_reduce) {
6988 		if (idle && ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
6989 			rack_cc_after_idle(tp,
6990 		            (rack->r_idle_reduce_largest ? 1 :0));
6991 	}
6992 	tp->t_flags &= ~TF_LASTIDLE;
6993 	if (idle) {
6994 		if (tp->t_flags & TF_MORETOCOME) {
6995 			tp->t_flags |= TF_LASTIDLE;
6996 			idle = 0;
6997 		}
6998 	}
6999 again:
7000 	/*
7001 	 * If we've recently taken a timeout, snd_max will be greater than
7002 	 * snd_nxt.  There may be SACK information that allows us to avoid
7003 	 * resending already delivered data.  Adjust snd_nxt accordingly.
7004 	 */
7005 	sendalot = 0;
7006 	cts = tcp_ts_getticks();
7007 	tso = 0;
7008 	mtu = 0;
7009 	sb_offset = tp->snd_max - tp->snd_una;
7010 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
7011 
7012 	flags = tcp_outflags[tp->t_state];
7013 	/*
7014 	 * Send any SACK-generated retransmissions.  If we're explicitly
7015 	 * trying to send out new data (when sendalot is 1), bypass this
7016 	 * function. If we retransmit in fast recovery mode, decrement
7017 	 * snd_cwnd, since we're replacing a (future) new transmission with
7018 	 * a retransmission now, and we previously incremented snd_cwnd in
7019 	 * tcp_input().
7020 	 */
7021 	/*
7022 	 * Still in sack recovery , reset rxmit flag to zero.
7023 	 */
7024 	while (rack->rc_free_cnt < rack_free_cache) {
7025 		rsm = rack_alloc(rack);
7026 		if (rsm == NULL) {
7027 			if (inp->inp_hpts_calls)
7028 				/* Retry in a ms */
7029 				slot = 1;
7030 			goto just_return_nolock;
7031 		}
7032 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_next);
7033 		rack->rc_free_cnt++;
7034 		rsm = NULL;
7035 	}
7036 	if (inp->inp_hpts_calls)
7037 		inp->inp_hpts_calls = 0;
7038 	sack_rxmit = 0;
7039 	len = 0;
7040 	rsm = NULL;
7041 	if (flags & TH_RST) {
7042 		SOCKBUF_LOCK(sb);
7043 		goto send;
7044 	}
7045 	if (rack->r_ctl.rc_tlpsend) {
7046 		/* Tail loss probe */
7047 		long cwin;
7048 		long tlen;
7049 
7050 		doing_tlp = 1;
7051 		rsm = rack->r_ctl.rc_tlpsend;
7052 		rack->r_ctl.rc_tlpsend = NULL;
7053 		sack_rxmit = 1;
7054 		tlen = rsm->r_end - rsm->r_start;
7055 		if (tlen > tp->t_maxseg)
7056 			tlen = tp->t_maxseg;
7057 		KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
7058 		    ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
7059 		    __func__, __LINE__,
7060 		    rsm->r_start, tp->snd_una, tp, rack, rsm));
7061 		sb_offset = rsm->r_start - tp->snd_una;
7062 		cwin = min(tp->snd_wnd, tlen);
7063 		len = cwin;
7064 	} else if (rack->r_ctl.rc_resend) {
7065 		/* Retransmit timer */
7066 		rsm = rack->r_ctl.rc_resend;
7067 		rack->r_ctl.rc_resend = NULL;
7068 		len = rsm->r_end - rsm->r_start;
7069 		sack_rxmit = 1;
7070 		sendalot = 0;
7071 		KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
7072 		    ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
7073 		    __func__, __LINE__,
7074 		    rsm->r_start, tp->snd_una, tp, rack, rsm));
7075 		sb_offset = rsm->r_start - tp->snd_una;
7076 		if (len >= tp->t_maxseg) {
7077 			len = tp->t_maxseg;
7078 		}
7079 	} else if ((rack->rc_in_persist == 0) &&
7080 	    ((rsm = tcp_rack_output(tp, rack, cts)) != NULL)) {
7081 		long tlen;
7082 
7083 		if ((!IN_RECOVERY(tp->t_flags)) &&
7084 		    ((tp->t_flags & (TF_WASFRECOVERY | TF_WASCRECOVERY)) == 0)) {
7085 			/* Enter recovery if not induced by a time-out */
7086 			rack->r_ctl.rc_rsm_start = rsm->r_start;
7087 			rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
7088 			rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
7089 			rack_cong_signal(tp, NULL, CC_NDUPACK);
7090 			/*
7091 			 * When we enter recovery we need to assure we send
7092 			 * one packet.
7093 			 */
7094 			rack->r_ctl.rc_prr_sndcnt = tp->t_maxseg;
7095 		}
7096 #ifdef INVARIANTS
7097 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
7098 			panic("Huh, tp:%p rack:%p rsm:%p start:%u < snd_una:%u\n",
7099 			    tp, rack, rsm, rsm->r_start, tp->snd_una);
7100 		}
7101 #endif
7102 		tlen = rsm->r_end - rsm->r_start;
7103 		KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
7104 		    ("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
7105 		    __func__, __LINE__,
7106 		    rsm->r_start, tp->snd_una, tp, rack, rsm));
7107 		sb_offset = rsm->r_start - tp->snd_una;
7108 		if (tlen > rack->r_ctl.rc_prr_sndcnt) {
7109 			len = rack->r_ctl.rc_prr_sndcnt;
7110 		} else {
7111 			len = tlen;
7112 		}
7113 		if (len >= tp->t_maxseg) {
7114 			sendalot = 1;
7115 			len = tp->t_maxseg;
7116 		} else {
7117 			sendalot = 0;
7118 			if ((rack->rc_timer_up == 0) &&
7119 			    (len < tlen)) {
7120 				/*
7121 				 * If its not a timer don't send a partial
7122 				 * segment.
7123 				 */
7124 				len = 0;
7125 				goto just_return_nolock;
7126 			}
7127 		}
7128 		if (len > 0) {
7129 			sub_from_prr = 1;
7130 			sack_rxmit = 1;
7131 			TCPSTAT_INC(tcps_sack_rexmits);
7132 			TCPSTAT_ADD(tcps_sack_rexmit_bytes,
7133 			    min(len, tp->t_maxseg));
7134 			counter_u64_add(rack_rtm_prr_retran, 1);
7135 		}
7136 	}
7137 	if (rsm && (rsm->r_flags & RACK_HAS_FIN)) {
7138 		/* we are retransmitting the fin */
7139 		len--;
7140 		if (len) {
7141 			/*
7142 			 * When retransmitting data do *not* include the
7143 			 * FIN. This could happen from a TLP probe.
7144 			 */
7145 			flags &= ~TH_FIN;
7146 		}
7147 	}
7148 #ifdef INVARIANTS
7149 	/* For debugging */
7150 	rack->r_ctl.rc_rsm_at_retran = rsm;
7151 #endif
7152 	/*
7153 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
7154 	 * state flags.
7155 	 */
7156 	if (tp->t_flags & TF_NEEDFIN)
7157 		flags |= TH_FIN;
7158 	if (tp->t_flags & TF_NEEDSYN)
7159 		flags |= TH_SYN;
7160 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
7161 		void *end_rsm;
7162 		end_rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
7163 		if (end_rsm)
7164 			kern_prefetch(end_rsm, &prefetch_rsm);
7165 		prefetch_rsm = 1;
7166 	}
7167 	SOCKBUF_LOCK(sb);
7168 	/*
7169 	 * If in persist timeout with window of 0, send 1 byte. Otherwise,
7170 	 * if window is small but nonzero and time TF_SENTFIN expired, we
7171 	 * will send what we can and go to transmit state.
7172 	 */
7173 	if (tp->t_flags & TF_FORCEDATA) {
7174 		if (sendwin == 0) {
7175 			/*
7176 			 * If we still have some data to send, then clear
7177 			 * the FIN bit.  Usually this would happen below
7178 			 * when it realizes that we aren't sending all the
7179 			 * data.  However, if we have exactly 1 byte of
7180 			 * unsent data, then it won't clear the FIN bit
7181 			 * below, and if we are in persist state, we wind up
7182 			 * sending the packet without recording that we sent
7183 			 * the FIN bit.
7184 			 *
7185 			 * We can't just blindly clear the FIN bit, because
7186 			 * if we don't have any more data to send then the
7187 			 * probe will be the FIN itself.
7188 			 */
7189 			if (sb_offset < sbused(sb))
7190 				flags &= ~TH_FIN;
7191 			sendwin = 1;
7192 		} else {
7193 			if (rack->rc_in_persist)
7194 				rack_exit_persist(tp, rack);
7195 			/*
7196 			 * If we are dropping persist mode then we need to
7197 			 * correct snd_nxt/snd_max and off.
7198 			 */
7199 			tp->snd_nxt = tp->snd_max;
7200 			sb_offset = tp->snd_nxt - tp->snd_una;
7201 		}
7202 	}
7203 	/*
7204 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
7205 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
7206 	 * negative length.  This can also occur when TCP opens up its
7207 	 * congestion window while receiving additional duplicate acks after
7208 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
7209 	 * the fast-retransmit.
7210 	 *
7211 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
7212 	 * set to snd_una, the sb_offset will be 0, and the length may wind
7213 	 * up 0.
7214 	 *
7215 	 * If sack_rxmit is true we are retransmitting from the scoreboard
7216 	 * in which case len is already set.
7217 	 */
7218 	if (sack_rxmit == 0) {
7219 		uint32_t avail;
7220 
7221 		avail = sbavail(sb);
7222 		if (SEQ_GT(tp->snd_nxt, tp->snd_una) && avail)
7223 			sb_offset = tp->snd_nxt - tp->snd_una;
7224 		else
7225 			sb_offset = 0;
7226 		if (IN_RECOVERY(tp->t_flags) == 0) {
7227 			if (rack->r_ctl.rc_tlp_new_data) {
7228 				/* TLP is forcing out new data */
7229 				if (rack->r_ctl.rc_tlp_new_data > (uint32_t) (avail - sb_offset)) {
7230 					rack->r_ctl.rc_tlp_new_data = (uint32_t) (avail - sb_offset);
7231 				}
7232 				if (rack->r_ctl.rc_tlp_new_data > tp->snd_wnd)
7233 					len = tp->snd_wnd;
7234 				else
7235 					len = rack->r_ctl.rc_tlp_new_data;
7236 				rack->r_ctl.rc_tlp_new_data = 0;
7237 				doing_tlp = 1;
7238 			} else {
7239 				if (sendwin > avail) {
7240 					/* use the available */
7241 					if (avail > sb_offset) {
7242 						len = (int32_t)(avail - sb_offset);
7243 					} else {
7244 						len = 0;
7245 					}
7246 				} else {
7247 					if (sendwin > sb_offset) {
7248 						len = (int32_t)(sendwin - sb_offset);
7249 					} else {
7250 						len = 0;
7251 					}
7252 				}
7253 			}
7254 		} else {
7255 			uint32_t outstanding;
7256 
7257 			/*
7258 			 * We are inside of a SACK recovery episode and are
7259 			 * sending new data, having retransmitted all the
7260 			 * data possible so far in the scoreboard.
7261 			 */
7262 			outstanding = tp->snd_max - tp->snd_una;
7263 			if ((rack->r_ctl.rc_prr_sndcnt + outstanding) > tp->snd_wnd)
7264 				len = 0;
7265 			else if (avail > sb_offset)
7266 				len = avail - sb_offset;
7267 			else
7268 				len = 0;
7269 			if (len > 0) {
7270 				if (len > rack->r_ctl.rc_prr_sndcnt)
7271 					len = rack->r_ctl.rc_prr_sndcnt;
7272 
7273 				if (len > 0) {
7274 					sub_from_prr = 1;
7275 					counter_u64_add(rack_rtm_prr_newdata, 1);
7276 				}
7277 			}
7278 			if (len > tp->t_maxseg) {
7279 				/*
7280 				 * We should never send more than a MSS when
7281 				 * retransmitting or sending new data in prr
7282 				 * mode unless the override flag is on. Most
7283 				 * likely the PRR algorithm is not going to
7284 				 * let us send a lot as well :-)
7285 				 */
7286 				if (rack->r_ctl.rc_prr_sendalot == 0)
7287 					len = tp->t_maxseg;
7288 			} else if (len < tp->t_maxseg) {
7289 				/*
7290 				 * Do we send any? The idea here is if the
7291 				 * send empty's the socket buffer we want to
7292 				 * do it. However if not then lets just wait
7293 				 * for our prr_sndcnt to get bigger.
7294 				 */
7295 				long leftinsb;
7296 
7297 				leftinsb = sbavail(sb) - sb_offset;
7298 				if (leftinsb > len) {
7299 					/* This send does not empty the sb */
7300 					len = 0;
7301 				}
7302 			}
7303 		}
7304 	}
7305 	if (prefetch_so_done == 0) {
7306 		kern_prefetch(so, &prefetch_so_done);
7307 		prefetch_so_done = 1;
7308 	}
7309 	/*
7310 	 * Lop off SYN bit if it has already been sent.  However, if this is
7311 	 * SYN-SENT state and if segment contains data and if we don't know
7312 	 * that foreign host supports TAO, suppress sending segment.
7313 	 */
7314 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una) &&
7315 	    ((sack_rxmit == 0) && (tp->t_rxtshift == 0))) {
7316 		if (tp->t_state != TCPS_SYN_RECEIVED)
7317 			flags &= ~TH_SYN;
7318 		/*
7319 		 * When sending additional segments following a TFO SYN|ACK,
7320 		 * do not include the SYN bit.
7321 		 */
7322 		if (IS_FASTOPEN(tp->t_flags) &&
7323 		    (tp->t_state == TCPS_SYN_RECEIVED))
7324 			flags &= ~TH_SYN;
7325 		sb_offset--, len++;
7326 	}
7327 	/*
7328 	 * Be careful not to send data and/or FIN on SYN segments. This
7329 	 * measure is needed to prevent interoperability problems with not
7330 	 * fully conformant TCP implementations.
7331 	 */
7332 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
7333 		len = 0;
7334 		flags &= ~TH_FIN;
7335 	}
7336 	/*
7337 	 * On TFO sockets, ensure no data is sent in the following cases:
7338 	 *
7339 	 *  - When retransmitting SYN|ACK on a passively-created socket
7340 	 *
7341 	 *  - When retransmitting SYN on an actively created socket
7342 	 *
7343 	 *  - When sending a zero-length cookie (cookie request) on an
7344 	 *    actively created socket
7345 	 *
7346 	 *  - When the socket is in the CLOSED state (RST is being sent)
7347 	 */
7348 	if (IS_FASTOPEN(tp->t_flags) &&
7349 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
7350 	     ((tp->t_state == TCPS_SYN_SENT) &&
7351 	      (tp->t_tfo_client_cookie_len == 0)) ||
7352 	     (flags & TH_RST))) {
7353 		sack_rxmit = 0;
7354 		len = 0;
7355 	}
7356 	/* Without fast-open there should never be data sent on a SYN */
7357 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
7358 		len = 0;
7359 	if (len <= 0) {
7360 		/*
7361 		 * If FIN has been sent but not acked, but we haven't been
7362 		 * called to retransmit, len will be < 0.  Otherwise, window
7363 		 * shrank after we sent into it.  If window shrank to 0,
7364 		 * cancel pending retransmit, pull snd_nxt back to (closed)
7365 		 * window, and set the persist timer if it isn't already
7366 		 * going.  If the window didn't close completely, just wait
7367 		 * for an ACK.
7368 		 *
7369 		 * We also do a general check here to ensure that we will
7370 		 * set the persist timer when we have data to send, but a
7371 		 * 0-byte window. This makes sure the persist timer is set
7372 		 * even if the packet hits one of the "goto send" lines
7373 		 * below.
7374 		 */
7375 		len = 0;
7376 		if ((tp->snd_wnd == 0) &&
7377 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
7378 		    (sb_offset < (int)sbavail(sb))) {
7379 			tp->snd_nxt = tp->snd_una;
7380 			rack_enter_persist(tp, rack, cts);
7381 		}
7382 	}
7383 	/* len will be >= 0 after this point. */
7384 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
7385 	tcp_sndbuf_autoscale(tp, so, sendwin);
7386 	/*
7387 	 * Decide if we can use TCP Segmentation Offloading (if supported by
7388 	 * hardware).
7389 	 *
7390 	 * TSO may only be used if we are in a pure bulk sending state.  The
7391 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
7392 	 * options prevent using TSO.  With TSO the TCP header is the same
7393 	 * (except for the sequence number) for all generated packets.  This
7394 	 * makes it impossible to transmit any options which vary per
7395 	 * generated segment or packet.
7396 	 *
7397 	 * IPv4 handling has a clear separation of ip options and ip header
7398 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
7399 	 * the right thing below to provide length of just ip options and thus
7400 	 * checking for ipoptlen is enough to decide if ip options are present.
7401 	 */
7402 
7403 #ifdef INET6
7404 	if (isipv6)
7405 		ipoptlen = ip6_optlen(tp->t_inpcb);
7406 	else
7407 #endif
7408 		if (tp->t_inpcb->inp_options)
7409 			ipoptlen = tp->t_inpcb->inp_options->m_len -
7410 			    offsetof(struct ipoption, ipopt_list);
7411 		else
7412 			ipoptlen = 0;
7413 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
7414 	/*
7415 	 * Pre-calculate here as we save another lookup into the darknesses
7416 	 * of IPsec that way and can actually decide if TSO is ok.
7417 	 */
7418 #ifdef INET6
7419 	if (isipv6 && IPSEC_ENABLED(ipv6))
7420 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, tp->t_inpcb);
7421 #ifdef INET
7422 	else
7423 #endif
7424 #endif				/* INET6 */
7425 #ifdef INET
7426 	if (IPSEC_ENABLED(ipv4))
7427 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, tp->t_inpcb);
7428 #endif				/* INET */
7429 #endif
7430 
7431 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
7432 	ipoptlen += ipsec_optlen;
7433 #endif
7434 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > tp->t_maxseg &&
7435 	    (tp->t_port == 0) &&
7436 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
7437 	    tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
7438 	    ipoptlen == 0)
7439 		tso = 1;
7440 	{
7441 		uint32_t outstanding;
7442 
7443 		outstanding = tp->snd_max - tp->snd_una;
7444 		if (tp->t_flags & TF_SENTFIN) {
7445 			/*
7446 			 * If we sent a fin, snd_max is 1 higher than
7447 			 * snd_una
7448 			 */
7449 			outstanding--;
7450 		}
7451 		if (outstanding > 0) {
7452 			/*
7453 			 * This is sub-optimal. We only send a stand alone
7454 			 * FIN on its own segment.
7455 			 */
7456 			if (flags & TH_FIN) {
7457 				flags &= ~TH_FIN;
7458 				would_have_fin = 1;
7459 			}
7460 		} else if (sack_rxmit) {
7461 			if ((rsm->r_flags & RACK_HAS_FIN) == 0)
7462 				flags &= ~TH_FIN;
7463 		} else {
7464 			if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
7465 			    sbused(sb)))
7466 				flags &= ~TH_FIN;
7467 		}
7468 	}
7469 	recwin = sbspace(&so->so_rcv);
7470 
7471 	/*
7472 	 * Sender silly window avoidance.   We transmit under the following
7473 	 * conditions when len is non-zero:
7474 	 *
7475 	 * - We have a full segment (or more with TSO) - This is the last
7476 	 * buffer in a write()/send() and we are either idle or running
7477 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
7478 	 * then 1/2 the maximum send window's worth of data (receiver may be
7479 	 * limited the window size) - we need to retransmit
7480 	 */
7481 	if (len) {
7482 		if (len >= tp->t_maxseg) {
7483 			pass = 1;
7484 			goto send;
7485 		}
7486 		/*
7487 		 * NOTE! on localhost connections an 'ack' from the remote
7488 		 * end may occur synchronously with the output and cause us
7489 		 * to flush a buffer queued with moretocome.  XXX
7490 		 *
7491 		 */
7492 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
7493 		    (idle || (tp->t_flags & TF_NODELAY)) &&
7494 		    ((uint32_t)len + (uint32_t)sb_offset >= sbavail(&so->so_snd)) &&
7495 		    (tp->t_flags & TF_NOPUSH) == 0) {
7496 			pass = 2;
7497 			goto send;
7498 		}
7499 		if (tp->t_flags & TF_FORCEDATA) {	/* typ. timeout case */
7500 			pass = 3;
7501 			goto send;
7502 		}
7503 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
7504 			goto send;
7505 		}
7506 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
7507 			pass = 4;
7508 			goto send;
7509 		}
7510 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {	/* retransmit case */
7511 			pass = 5;
7512 			goto send;
7513 		}
7514 		if (sack_rxmit) {
7515 			pass = 6;
7516 			goto send;
7517 		}
7518 	}
7519 	/*
7520 	 * Sending of standalone window updates.
7521 	 *
7522 	 * Window updates are important when we close our window due to a
7523 	 * full socket buffer and are opening it again after the application
7524 	 * reads data from it.  Once the window has opened again and the
7525 	 * remote end starts to send again the ACK clock takes over and
7526 	 * provides the most current window information.
7527 	 *
7528 	 * We must avoid the silly window syndrome whereas every read from
7529 	 * the receive buffer, no matter how small, causes a window update
7530 	 * to be sent.  We also should avoid sending a flurry of window
7531 	 * updates when the socket buffer had queued a lot of data and the
7532 	 * application is doing small reads.
7533 	 *
7534 	 * Prevent a flurry of pointless window updates by only sending an
7535 	 * update when we can increase the advertized window by more than
7536 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
7537 	 * full or is very small be more aggressive and send an update
7538 	 * whenever we can increase by two mss sized segments. In all other
7539 	 * situations the ACK's to new incoming data will carry further
7540 	 * window increases.
7541 	 *
7542 	 * Don't send an independent window update if a delayed ACK is
7543 	 * pending (it will get piggy-backed on it) or the remote side
7544 	 * already has done a half-close and won't send more data.  Skip
7545 	 * this if the connection is in T/TCP half-open state.
7546 	 */
7547 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
7548 	    !(tp->t_flags & TF_DELACK) &&
7549 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
7550 		/*
7551 		 * "adv" is the amount we could increase the window, taking
7552 		 * into account that we are limited by TCP_MAXWIN <<
7553 		 * tp->rcv_scale.
7554 		 */
7555 		int32_t adv;
7556 		int oldwin;
7557 
7558 		adv = min(recwin, (long)TCP_MAXWIN << tp->rcv_scale);
7559 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
7560 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
7561 			adv -= oldwin;
7562 		} else
7563 			oldwin = 0;
7564 
7565 		/*
7566 		 * If the new window size ends up being the same as the old
7567 		 * size when it is scaled, then don't force a window update.
7568 		 */
7569 		if (oldwin >> tp->rcv_scale == (adv + oldwin) >> tp->rcv_scale)
7570 			goto dontupdate;
7571 
7572 		if (adv >= (int32_t)(2 * tp->t_maxseg) &&
7573 		    (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
7574 		    recwin <= (int32_t)(so->so_rcv.sb_hiwat / 8) ||
7575 		    so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg)) {
7576 			pass = 7;
7577 			goto send;
7578 		}
7579 		if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
7580 			goto send;
7581 	}
7582 dontupdate:
7583 
7584 	/*
7585 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
7586 	 * is also a catch-all for the retransmit timer timeout case.
7587 	 */
7588 	if (tp->t_flags & TF_ACKNOW) {
7589 		pass = 8;
7590 		goto send;
7591 	}
7592 	if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
7593 		pass = 9;
7594 		goto send;
7595 	}
7596 	if (SEQ_GT(tp->snd_up, tp->snd_una)) {
7597 		pass = 10;
7598 		goto send;
7599 	}
7600 	/*
7601 	 * If our state indicates that FIN should be sent and we have not
7602 	 * yet done so, then we need to send.
7603 	 */
7604 	if ((flags & TH_FIN) &&
7605 	    (tp->snd_nxt == tp->snd_una)) {
7606 		pass = 11;
7607 		goto send;
7608 	}
7609 	/*
7610 	 * No reason to send a segment, just return.
7611 	 */
7612 just_return:
7613 	SOCKBUF_UNLOCK(sb);
7614 just_return_nolock:
7615 	if (tot_len_this_send == 0)
7616 		counter_u64_add(rack_out_size[TCP_MSS_ACCT_JUSTRET], 1);
7617 	rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, tot_len_this_send, 1);
7618 	rack_log_type_just_return(rack, cts, tot_len_this_send, slot, hpts_calling);
7619 	tp->t_flags &= ~TF_FORCEDATA;
7620 	return (0);
7621 
7622 send:
7623 	if (doing_tlp == 0) {
7624 		/*
7625 		 * Data not a TLP, and its not the rxt firing. If it is the
7626 		 * rxt firing, we want to leave the tlp_in_progress flag on
7627 		 * so we don't send another TLP. It has to be a rack timer
7628 		 * or normal send (response to acked data) to clear the tlp
7629 		 * in progress flag.
7630 		 */
7631 		rack->rc_tlp_in_progress = 0;
7632 	}
7633 	SOCKBUF_LOCK_ASSERT(sb);
7634 	if (len > 0) {
7635 		if (len >= tp->t_maxseg)
7636 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
7637 		else
7638 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
7639 	}
7640 	/*
7641 	 * Before ESTABLISHED, force sending of initial options unless TCP
7642 	 * set not to do any options. NOTE: we assume that the IP/TCP header
7643 	 * plus TCP options always fit in a single mbuf, leaving room for a
7644 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
7645 	 * + optlen <= MCLBYTES
7646 	 */
7647 	optlen = 0;
7648 #ifdef INET6
7649 	if (isipv6)
7650 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
7651 	else
7652 #endif
7653 		hdrlen = sizeof(struct tcpiphdr);
7654 
7655 	/*
7656 	 * Compute options for segment. We only have to care about SYN and
7657 	 * established connection segments.  Options for SYN-ACK segments
7658 	 * are handled in TCP syncache.
7659 	 */
7660 	to.to_flags = 0;
7661 	if ((tp->t_flags & TF_NOOPT) == 0) {
7662 		/* Maximum segment size. */
7663 		if (flags & TH_SYN) {
7664 			tp->snd_nxt = tp->iss;
7665 			to.to_mss = tcp_mssopt(&inp->inp_inc);
7666 #ifdef NETFLIX_TCPOUDP
7667 			if (tp->t_port)
7668 				to.to_mss -= V_tcp_udp_tunneling_overhead;
7669 #endif
7670 			to.to_flags |= TOF_MSS;
7671 
7672 			/*
7673 			 * On SYN or SYN|ACK transmits on TFO connections,
7674 			 * only include the TFO option if it is not a
7675 			 * retransmit, as the presence of the TFO option may
7676 			 * have caused the original SYN or SYN|ACK to have
7677 			 * been dropped by a middlebox.
7678 			 */
7679 			if (IS_FASTOPEN(tp->t_flags) &&
7680 			    (tp->t_rxtshift == 0)) {
7681 				if (tp->t_state == TCPS_SYN_RECEIVED) {
7682 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
7683 					to.to_tfo_cookie =
7684 					    (u_int8_t *)&tp->t_tfo_cookie.server;
7685 					to.to_flags |= TOF_FASTOPEN;
7686 					wanted_cookie = 1;
7687 				} else if (tp->t_state == TCPS_SYN_SENT) {
7688 					to.to_tfo_len =
7689 					    tp->t_tfo_client_cookie_len;
7690 					to.to_tfo_cookie =
7691 					    tp->t_tfo_cookie.client;
7692 					to.to_flags |= TOF_FASTOPEN;
7693 					wanted_cookie = 1;
7694 					/*
7695 					 * If we wind up having more data to
7696 					 * send with the SYN than can fit in
7697 					 * one segment, don't send any more
7698 					 * until the SYN|ACK comes back from
7699 					 * the other end.
7700 					 */
7701 					sendalot = 0;
7702 				}
7703 			}
7704 		}
7705 		/* Window scaling. */
7706 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
7707 			to.to_wscale = tp->request_r_scale;
7708 			to.to_flags |= TOF_SCALE;
7709 		}
7710 		/* Timestamps. */
7711 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
7712 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
7713 			to.to_tsval = cts + tp->ts_offset;
7714 			to.to_tsecr = tp->ts_recent;
7715 			to.to_flags |= TOF_TS;
7716 		}
7717 		/* Set receive buffer autosizing timestamp. */
7718 		if (tp->rfbuf_ts == 0 &&
7719 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
7720 			tp->rfbuf_ts = tcp_ts_getticks();
7721 		/* Selective ACK's. */
7722 		if (flags & TH_SYN)
7723 			to.to_flags |= TOF_SACKPERM;
7724 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
7725 		    tp->rcv_numsacks > 0) {
7726 			to.to_flags |= TOF_SACK;
7727 			to.to_nsacks = tp->rcv_numsacks;
7728 			to.to_sacks = (u_char *)tp->sackblks;
7729 		}
7730 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
7731 		/* TCP-MD5 (RFC2385). */
7732 		if (tp->t_flags & TF_SIGNATURE)
7733 			to.to_flags |= TOF_SIGNATURE;
7734 #endif				/* TCP_SIGNATURE */
7735 
7736 		/* Processing the options. */
7737 		hdrlen += optlen = tcp_addoptions(&to, opt);
7738 		/*
7739 		 * If we wanted a TFO option to be added, but it was unable
7740 		 * to fit, ensure no data is sent.
7741 		 */
7742 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
7743 		    !(to.to_flags & TOF_FASTOPEN))
7744 			len = 0;
7745 	}
7746 #ifdef NETFLIX_TCPOUDP
7747 	if (tp->t_port) {
7748 		if (V_tcp_udp_tunneling_port == 0) {
7749 			/* The port was removed?? */
7750 			SOCKBUF_UNLOCK(&so->so_snd);
7751 			return (EHOSTUNREACH);
7752 		}
7753 		hdrlen += sizeof(struct udphdr);
7754 	}
7755 #endif
7756 	ipoptlen = 0;
7757 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
7758 	ipoptlen += ipsec_optlen;
7759 #endif
7760 
7761 	/*
7762 	 * Adjust data length if insertion of options will bump the packet
7763 	 * length beyond the t_maxseg length. Clear the FIN bit because we
7764 	 * cut off the tail of the segment.
7765 	 */
7766 	if (len + optlen + ipoptlen > tp->t_maxseg) {
7767 		if (flags & TH_FIN) {
7768 			would_have_fin = 1;
7769 			flags &= ~TH_FIN;
7770 		}
7771 		if (tso) {
7772 			uint32_t if_hw_tsomax;
7773 			uint32_t moff;
7774 			int32_t max_len;
7775 
7776 			/* extract TSO information */
7777 			if_hw_tsomax = tp->t_tsomax;
7778 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
7779 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
7780 			KASSERT(ipoptlen == 0,
7781 			    ("%s: TSO can't do IP options", __func__));
7782 
7783 			/*
7784 			 * Check if we should limit by maximum payload
7785 			 * length:
7786 			 */
7787 			if (if_hw_tsomax != 0) {
7788 				/* compute maximum TSO length */
7789 				max_len = (if_hw_tsomax - hdrlen -
7790 				    max_linkhdr);
7791 				if (max_len <= 0) {
7792 					len = 0;
7793 				} else if (len > max_len) {
7794 					sendalot = 1;
7795 					len = max_len;
7796 				}
7797 			}
7798 			/*
7799 			 * Prevent the last segment from being fractional
7800 			 * unless the send sockbuf can be emptied:
7801 			 */
7802 			max_len = (tp->t_maxseg - optlen);
7803 			if ((sb_offset + len) < sbavail(sb)) {
7804 				moff = len % (u_int)max_len;
7805 				if (moff != 0) {
7806 					len -= moff;
7807 					sendalot = 1;
7808 				}
7809 			}
7810 			/*
7811 			 * In case there are too many small fragments don't
7812 			 * use TSO:
7813 			 */
7814 			if (len <= max_len) {
7815 				len = max_len;
7816 				sendalot = 1;
7817 				tso = 0;
7818 			}
7819 			/*
7820 			 * Send the FIN in a separate segment after the bulk
7821 			 * sending is done. We don't trust the TSO
7822 			 * implementations to clear the FIN flag on all but
7823 			 * the last segment.
7824 			 */
7825 			if (tp->t_flags & TF_NEEDFIN)
7826 				sendalot = 1;
7827 
7828 		} else {
7829 			len = tp->t_maxseg - optlen - ipoptlen;
7830 			sendalot = 1;
7831 		}
7832 	} else
7833 		tso = 0;
7834 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
7835 	    ("%s: len > IP_MAXPACKET", __func__));
7836 #ifdef DIAGNOSTIC
7837 #ifdef INET6
7838 	if (max_linkhdr + hdrlen > MCLBYTES)
7839 #else
7840 	if (max_linkhdr + hdrlen > MHLEN)
7841 #endif
7842 		panic("tcphdr too big");
7843 #endif
7844 
7845 	/*
7846 	 * This KASSERT is here to catch edge cases at a well defined place.
7847 	 * Before, those had triggered (random) panic conditions further
7848 	 * down.
7849 	 */
7850 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
7851 	if ((len == 0) &&
7852 	    (flags & TH_FIN) &&
7853 	    (sbused(sb))) {
7854 		/*
7855 		 * We have outstanding data, don't send a fin by itself!.
7856 		 */
7857 		goto just_return;
7858 	}
7859 	/*
7860 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
7861 	 * and initialize the header from the template for sends on this
7862 	 * connection.
7863 	 */
7864 	if (len) {
7865 		uint32_t max_val;
7866 		uint32_t moff;
7867 
7868 		if (rack->rc_pace_max_segs)
7869 			max_val = rack->rc_pace_max_segs * tp->t_maxseg;
7870 		else
7871 			max_val = len;
7872 		/*
7873 		 * We allow a limit on sending with hptsi.
7874 		 */
7875 		if (len > max_val) {
7876 			len = max_val;
7877 		}
7878 #ifdef INET6
7879 		if (MHLEN < hdrlen + max_linkhdr)
7880 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
7881 		else
7882 #endif
7883 			m = m_gethdr(M_NOWAIT, MT_DATA);
7884 
7885 		if (m == NULL) {
7886 			SOCKBUF_UNLOCK(sb);
7887 			error = ENOBUFS;
7888 			sack_rxmit = 0;
7889 			goto out;
7890 		}
7891 		m->m_data += max_linkhdr;
7892 		m->m_len = hdrlen;
7893 
7894 		/*
7895 		 * Start the m_copy functions from the closest mbuf to the
7896 		 * sb_offset in the socket buffer chain.
7897 		 */
7898 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
7899 		if (len <= MHLEN - hdrlen - max_linkhdr) {
7900 			m_copydata(mb, moff, (int)len,
7901 			    mtod(m, caddr_t)+hdrlen);
7902 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
7903 				sbsndptr_adv(sb, mb, len);
7904 			m->m_len += len;
7905 		} else {
7906 			struct sockbuf *msb;
7907 
7908 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
7909 				msb = NULL;
7910 			else
7911 				msb = sb;
7912 			m->m_next = tcp_m_copym(mb, moff, &len,
7913 			    if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, msb);
7914 			if (len <= (tp->t_maxseg - optlen)) {
7915 				/*
7916 				 * Must have ran out of mbufs for the copy
7917 				 * shorten it to no longer need tso. Lets
7918 				 * not put on sendalot since we are low on
7919 				 * mbufs.
7920 				 */
7921 				tso = 0;
7922 			}
7923 			if (m->m_next == NULL) {
7924 				SOCKBUF_UNLOCK(sb);
7925 				(void)m_free(m);
7926 				error = ENOBUFS;
7927 				sack_rxmit = 0;
7928 				goto out;
7929 			}
7930 		}
7931 		if ((tp->t_flags & TF_FORCEDATA) && len == 1) {
7932 			TCPSTAT_INC(tcps_sndprobe);
7933 #ifdef NETFLIX_STATS
7934 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
7935 				stats_voi_update_abs_u32(tp->t_stats,
7936 				    VOI_TCP_RETXPB, len);
7937 			else
7938 				stats_voi_update_abs_u64(tp->t_stats,
7939 				    VOI_TCP_TXPB, len);
7940 #endif
7941 		} else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
7942 			if (rsm && (rsm->r_flags & RACK_TLP)) {
7943 				/*
7944 				 * TLP should not count in retran count, but
7945 				 * in its own bin
7946 				 */
7947 				counter_u64_add(rack_tlp_retran, 1);
7948 				counter_u64_add(rack_tlp_retran_bytes, len);
7949 			} else {
7950 				tp->t_sndrexmitpack++;
7951 				TCPSTAT_INC(tcps_sndrexmitpack);
7952 				TCPSTAT_ADD(tcps_sndrexmitbyte, len);
7953 			}
7954 #ifdef NETFLIX_STATS
7955 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
7956 			    len);
7957 #endif
7958 		} else {
7959 			TCPSTAT_INC(tcps_sndpack);
7960 			TCPSTAT_ADD(tcps_sndbyte, len);
7961 #ifdef NETFLIX_STATS
7962 			stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
7963 			    len);
7964 #endif
7965 		}
7966 		/*
7967 		 * If we're sending everything we've got, set PUSH. (This
7968 		 * will keep happy those implementations which only give
7969 		 * data to the user when a buffer fills or a PUSH comes in.)
7970 		 */
7971 		if (sb_offset + len == sbused(sb) &&
7972 		    sbused(sb) &&
7973 		    !(flags & TH_SYN))
7974 			flags |= TH_PUSH;
7975 
7976 		/*
7977 		 * Are we doing hptsi, if so we must calculate the slot. We
7978 		 * only do hptsi in ESTABLISHED and with no RESET being
7979 		 * sent where we have data to send.
7980 		 */
7981 		if (((tp->t_state == TCPS_ESTABLISHED) ||
7982 		    (tp->t_state == TCPS_CLOSE_WAIT) ||
7983 		    ((tp->t_state == TCPS_FIN_WAIT_1) &&
7984 		    ((tp->t_flags & TF_SENTFIN) == 0) &&
7985 		    ((flags & TH_FIN) == 0))) &&
7986 		    ((flags & TH_RST) == 0) &&
7987 		    (rack->rc_always_pace)) {
7988 			/*
7989 			 * We use the most optimistic possible cwnd/srtt for
7990 			 * sending calculations. This will make our
7991 			 * calculation anticipate getting more through
7992 			 * quicker then possible. But thats ok we don't want
7993 			 * the peer to have a gap in data sending.
7994 			 */
7995 			uint32_t srtt, cwnd, tr_perms = 0;
7996 
7997 			if (rack->r_ctl.rc_rack_min_rtt)
7998 				srtt = rack->r_ctl.rc_rack_min_rtt;
7999 			else
8000 				srtt = TICKS_2_MSEC((tp->t_srtt >> TCP_RTT_SHIFT));
8001 			if (rack->r_ctl.rc_rack_largest_cwnd)
8002 				cwnd = rack->r_ctl.rc_rack_largest_cwnd;
8003 			else
8004 				cwnd = tp->snd_cwnd;
8005 			tr_perms = cwnd / srtt;
8006 			if (tr_perms == 0) {
8007 				tr_perms = tp->t_maxseg;
8008 			}
8009 			tot_len_this_send += len;
8010 			/*
8011 			 * Calculate how long this will take to drain, if
8012 			 * the calculation comes out to zero, thats ok we
8013 			 * will use send_a_lot to possibly spin around for
8014 			 * more increasing tot_len_this_send to the point
8015 			 * that its going to require a pace, or we hit the
8016 			 * cwnd. Which in that case we are just waiting for
8017 			 * a ACK.
8018 			 */
8019 			slot = tot_len_this_send / tr_perms;
8020 			/* Now do we reduce the time so we don't run dry? */
8021 			if (slot && rack->rc_pace_reduce) {
8022 				int32_t reduce;
8023 
8024 				reduce = (slot / rack->rc_pace_reduce);
8025 				if (reduce < slot) {
8026 					slot -= reduce;
8027 				} else
8028 					slot = 0;
8029 			}
8030 			if (rack->r_enforce_min_pace &&
8031 			    (slot == 0) &&
8032 			    (tot_len_this_send >= (rack->r_min_pace_seg_thresh * tp->t_maxseg))) {
8033 				/* We are enforcing a minimum pace time of 1ms */
8034 				slot = rack->r_enforce_min_pace;
8035 			}
8036 		}
8037 		SOCKBUF_UNLOCK(sb);
8038 	} else {
8039 		SOCKBUF_UNLOCK(sb);
8040 		if (tp->t_flags & TF_ACKNOW)
8041 			TCPSTAT_INC(tcps_sndacks);
8042 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
8043 			TCPSTAT_INC(tcps_sndctrl);
8044 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
8045 			TCPSTAT_INC(tcps_sndurg);
8046 		else
8047 			TCPSTAT_INC(tcps_sndwinup);
8048 
8049 		m = m_gethdr(M_NOWAIT, MT_DATA);
8050 		if (m == NULL) {
8051 			error = ENOBUFS;
8052 			sack_rxmit = 0;
8053 			goto out;
8054 		}
8055 #ifdef INET6
8056 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
8057 		    MHLEN >= hdrlen) {
8058 			M_ALIGN(m, hdrlen);
8059 		} else
8060 #endif
8061 			m->m_data += max_linkhdr;
8062 		m->m_len = hdrlen;
8063 	}
8064 	SOCKBUF_UNLOCK_ASSERT(sb);
8065 	m->m_pkthdr.rcvif = (struct ifnet *)0;
8066 #ifdef MAC
8067 	mac_inpcb_create_mbuf(inp, m);
8068 #endif
8069 #ifdef INET6
8070 	if (isipv6) {
8071 		ip6 = mtod(m, struct ip6_hdr *);
8072 #ifdef NETFLIX_TCPOUDP
8073 		if (tp->t_port) {
8074 			udp = (struct udphdr *)((caddr_t)ip6 + ipoptlen + sizeof(struct ip6_hdr));
8075 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
8076 			udp->uh_dport = tp->t_port;
8077 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
8078 			udp->uh_ulen = htons(ulen);
8079 			th = (struct tcphdr *)(udp + 1);
8080 		} else
8081 #endif
8082 			th = (struct tcphdr *)(ip6 + 1);
8083 		tcpip_fillheaders(inp, ip6, th);
8084 	} else
8085 #endif				/* INET6 */
8086 	{
8087 		ip = mtod(m, struct ip *);
8088 #ifdef TCPDEBUG
8089 		ipov = (struct ipovly *)ip;
8090 #endif
8091 #ifdef NETFLIX_TCPOUDP
8092 		if (tp->t_port) {
8093 			udp = (struct udphdr *)((caddr_t)ip + ipoptlen + sizeof(struct ip));
8094 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
8095 			udp->uh_dport = tp->t_port;
8096 			ulen = hdrlen + len - sizeof(struct ip);
8097 			udp->uh_ulen = htons(ulen);
8098 			th = (struct tcphdr *)(udp + 1);
8099 		} else
8100 #endif
8101 			th = (struct tcphdr *)(ip + 1);
8102 		tcpip_fillheaders(inp, ip, th);
8103 	}
8104 	/*
8105 	 * Fill in fields, remembering maximum advertised window for use in
8106 	 * delaying messages about window sizes. If resending a FIN, be sure
8107 	 * not to use a new sequence number.
8108 	 */
8109 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
8110 	    tp->snd_nxt == tp->snd_max)
8111 		tp->snd_nxt--;
8112 	/*
8113 	 * If we are starting a connection, send ECN setup SYN packet. If we
8114 	 * are on a retransmit, we may resend those bits a number of times
8115 	 * as per RFC 3168.
8116 	 */
8117 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
8118 		if (tp->t_rxtshift >= 1) {
8119 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
8120 				flags |= TH_ECE | TH_CWR;
8121 		} else
8122 			flags |= TH_ECE | TH_CWR;
8123 	}
8124 	if (tp->t_state == TCPS_ESTABLISHED &&
8125 	    (tp->t_flags & TF_ECN_PERMIT)) {
8126 		/*
8127 		 * If the peer has ECN, mark data packets with ECN capable
8128 		 * transmission (ECT). Ignore pure ack packets,
8129 		 * retransmissions and window probes.
8130 		 */
8131 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
8132 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
8133 #ifdef INET6
8134 			if (isipv6)
8135 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
8136 			else
8137 #endif
8138 				ip->ip_tos |= IPTOS_ECN_ECT0;
8139 			TCPSTAT_INC(tcps_ecn_ect0);
8140 		}
8141 		/*
8142 		 * Reply with proper ECN notifications.
8143 		 */
8144 		if (tp->t_flags & TF_ECN_SND_CWR) {
8145 			flags |= TH_CWR;
8146 			tp->t_flags &= ~TF_ECN_SND_CWR;
8147 		}
8148 		if (tp->t_flags & TF_ECN_SND_ECE)
8149 			flags |= TH_ECE;
8150 	}
8151 	/*
8152 	 * If we are doing retransmissions, then snd_nxt will not reflect
8153 	 * the first unsent octet.  For ACK only packets, we do not want the
8154 	 * sequence number of the retransmitted packet, we want the sequence
8155 	 * number of the next unsent octet.  So, if there is no data (and no
8156 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
8157 	 * ti_seq.  But if we are in persist state, snd_max might reflect
8158 	 * one byte beyond the right edge of the window, so use snd_nxt in
8159 	 * that case, since we know we aren't doing a retransmission.
8160 	 * (retransmit and persist are mutually exclusive...)
8161 	 */
8162 	if (sack_rxmit == 0) {
8163 		if (len || (flags & (TH_SYN | TH_FIN)) ||
8164 		    rack->rc_in_persist) {
8165 			th->th_seq = htonl(tp->snd_nxt);
8166 			rack_seq = tp->snd_nxt;
8167 		} else if (flags & TH_RST) {
8168 			/*
8169 			 * For a Reset send the last cum ack in sequence
8170 			 * (this like any other choice may still generate a
8171 			 * challenge ack, if a ack-update packet is in
8172 			 * flight).
8173 			 */
8174 			th->th_seq = htonl(tp->snd_una);
8175 			rack_seq = tp->snd_una;
8176 		} else {
8177 			th->th_seq = htonl(tp->snd_max);
8178 			rack_seq = tp->snd_max;
8179 		}
8180 	} else {
8181 		th->th_seq = htonl(rsm->r_start);
8182 		rack_seq = rsm->r_start;
8183 	}
8184 	th->th_ack = htonl(tp->rcv_nxt);
8185 	if (optlen) {
8186 		bcopy(opt, th + 1, optlen);
8187 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
8188 	}
8189 	th->th_flags = flags;
8190 	/*
8191 	 * Calculate receive window.  Don't shrink window, but avoid silly
8192 	 * window syndrome.
8193 	 * If a RST segment is sent, advertise a window of zero.
8194 	 */
8195 	if (flags & TH_RST) {
8196 		recwin = 0;
8197 	} else {
8198 		if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
8199 		    recwin < (long)tp->t_maxseg)
8200 			recwin = 0;
8201 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
8202 		    recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
8203 			recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
8204 		if (recwin > (long)TCP_MAXWIN << tp->rcv_scale)
8205 			recwin = (long)TCP_MAXWIN << tp->rcv_scale;
8206 	}
8207 
8208 	/*
8209 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
8210 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
8211 	 * handled in syncache.
8212 	 */
8213 	if (flags & TH_SYN)
8214 		th->th_win = htons((u_short)
8215 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
8216 	else
8217 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
8218 	/*
8219 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
8220 	 * window.  This may cause the remote transmitter to stall.  This
8221 	 * flag tells soreceive() to disable delayed acknowledgements when
8222 	 * draining the buffer.  This can occur if the receiver is
8223 	 * attempting to read more data than can be buffered prior to
8224 	 * transmitting on the connection.
8225 	 */
8226 	if (th->th_win == 0) {
8227 		tp->t_sndzerowin++;
8228 		tp->t_flags |= TF_RXWIN0SENT;
8229 	} else
8230 		tp->t_flags &= ~TF_RXWIN0SENT;
8231 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
8232 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_nxt));
8233 		th->th_flags |= TH_URG;
8234 	} else
8235 		/*
8236 		 * If no urgent pointer to send, then we pull the urgent
8237 		 * pointer to the left edge of the send window so that it
8238 		 * doesn't drift into the send window on sequence number
8239 		 * wraparound.
8240 		 */
8241 		tp->snd_up = tp->snd_una;	/* drag it along */
8242 
8243 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
8244 	if (to.to_flags & TOF_SIGNATURE) {
8245 		/*
8246 		 * Calculate MD5 signature and put it into the place
8247 		 * determined before.
8248 		 * NOTE: since TCP options buffer doesn't point into
8249 		 * mbuf's data, calculate offset and use it.
8250 		 */
8251 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
8252 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
8253 			/*
8254 			 * Do not send segment if the calculation of MD5
8255 			 * digest has failed.
8256 			 */
8257 			goto out;
8258 		}
8259 	}
8260 #endif
8261 
8262 	/*
8263 	 * Put TCP length in extended header, and then checksum extended
8264 	 * header and data.
8265 	 */
8266 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
8267 #ifdef INET6
8268 	if (isipv6) {
8269 		/*
8270 		 * ip6_plen is not need to be filled now, and will be filled
8271 		 * in ip6_output.
8272 		 */
8273 		if (tp->t_port) {
8274 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
8275 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
8276 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
8277 			th->th_sum = htons(0);
8278 		} else {
8279 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
8280 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
8281 			th->th_sum = in6_cksum_pseudo(ip6,
8282 			    sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
8283 			    0);
8284 		}
8285 	}
8286 #endif
8287 #if defined(INET6) && defined(INET)
8288 	else
8289 #endif
8290 #ifdef INET
8291 	{
8292 		if (tp->t_port) {
8293 			m->m_pkthdr.csum_flags = CSUM_UDP;
8294 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
8295 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
8296 			   ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
8297 			th->th_sum = htons(0);
8298 		} else {
8299 			m->m_pkthdr.csum_flags = CSUM_TCP;
8300 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
8301 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
8302 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
8303 			    IPPROTO_TCP + len + optlen));
8304 		}
8305 		/* IP version must be set here for ipv4/ipv6 checking later */
8306 		KASSERT(ip->ip_v == IPVERSION,
8307 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
8308 	}
8309 #endif
8310 
8311 	/*
8312 	 * Enable TSO and specify the size of the segments. The TCP pseudo
8313 	 * header checksum is always provided. XXX: Fixme: This is currently
8314 	 * not the case for IPv6.
8315 	 */
8316 	if (tso) {
8317 		KASSERT(len > tp->t_maxseg - optlen,
8318 		    ("%s: len <= tso_segsz", __func__));
8319 		m->m_pkthdr.csum_flags |= CSUM_TSO;
8320 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
8321 	}
8322 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
8323 	KASSERT(len + hdrlen + ipoptlen - ipsec_optlen == m_length(m, NULL),
8324 	    ("%s: mbuf chain shorter than expected: %d + %u + %u - %u != %u",
8325 	    __func__, len, hdrlen, ipoptlen, ipsec_optlen, m_length(m, NULL)));
8326 #else
8327 	KASSERT(len + hdrlen + ipoptlen == m_length(m, NULL),
8328 	    ("%s: mbuf chain shorter than expected: %d + %u + %u != %u",
8329 	    __func__, len, hdrlen, ipoptlen, m_length(m, NULL)));
8330 #endif
8331 
8332 #ifdef TCP_HHOOK
8333 	/* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
8334 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
8335 #endif
8336 
8337 #ifdef TCPDEBUG
8338 	/*
8339 	 * Trace.
8340 	 */
8341 	if (so->so_options & SO_DEBUG) {
8342 		u_short save = 0;
8343 
8344 #ifdef INET6
8345 		if (!isipv6)
8346 #endif
8347 		{
8348 			save = ipov->ih_len;
8349 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
8350 			      * (th->th_off << 2) */ );
8351 		}
8352 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
8353 #ifdef INET6
8354 		if (!isipv6)
8355 #endif
8356 			ipov->ih_len = save;
8357 	}
8358 #endif				/* TCPDEBUG */
8359 
8360 	/* We're getting ready to send; log now. */
8361 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
8362 		union tcp_log_stackspecific log;
8363 
8364 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
8365 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
8366 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
8367 		log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
8368 		if (rsm || sack_rxmit) {
8369 			log.u_bbr.flex8 = 1;
8370 		} else {
8371 			log.u_bbr.flex8 = 0;
8372 		}
8373 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
8374 		    len, &log, false, NULL, NULL, 0, NULL);
8375 	} else
8376 		lgb = NULL;
8377 
8378 	/*
8379 	 * Fill in IP length and desired time to live and send to IP level.
8380 	 * There should be a better way to handle ttl and tos; we could keep
8381 	 * them in the template, but need a way to checksum without them.
8382 	 */
8383 	/*
8384 	 * m->m_pkthdr.len should have been set before cksum calcuration,
8385 	 * because in6_cksum() need it.
8386 	 */
8387 #ifdef INET6
8388 	if (isipv6) {
8389 		/*
8390 		 * we separately set hoplimit for every segment, since the
8391 		 * user might want to change the value via setsockopt. Also,
8392 		 * desired default hop limit might be changed via Neighbor
8393 		 * Discovery.
8394 		 */
8395 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
8396 
8397 		/*
8398 		 * Set the packet size here for the benefit of DTrace
8399 		 * probes. ip6_output() will set it properly; it's supposed
8400 		 * to include the option header lengths as well.
8401 		 */
8402 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
8403 
8404 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
8405 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
8406 		else
8407 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
8408 
8409 		if (tp->t_state == TCPS_SYN_SENT)
8410 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
8411 
8412 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
8413 		/* TODO: IPv6 IP6TOS_ECT bit on */
8414 		error = ip6_output(m, tp->t_inpcb->in6p_outputopts,
8415 		    &inp->inp_route6,
8416 		    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0),
8417 		    NULL, NULL, inp);
8418 
8419 		if (error == EMSGSIZE && inp->inp_route6.ro_rt != NULL)
8420 			mtu = inp->inp_route6.ro_rt->rt_mtu;
8421 	}
8422 #endif				/* INET6 */
8423 #if defined(INET) && defined(INET6)
8424 	else
8425 #endif
8426 #ifdef INET
8427 	{
8428 		ip->ip_len = htons(m->m_pkthdr.len);
8429 #ifdef INET6
8430 		if (inp->inp_vflag & INP_IPV6PROTO)
8431 			ip->ip_ttl = in6_selecthlim(inp, NULL);
8432 #endif				/* INET6 */
8433 		/*
8434 		 * If we do path MTU discovery, then we set DF on every
8435 		 * packet. This might not be the best thing to do according
8436 		 * to RFC3390 Section 2. However the tcp hostcache migitates
8437 		 * the problem so it affects only the first tcp connection
8438 		 * with a host.
8439 		 *
8440 		 * NB: Don't set DF on small MTU/MSS to have a safe
8441 		 * fallback.
8442 		 */
8443 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
8444 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
8445 			if (tp->t_port == 0 || len < V_tcp_minmss) {
8446 				ip->ip_off |= htons(IP_DF);
8447 			}
8448 		} else {
8449 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
8450 		}
8451 
8452 		if (tp->t_state == TCPS_SYN_SENT)
8453 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
8454 
8455 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
8456 
8457 		error = ip_output(m, tp->t_inpcb->inp_options, &inp->inp_route,
8458 		    ((so->so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0), 0,
8459 		    inp);
8460 		if (error == EMSGSIZE && inp->inp_route.ro_rt != NULL)
8461 			mtu = inp->inp_route.ro_rt->rt_mtu;
8462 	}
8463 #endif				/* INET */
8464 
8465 out:
8466 	if (lgb) {
8467 		lgb->tlb_errno = error;
8468 		lgb = NULL;
8469 	}
8470 	/*
8471 	 * In transmit state, time the transmission and arrange for the
8472 	 * retransmit.  In persist state, just set snd_max.
8473 	 */
8474 	if (error == 0) {
8475 		if (len == 0)
8476 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_SNDACK], 1);
8477 		else if (len == 1) {
8478 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_PERSIST], 1);
8479 		} else if (len > 1) {
8480 			int idx;
8481 
8482 			idx = (len / tp->t_maxseg) + 3;
8483 			if (idx >= TCP_MSS_ACCT_ATIMER)
8484 				counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
8485 			else
8486 				counter_u64_add(rack_out_size[idx], 1);
8487 		}
8488 	}
8489 	if (sub_from_prr && (error == 0)) {
8490 		rack->r_ctl.rc_prr_sndcnt -= len;
8491 	}
8492 	sub_from_prr = 0;
8493 	rack_log_output(tp, &to, len, rack_seq, (uint8_t) flags, error, cts,
8494 	    pass, rsm);
8495 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
8496 	    (rack->rc_in_persist == 0)) {
8497 		tcp_seq startseq = tp->snd_nxt;
8498 
8499 		/*
8500 		 * Advance snd_nxt over sequence space of this segment.
8501 		 */
8502 		if (error)
8503 			/* We don't log or do anything with errors */
8504 			goto timer;
8505 
8506 		if (flags & (TH_SYN | TH_FIN)) {
8507 			if (flags & TH_SYN)
8508 				tp->snd_nxt++;
8509 			if (flags & TH_FIN) {
8510 				tp->snd_nxt++;
8511 				tp->t_flags |= TF_SENTFIN;
8512 			}
8513 		}
8514 		/* In the ENOBUFS case we do *not* update snd_max */
8515 		if (sack_rxmit)
8516 			goto timer;
8517 
8518 		tp->snd_nxt += len;
8519 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
8520 			if (tp->snd_una == tp->snd_max) {
8521 				/*
8522 				 * Update the time we just added data since
8523 				 * none was outstanding.
8524 				 */
8525 				rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
8526 				tp->t_acktime = ticks;
8527 			}
8528 			tp->snd_max = tp->snd_nxt;
8529 			/*
8530 			 * Time this transmission if not a retransmission and
8531 			 * not currently timing anything.
8532 			 * This is only relevant in case of switching back to
8533 			 * the base stack.
8534 			 */
8535 			if (tp->t_rtttime == 0) {
8536 				tp->t_rtttime = ticks;
8537 				tp->t_rtseq = startseq;
8538 				TCPSTAT_INC(tcps_segstimed);
8539 			}
8540 #ifdef NETFLIX_STATS
8541 			if (!(tp->t_flags & TF_GPUTINPROG) && len) {
8542 				tp->t_flags |= TF_GPUTINPROG;
8543 				tp->gput_seq = startseq;
8544 				tp->gput_ack = startseq +
8545 				    ulmin(sbavail(sb) - sb_offset, sendwin);
8546 				tp->gput_ts = tcp_ts_getticks();
8547 			}
8548 #endif
8549 		}
8550 		/*
8551 		 * Set retransmit timer if not currently set, and not doing
8552 		 * a pure ack or a keep-alive probe. Initial value for
8553 		 * retransmit timer is smoothed round-trip time + 2 *
8554 		 * round-trip time variance. Initialize shift counter which
8555 		 * is used for backoff of retransmit time.
8556 		 */
8557 timer:
8558 		if ((tp->snd_wnd == 0) &&
8559 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8560 			/*
8561 			 * If the persists timer was set above (right before
8562 			 * the goto send), and still needs to be on. Lets
8563 			 * make sure all is canceled. If the persist timer
8564 			 * is not running, we want to get it up.
8565 			 */
8566 			if (rack->rc_in_persist == 0) {
8567 				rack_enter_persist(tp, rack, cts);
8568 			}
8569 		}
8570 	} else {
8571 		/*
8572 		 * Persist case, update snd_max but since we are in persist
8573 		 * mode (no window) we do not update snd_nxt.
8574 		 */
8575 		int32_t xlen = len;
8576 
8577 		if (error)
8578 			goto nomore;
8579 
8580 		if (flags & TH_SYN)
8581 			++xlen;
8582 		if (flags & TH_FIN) {
8583 			++xlen;
8584 			tp->t_flags |= TF_SENTFIN;
8585 		}
8586 		/* In the ENOBUFS case we do *not* update snd_max */
8587 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max)) {
8588 			if (tp->snd_una == tp->snd_max) {
8589 				/*
8590 				 * Update the time we just added data since
8591 				 * none was outstanding.
8592 				 */
8593 				rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
8594 				tp->t_acktime = ticks;
8595 			}
8596 			tp->snd_max = tp->snd_nxt + len;
8597 		}
8598 	}
8599 nomore:
8600 	if (error) {
8601 		SOCKBUF_UNLOCK_ASSERT(sb);	/* Check gotos. */
8602 		/*
8603 		 * Failures do not advance the seq counter above. For the
8604 		 * case of ENOBUFS we will fall out and retry in 1ms with
8605 		 * the hpts. Everything else will just have to retransmit
8606 		 * with the timer.
8607 		 *
8608 		 * In any case, we do not want to loop around for another
8609 		 * send without a good reason.
8610 		 */
8611 		sendalot = 0;
8612 		switch (error) {
8613 		case EPERM:
8614 			tp->t_flags &= ~TF_FORCEDATA;
8615 			tp->t_softerror = error;
8616 			return (error);
8617 		case ENOBUFS:
8618 			if (slot == 0) {
8619 				/*
8620 				 * Pace us right away to retry in a some
8621 				 * time
8622 				 */
8623 				slot = 1 + rack->rc_enobuf;
8624 				if (rack->rc_enobuf < 255)
8625 					rack->rc_enobuf++;
8626 				if (slot > (rack->rc_rack_rtt / 2)) {
8627 					slot = rack->rc_rack_rtt / 2;
8628 				}
8629 				if (slot < 10)
8630 					slot = 10;
8631 			}
8632 			counter_u64_add(rack_saw_enobuf, 1);
8633 			error = 0;
8634 			goto enobufs;
8635 		case EMSGSIZE:
8636 			/*
8637 			 * For some reason the interface we used initially
8638 			 * to send segments changed to another or lowered
8639 			 * its MTU. If TSO was active we either got an
8640 			 * interface without TSO capabilits or TSO was
8641 			 * turned off. If we obtained mtu from ip_output()
8642 			 * then update it and try again.
8643 			 */
8644 			if (tso)
8645 				tp->t_flags &= ~TF_TSO;
8646 			if (mtu != 0) {
8647 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
8648 				goto again;
8649 			}
8650 			slot = 10;
8651 			rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, 0, 1);
8652 			tp->t_flags &= ~TF_FORCEDATA;
8653 			return (error);
8654 		case ENETUNREACH:
8655 			counter_u64_add(rack_saw_enetunreach, 1);
8656 		case EHOSTDOWN:
8657 		case EHOSTUNREACH:
8658 		case ENETDOWN:
8659 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
8660 				tp->t_softerror = error;
8661 			}
8662 			/* FALLTHROUGH */
8663 		default:
8664 			slot = 10;
8665 			rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, 0, 1);
8666 			tp->t_flags &= ~TF_FORCEDATA;
8667 			return (error);
8668 		}
8669 	} else {
8670 		rack->rc_enobuf = 0;
8671 	}
8672 	TCPSTAT_INC(tcps_sndtotal);
8673 
8674 	/*
8675 	 * Data sent (as far as we can tell). If this advertises a larger
8676 	 * window than any other segment, then remember the size of the
8677 	 * advertised window. Any pending ACK has now been sent.
8678 	 */
8679 	if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
8680 		tp->rcv_adv = tp->rcv_nxt + recwin;
8681 	tp->last_ack_sent = tp->rcv_nxt;
8682 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
8683 enobufs:
8684 	rack->r_tlp_running = 0;
8685 	if ((flags & TH_RST) || (would_have_fin == 1)) {
8686 		/*
8687 		 * We don't send again after a RST. We also do *not* send
8688 		 * again if we would have had a find, but now have
8689 		 * outstanding data.
8690 		 */
8691 		slot = 0;
8692 		sendalot = 0;
8693 	}
8694 	if (slot) {
8695 		/* set the rack tcb into the slot N */
8696 		counter_u64_add(rack_paced_segments, 1);
8697 	} else if (sendalot) {
8698 		if (len)
8699 			counter_u64_add(rack_unpaced_segments, 1);
8700 		sack_rxmit = 0;
8701 		tp->t_flags &= ~TF_FORCEDATA;
8702 		goto again;
8703 	} else if (len) {
8704 		counter_u64_add(rack_unpaced_segments, 1);
8705 	}
8706 	tp->t_flags &= ~TF_FORCEDATA;
8707 	rack_start_hpts_timer(rack, tp, cts, __LINE__, slot, tot_len_this_send, 1);
8708 	return (error);
8709 }
8710 
8711 /*
8712  * rack_ctloutput() must drop the inpcb lock before performing copyin on
8713  * socket option arguments.  When it re-acquires the lock after the copy, it
8714  * has to revalidate that the connection is still valid for the socket
8715  * option.
8716  */
8717 static int
8718 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
8719     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
8720 {
8721 	int32_t error = 0, optval;
8722 
8723 	switch (sopt->sopt_name) {
8724 	case TCP_RACK_PROP_RATE:
8725 	case TCP_RACK_PROP:
8726 	case TCP_RACK_TLP_REDUCE:
8727 	case TCP_RACK_EARLY_RECOV:
8728 	case TCP_RACK_PACE_ALWAYS:
8729 	case TCP_DELACK:
8730 	case TCP_RACK_PACE_REDUCE:
8731 	case TCP_RACK_PACE_MAX_SEG:
8732 	case TCP_RACK_PRR_SENDALOT:
8733 	case TCP_RACK_MIN_TO:
8734 	case TCP_RACK_EARLY_SEG:
8735 	case TCP_RACK_REORD_THRESH:
8736 	case TCP_RACK_REORD_FADE:
8737 	case TCP_RACK_TLP_THRESH:
8738 	case TCP_RACK_PKT_DELAY:
8739 	case TCP_RACK_TLP_USE:
8740 	case TCP_RACK_TLP_INC_VAR:
8741 	case TCP_RACK_IDLE_REDUCE_HIGH:
8742 	case TCP_RACK_MIN_PACE:
8743 	case TCP_RACK_MIN_PACE_SEG:
8744 	case TCP_BBR_RACK_RTT_USE:
8745 	case TCP_DATA_AFTER_CLOSE:
8746 		break;
8747 	default:
8748 		return (tcp_default_ctloutput(so, sopt, inp, tp));
8749 		break;
8750 	}
8751 	INP_WUNLOCK(inp);
8752 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
8753 	if (error)
8754 		return (error);
8755 	INP_WLOCK(inp);
8756 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
8757 		INP_WUNLOCK(inp);
8758 		return (ECONNRESET);
8759 	}
8760 	tp = intotcpcb(inp);
8761 	rack = (struct tcp_rack *)tp->t_fb_ptr;
8762 	switch (sopt->sopt_name) {
8763 	case TCP_RACK_PROP_RATE:
8764 		if ((optval <= 0) || (optval >= 100)) {
8765 			error = EINVAL;
8766 			break;
8767 		}
8768 		RACK_OPTS_INC(tcp_rack_prop_rate);
8769 		rack->r_ctl.rc_prop_rate = optval;
8770 		break;
8771 	case TCP_RACK_TLP_USE:
8772 		if ((optval < TLP_USE_ID) || (optval > TLP_USE_TWO_TWO)) {
8773 			error = EINVAL;
8774 			break;
8775 		}
8776 		RACK_OPTS_INC(tcp_tlp_use);
8777 		rack->rack_tlp_threshold_use = optval;
8778 		break;
8779 	case TCP_RACK_PROP:
8780 		/* RACK proportional rate reduction (bool) */
8781 		RACK_OPTS_INC(tcp_rack_prop);
8782 		rack->r_ctl.rc_prop_reduce = optval;
8783 		break;
8784 	case TCP_RACK_TLP_REDUCE:
8785 		/* RACK TLP cwnd reduction (bool) */
8786 		RACK_OPTS_INC(tcp_rack_tlp_reduce);
8787 		rack->r_ctl.rc_tlp_cwnd_reduce = optval;
8788 		break;
8789 	case TCP_RACK_EARLY_RECOV:
8790 		/* Should recovery happen early (bool) */
8791 		RACK_OPTS_INC(tcp_rack_early_recov);
8792 		rack->r_ctl.rc_early_recovery = optval;
8793 		break;
8794 	case TCP_RACK_PACE_ALWAYS:
8795 		/* Use the always pace method (bool)  */
8796 		RACK_OPTS_INC(tcp_rack_pace_always);
8797 		if (optval > 0)
8798 			rack->rc_always_pace = 1;
8799 		else
8800 			rack->rc_always_pace = 0;
8801 		break;
8802 	case TCP_RACK_PACE_REDUCE:
8803 		/* RACK Hptsi reduction factor (divisor) */
8804 		RACK_OPTS_INC(tcp_rack_pace_reduce);
8805 		if (optval)
8806 			/* Must be non-zero */
8807 			rack->rc_pace_reduce = optval;
8808 		else
8809 			error = EINVAL;
8810 		break;
8811 	case TCP_RACK_PACE_MAX_SEG:
8812 		/* Max segments in a pace */
8813 		RACK_OPTS_INC(tcp_rack_max_seg);
8814 		rack->rc_pace_max_segs = optval;
8815 		break;
8816 	case TCP_RACK_PRR_SENDALOT:
8817 		/* Allow PRR to send more than one seg */
8818 		RACK_OPTS_INC(tcp_rack_prr_sendalot);
8819 		rack->r_ctl.rc_prr_sendalot = optval;
8820 		break;
8821 	case TCP_RACK_MIN_TO:
8822 		/* Minimum time between rack t-o's in ms */
8823 		RACK_OPTS_INC(tcp_rack_min_to);
8824 		rack->r_ctl.rc_min_to = optval;
8825 		break;
8826 	case TCP_RACK_EARLY_SEG:
8827 		/* If early recovery max segments */
8828 		RACK_OPTS_INC(tcp_rack_early_seg);
8829 		rack->r_ctl.rc_early_recovery_segs = optval;
8830 		break;
8831 	case TCP_RACK_REORD_THRESH:
8832 		/* RACK reorder threshold (shift amount) */
8833 		RACK_OPTS_INC(tcp_rack_reord_thresh);
8834 		if ((optval > 0) && (optval < 31))
8835 			rack->r_ctl.rc_reorder_shift = optval;
8836 		else
8837 			error = EINVAL;
8838 		break;
8839 	case TCP_RACK_REORD_FADE:
8840 		/* Does reordering fade after ms time */
8841 		RACK_OPTS_INC(tcp_rack_reord_fade);
8842 		rack->r_ctl.rc_reorder_fade = optval;
8843 		break;
8844 	case TCP_RACK_TLP_THRESH:
8845 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
8846 		RACK_OPTS_INC(tcp_rack_tlp_thresh);
8847 		if (optval)
8848 			rack->r_ctl.rc_tlp_threshold = optval;
8849 		else
8850 			error = EINVAL;
8851 		break;
8852 	case TCP_RACK_PKT_DELAY:
8853 		/* RACK added ms i.e. rack-rtt + reord + N */
8854 		RACK_OPTS_INC(tcp_rack_pkt_delay);
8855 		rack->r_ctl.rc_pkt_delay = optval;
8856 		break;
8857 	case TCP_RACK_TLP_INC_VAR:
8858 		/* Does TLP include rtt variance in t-o */
8859 		RACK_OPTS_INC(tcp_rack_tlp_inc_var);
8860 		rack->r_ctl.rc_prr_inc_var = optval;
8861 		break;
8862 	case TCP_RACK_IDLE_REDUCE_HIGH:
8863 		RACK_OPTS_INC(tcp_rack_idle_reduce_high);
8864 		if (optval)
8865 			rack->r_idle_reduce_largest = 1;
8866 		else
8867 			rack->r_idle_reduce_largest = 0;
8868 		break;
8869 	case TCP_DELACK:
8870 		if (optval == 0)
8871 			tp->t_delayed_ack = 0;
8872 		else
8873 			tp->t_delayed_ack = 1;
8874 		if (tp->t_flags & TF_DELACK) {
8875 			tp->t_flags &= ~TF_DELACK;
8876 			tp->t_flags |= TF_ACKNOW;
8877 			rack_output(tp);
8878 		}
8879 		break;
8880 	case TCP_RACK_MIN_PACE:
8881 		RACK_OPTS_INC(tcp_rack_min_pace);
8882 		if (optval > 3)
8883 			rack->r_enforce_min_pace = 3;
8884 		else
8885 			rack->r_enforce_min_pace = optval;
8886 		break;
8887 	case TCP_RACK_MIN_PACE_SEG:
8888 		RACK_OPTS_INC(tcp_rack_min_pace_seg);
8889 		if (optval >= 16)
8890 			rack->r_min_pace_seg_thresh = 15;
8891 		else
8892 			rack->r_min_pace_seg_thresh = optval;
8893 		break;
8894 	case TCP_BBR_RACK_RTT_USE:
8895 		if ((optval != USE_RTT_HIGH) &&
8896 		    (optval != USE_RTT_LOW) &&
8897 		    (optval != USE_RTT_AVG))
8898 			error = EINVAL;
8899 		else
8900 			rack->r_ctl.rc_rate_sample_method = optval;
8901 		break;
8902 	case TCP_DATA_AFTER_CLOSE:
8903 		if (optval)
8904 			rack->rc_allow_data_af_clo = 1;
8905 		else
8906 			rack->rc_allow_data_af_clo = 0;
8907 		break;
8908 	default:
8909 		return (tcp_default_ctloutput(so, sopt, inp, tp));
8910 		break;
8911 	}
8912 #ifdef NETFLIX_STATS
8913 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
8914 #endif
8915 	INP_WUNLOCK(inp);
8916 	return (error);
8917 }
8918 
8919 static int
8920 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
8921     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
8922 {
8923 	int32_t error, optval;
8924 
8925 	/*
8926 	 * Because all our options are either boolean or an int, we can just
8927 	 * pull everything into optval and then unlock and copy. If we ever
8928 	 * add a option that is not a int, then this will have quite an
8929 	 * impact to this routine.
8930 	 */
8931 	switch (sopt->sopt_name) {
8932 	case TCP_RACK_PROP_RATE:
8933 		optval = rack->r_ctl.rc_prop_rate;
8934 		break;
8935 	case TCP_RACK_PROP:
8936 		/* RACK proportional rate reduction (bool) */
8937 		optval = rack->r_ctl.rc_prop_reduce;
8938 		break;
8939 	case TCP_RACK_TLP_REDUCE:
8940 		/* RACK TLP cwnd reduction (bool) */
8941 		optval = rack->r_ctl.rc_tlp_cwnd_reduce;
8942 		break;
8943 	case TCP_RACK_EARLY_RECOV:
8944 		/* Should recovery happen early (bool) */
8945 		optval = rack->r_ctl.rc_early_recovery;
8946 		break;
8947 	case TCP_RACK_PACE_REDUCE:
8948 		/* RACK Hptsi reduction factor (divisor) */
8949 		optval = rack->rc_pace_reduce;
8950 		break;
8951 	case TCP_RACK_PACE_MAX_SEG:
8952 		/* Max segments in a pace */
8953 		optval = rack->rc_pace_max_segs;
8954 		break;
8955 	case TCP_RACK_PACE_ALWAYS:
8956 		/* Use the always pace method */
8957 		optval = rack->rc_always_pace;
8958 		break;
8959 	case TCP_RACK_PRR_SENDALOT:
8960 		/* Allow PRR to send more than one seg */
8961 		optval = rack->r_ctl.rc_prr_sendalot;
8962 		break;
8963 	case TCP_RACK_MIN_TO:
8964 		/* Minimum time between rack t-o's in ms */
8965 		optval = rack->r_ctl.rc_min_to;
8966 		break;
8967 	case TCP_RACK_EARLY_SEG:
8968 		/* If early recovery max segments */
8969 		optval = rack->r_ctl.rc_early_recovery_segs;
8970 		break;
8971 	case TCP_RACK_REORD_THRESH:
8972 		/* RACK reorder threshold (shift amount) */
8973 		optval = rack->r_ctl.rc_reorder_shift;
8974 		break;
8975 	case TCP_RACK_REORD_FADE:
8976 		/* Does reordering fade after ms time */
8977 		optval = rack->r_ctl.rc_reorder_fade;
8978 		break;
8979 	case TCP_RACK_TLP_THRESH:
8980 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
8981 		optval = rack->r_ctl.rc_tlp_threshold;
8982 		break;
8983 	case TCP_RACK_PKT_DELAY:
8984 		/* RACK added ms i.e. rack-rtt + reord + N */
8985 		optval = rack->r_ctl.rc_pkt_delay;
8986 		break;
8987 	case TCP_RACK_TLP_USE:
8988 		optval = rack->rack_tlp_threshold_use;
8989 		break;
8990 	case TCP_RACK_TLP_INC_VAR:
8991 		/* Does TLP include rtt variance in t-o */
8992 		optval = rack->r_ctl.rc_prr_inc_var;
8993 		break;
8994 	case TCP_RACK_IDLE_REDUCE_HIGH:
8995 		optval = rack->r_idle_reduce_largest;
8996 		break;
8997 	case TCP_RACK_MIN_PACE:
8998 		optval = rack->r_enforce_min_pace;
8999 		break;
9000 	case TCP_RACK_MIN_PACE_SEG:
9001 		optval = rack->r_min_pace_seg_thresh;
9002 		break;
9003 	case TCP_BBR_RACK_RTT_USE:
9004 		optval = rack->r_ctl.rc_rate_sample_method;
9005 		break;
9006 	case TCP_DELACK:
9007 		optval = tp->t_delayed_ack;
9008 		break;
9009 	case TCP_DATA_AFTER_CLOSE:
9010 		optval = rack->rc_allow_data_af_clo;
9011 		break;
9012 	default:
9013 		return (tcp_default_ctloutput(so, sopt, inp, tp));
9014 		break;
9015 	}
9016 	INP_WUNLOCK(inp);
9017 	error = sooptcopyout(sopt, &optval, sizeof optval);
9018 	return (error);
9019 }
9020 
9021 static int
9022 rack_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
9023 {
9024 	int32_t error = EINVAL;
9025 	struct tcp_rack *rack;
9026 
9027 	rack = (struct tcp_rack *)tp->t_fb_ptr;
9028 	if (rack == NULL) {
9029 		/* Huh? */
9030 		goto out;
9031 	}
9032 	if (sopt->sopt_dir == SOPT_SET) {
9033 		return (rack_set_sockopt(so, sopt, inp, tp, rack));
9034 	} else if (sopt->sopt_dir == SOPT_GET) {
9035 		return (rack_get_sockopt(so, sopt, inp, tp, rack));
9036 	}
9037 out:
9038 	INP_WUNLOCK(inp);
9039 	return (error);
9040 }
9041 
9042 
9043 struct tcp_function_block __tcp_rack = {
9044 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
9045 	.tfb_tcp_output = rack_output,
9046 	.tfb_tcp_do_segment = rack_do_segment,
9047 	.tfb_tcp_hpts_do_segment = rack_hpts_do_segment,
9048 	.tfb_tcp_ctloutput = rack_ctloutput,
9049 	.tfb_tcp_fb_init = rack_init,
9050 	.tfb_tcp_fb_fini = rack_fini,
9051 	.tfb_tcp_timer_stop_all = rack_stopall,
9052 	.tfb_tcp_timer_activate = rack_timer_activate,
9053 	.tfb_tcp_timer_active = rack_timer_active,
9054 	.tfb_tcp_timer_stop = rack_timer_stop,
9055 	.tfb_tcp_rexmit_tmr = rack_remxt_tmr,
9056 	.tfb_tcp_handoff_ok = rack_handoff_ok
9057 };
9058 
9059 static const char *rack_stack_names[] = {
9060 	__XSTRING(STACKNAME),
9061 #ifdef STACKALIAS
9062 	__XSTRING(STACKALIAS),
9063 #endif
9064 };
9065 
9066 static int
9067 rack_ctor(void *mem, int32_t size, void *arg, int32_t how)
9068 {
9069 	memset(mem, 0, size);
9070 	return (0);
9071 }
9072 
9073 static void
9074 rack_dtor(void *mem, int32_t size, void *arg)
9075 {
9076 
9077 }
9078 
9079 static bool rack_mod_inited = false;
9080 
9081 static int
9082 tcp_addrack(module_t mod, int32_t type, void *data)
9083 {
9084 	int32_t err = 0;
9085 	int num_stacks;
9086 
9087 	switch (type) {
9088 	case MOD_LOAD:
9089 		rack_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
9090 		    sizeof(struct rack_sendmap),
9091 		    rack_ctor, rack_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
9092 
9093 		rack_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
9094 		    sizeof(struct tcp_rack),
9095 		    rack_ctor, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
9096 
9097 		sysctl_ctx_init(&rack_sysctl_ctx);
9098 		rack_sysctl_root = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
9099 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
9100 		    OID_AUTO,
9101 		    __XSTRING(STACKNAME),
9102 		    CTLFLAG_RW, 0,
9103 		    "");
9104 		if (rack_sysctl_root == NULL) {
9105 			printf("Failed to add sysctl node\n");
9106 			err = EFAULT;
9107 			goto free_uma;
9108 		}
9109 		rack_init_sysctls();
9110 		num_stacks = nitems(rack_stack_names);
9111 		err = register_tcp_functions_as_names(&__tcp_rack, M_WAITOK,
9112 		    rack_stack_names, &num_stacks);
9113 		if (err) {
9114 			printf("Failed to register %s stack name for "
9115 			    "%s module\n", rack_stack_names[num_stacks],
9116 			    __XSTRING(MODNAME));
9117 			sysctl_ctx_free(&rack_sysctl_ctx);
9118 free_uma:
9119 			uma_zdestroy(rack_zone);
9120 			uma_zdestroy(rack_pcb_zone);
9121 			rack_counter_destroy();
9122 			printf("Failed to register rack module -- err:%d\n", err);
9123 			return (err);
9124 		}
9125 		rack_mod_inited = true;
9126 		break;
9127 	case MOD_QUIESCE:
9128 		err = deregister_tcp_functions(&__tcp_rack, true, false);
9129 		break;
9130 	case MOD_UNLOAD:
9131 		err = deregister_tcp_functions(&__tcp_rack, false, true);
9132 		if (err == EBUSY)
9133 			break;
9134 		if (rack_mod_inited) {
9135 			uma_zdestroy(rack_zone);
9136 			uma_zdestroy(rack_pcb_zone);
9137 			sysctl_ctx_free(&rack_sysctl_ctx);
9138 			rack_counter_destroy();
9139 			rack_mod_inited = false;
9140 		}
9141 		err = 0;
9142 		break;
9143 	default:
9144 		return (EOPNOTSUPP);
9145 	}
9146 	return (err);
9147 }
9148 
9149 static moduledata_t tcp_rack = {
9150 	.name = __XSTRING(MODNAME),
9151 	.evhand = tcp_addrack,
9152 	.priv = 0
9153 };
9154 
9155 MODULE_VERSION(MODNAME, 1);
9156 DECLARE_MODULE(MODNAME, tcp_rack, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
9157 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
9158