xref: /freebsd/sys/netinet/tcp_stacks/rack.c (revision 3984400149a53982f1254cfaf7b73fd2acda460a)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_inet.h"
31 #include "opt_inet6.h"
32 #include "opt_ipsec.h"
33 #include "opt_tcpdebug.h"
34 #include "opt_ratelimit.h"
35 #include "opt_kern_tls.h"
36 #include <sys/param.h>
37 #include <sys/arb.h>
38 #include <sys/module.h>
39 #include <sys/kernel.h>
40 #ifdef TCP_HHOOK
41 #include <sys/hhook.h>
42 #endif
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>		/* for proc0 declaration */
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #else
58 #include <sys/tree.h>
59 #endif
60 #include <sys/refcount.h>
61 #include <sys/queue.h>
62 #include <sys/tim_filter.h>
63 #include <sys/smp.h>
64 #include <sys/kthread.h>
65 #include <sys/kern_prefetch.h>
66 #include <sys/protosw.h>
67 #ifdef TCP_ACCOUNTING
68 #include <sys/sched.h>
69 #include <machine/cpu.h>
70 #endif
71 #include <vm/uma.h>
72 
73 #include <net/route.h>
74 #include <net/route/nhop.h>
75 #include <net/vnet.h>
76 
77 #define TCPSTATES		/* for logging */
78 
79 #include <netinet/in.h>
80 #include <netinet/in_kdtrace.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
84 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
85 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet6/ip6_var.h>
89 #include <netinet/tcp.h>
90 #define	TCPOUTFLAGS
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_log_buf.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcp_hpts.h>
97 #include <netinet/tcp_ratelimit.h>
98 #include <netinet/tcp_accounting.h>
99 #include <netinet/tcpip.h>
100 #include <netinet/cc/cc.h>
101 #include <netinet/cc/cc_newreno.h>
102 #include <netinet/tcp_fastopen.h>
103 #include <netinet/tcp_lro.h>
104 #ifdef NETFLIX_SHARED_CWND
105 #include <netinet/tcp_shared_cwnd.h>
106 #endif
107 #ifdef TCPDEBUG
108 #include <netinet/tcp_debug.h>
109 #endif				/* TCPDEBUG */
110 #ifdef TCP_OFFLOAD
111 #include <netinet/tcp_offload.h>
112 #endif
113 #ifdef INET6
114 #include <netinet6/tcp6_var.h>
115 #endif
116 
117 #include <netipsec/ipsec_support.h>
118 
119 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
120 #include <netipsec/ipsec.h>
121 #include <netipsec/ipsec6.h>
122 #endif				/* IPSEC */
123 
124 #include <netinet/udp.h>
125 #include <netinet/udp_var.h>
126 #include <machine/in_cksum.h>
127 
128 #ifdef MAC
129 #include <security/mac/mac_framework.h>
130 #endif
131 #include "sack_filter.h"
132 #include "tcp_rack.h"
133 #include "rack_bbr_common.h"
134 
135 uma_zone_t rack_zone;
136 uma_zone_t rack_pcb_zone;
137 
138 #ifndef TICKS2SBT
139 #define	TICKS2SBT(__t)	(tick_sbt * ((sbintime_t)(__t)))
140 #endif
141 
142 VNET_DECLARE(uint32_t, newreno_beta);
143 VNET_DECLARE(uint32_t, newreno_beta_ecn);
144 #define V_newreno_beta VNET(newreno_beta)
145 #define V_newreno_beta_ecn VNET(newreno_beta_ecn)
146 
147 
148 MALLOC_DEFINE(M_TCPFSB, "tcp_fsb", "TCP fast send block");
149 MALLOC_DEFINE(M_TCPDO, "tcp_do", "TCP deferred options");
150 
151 struct sysctl_ctx_list rack_sysctl_ctx;
152 struct sysctl_oid *rack_sysctl_root;
153 
154 #define CUM_ACKED 1
155 #define SACKED 2
156 
157 /*
158  * The RACK module incorporates a number of
159  * TCP ideas that have been put out into the IETF
160  * over the last few years:
161  * - Matt Mathis's Rate Halving which slowly drops
162  *    the congestion window so that the ack clock can
163  *    be maintained during a recovery.
164  * - Yuchung Cheng's RACK TCP (for which its named) that
165  *    will stop us using the number of dup acks and instead
166  *    use time as the gage of when we retransmit.
167  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
168  *    of Dukkipati et.al.
169  * RACK depends on SACK, so if an endpoint arrives that
170  * cannot do SACK the state machine below will shuttle the
171  * connection back to using the "default" TCP stack that is
172  * in FreeBSD.
173  *
174  * To implement RACK the original TCP stack was first decomposed
175  * into a functional state machine with individual states
176  * for each of the possible TCP connection states. The do_segement
177  * functions role in life is to mandate the connection supports SACK
178  * initially and then assure that the RACK state matches the conenction
179  * state before calling the states do_segment function. Each
180  * state is simplified due to the fact that the original do_segment
181  * has been decomposed and we *know* what state we are in (no
182  * switches on the state) and all tests for SACK are gone. This
183  * greatly simplifies what each state does.
184  *
185  * TCP output is also over-written with a new version since it
186  * must maintain the new rack scoreboard.
187  *
188  */
189 static int32_t rack_tlp_thresh = 1;
190 static int32_t rack_tlp_limit = 2;	/* No more than 2 TLPs w-out new data */
191 static int32_t rack_tlp_use_greater = 1;
192 static int32_t rack_reorder_thresh = 2;
193 static int32_t rack_reorder_fade = 60000000;	/* 0 - never fade, def 60,000,000
194 						 * - 60 seconds */
195 static uint8_t rack_req_measurements = 1;
196 /* Attack threshold detections */
197 static uint32_t rack_highest_sack_thresh_seen = 0;
198 static uint32_t rack_highest_move_thresh_seen = 0;
199 static int32_t rack_enable_hw_pacing = 0; /* Due to CCSP keep it off by default */
200 static int32_t rack_hw_pace_extra_slots = 2;	/* 2 extra MSS time betweens */
201 static int32_t rack_hw_rate_caps = 1; /* 1; */
202 static int32_t rack_hw_rate_min = 0; /* 1500000;*/
203 static int32_t rack_hw_rate_to_low = 0; /* 1200000; */
204 static int32_t rack_hw_up_only = 1;
205 static int32_t rack_stats_gets_ms_rtt = 1;
206 static int32_t rack_prr_addbackmax = 2;
207 
208 static int32_t rack_pkt_delay = 1000;
209 static int32_t rack_send_a_lot_in_prr = 1;
210 static int32_t rack_min_to = 1000;	/* Number of microsecond  min timeout */
211 static int32_t rack_verbose_logging = 0;
212 static int32_t rack_ignore_data_after_close = 1;
213 static int32_t rack_enable_shared_cwnd = 1;
214 static int32_t rack_use_cmp_acks = 1;
215 static int32_t rack_use_fsb = 1;
216 static int32_t rack_use_rfo = 1;
217 static int32_t rack_use_rsm_rfo = 1;
218 static int32_t rack_max_abc_post_recovery = 2;
219 static int32_t rack_client_low_buf = 0;
220 static int32_t rack_dsack_std_based = 0x3;	/* bit field bit 1 sets rc_rack_tmr_std_based and bit 2 sets rc_rack_use_dsack */
221 #ifdef TCP_ACCOUNTING
222 static int32_t rack_tcp_accounting = 0;
223 #endif
224 static int32_t rack_limits_scwnd = 1;
225 static int32_t rack_enable_mqueue_for_nonpaced = 0;
226 static int32_t rack_disable_prr = 0;
227 static int32_t use_rack_rr = 1;
228 static int32_t rack_non_rxt_use_cr = 0; /* does a non-rxt in recovery use the configured rate (ss/ca)? */
229 static int32_t rack_persist_min = 250000;	/* 250usec */
230 static int32_t rack_persist_max = 2000000;	/* 2 Second in usec's */
231 static int32_t rack_sack_not_required = 1;	/* set to one to allow non-sack to use rack */
232 static int32_t rack_default_init_window = 0;	/* Use system default */
233 static int32_t rack_limit_time_with_srtt = 0;
234 static int32_t rack_autosndbuf_inc = 20;	/* In percentage form */
235 static int32_t rack_enobuf_hw_boost_mult = 2;	/* How many times the hw rate we boost slot using time_between */
236 static int32_t rack_enobuf_hw_max = 12000;	/* 12 ms in usecs */
237 static int32_t rack_enobuf_hw_min = 10000;	/* 10 ms in usecs */
238 static int32_t rack_hw_rwnd_factor = 2;		/* How many max_segs the rwnd must be before we hold off sending */
239 /*
240  * Currently regular tcp has a rto_min of 30ms
241  * the backoff goes 12 times so that ends up
242  * being a total of 122.850 seconds before a
243  * connection is killed.
244  */
245 static uint32_t rack_def_data_window = 20;
246 static uint32_t rack_goal_bdp = 2;
247 static uint32_t rack_min_srtts = 1;
248 static uint32_t rack_min_measure_usec = 0;
249 static int32_t rack_tlp_min = 10000;	/* 10ms */
250 static int32_t rack_rto_min = 30000;	/* 30,000 usec same as main freebsd */
251 static int32_t rack_rto_max = 4000000;	/* 4 seconds in usec's */
252 static const int32_t rack_free_cache = 2;
253 static int32_t rack_hptsi_segments = 40;
254 static int32_t rack_rate_sample_method = USE_RTT_LOW;
255 static int32_t rack_pace_every_seg = 0;
256 static int32_t rack_delayed_ack_time = 40000;	/* 40ms in usecs */
257 static int32_t rack_slot_reduction = 4;
258 static int32_t rack_wma_divisor = 8;		/* For WMA calculation */
259 static int32_t rack_cwnd_block_ends_measure = 0;
260 static int32_t rack_rwnd_block_ends_measure = 0;
261 static int32_t rack_def_profile = 0;
262 
263 static int32_t rack_lower_cwnd_at_tlp = 0;
264 static int32_t rack_limited_retran = 0;
265 static int32_t rack_always_send_oldest = 0;
266 static int32_t rack_tlp_threshold_use = TLP_USE_TWO_ONE;
267 
268 static uint16_t rack_per_of_gp_ss = 250;	/* 250 % slow-start */
269 static uint16_t rack_per_of_gp_ca = 200;	/* 200 % congestion-avoidance */
270 static uint16_t rack_per_of_gp_rec = 200;	/* 200 % of bw */
271 
272 /* Probertt */
273 static uint16_t rack_per_of_gp_probertt = 60;	/* 60% of bw */
274 static uint16_t rack_per_of_gp_lowthresh = 40;	/* 40% is bottom */
275 static uint16_t rack_per_of_gp_probertt_reduce = 10; /* 10% reduction */
276 static uint16_t rack_atexit_prtt_hbp = 130;	/* Clamp to 130% on exit prtt if highly buffered path */
277 static uint16_t rack_atexit_prtt = 130;	/* Clamp to 100% on exit prtt if non highly buffered path */
278 
279 static uint32_t rack_max_drain_wait = 2;	/* How man gp srtt's before we give up draining */
280 static uint32_t rack_must_drain = 1;		/* How many GP srtt's we *must* wait */
281 static uint32_t rack_probertt_use_min_rtt_entry = 1;	/* Use the min to calculate the goal else gp_srtt */
282 static uint32_t rack_probertt_use_min_rtt_exit = 0;
283 static uint32_t rack_probe_rtt_sets_cwnd = 0;
284 static uint32_t rack_probe_rtt_safety_val = 2000000;	/* No more than 2 sec in probe-rtt */
285 static uint32_t rack_time_between_probertt = 9600000;	/* 9.6 sec in usecs */
286 static uint32_t rack_probertt_gpsrtt_cnt_mul = 0;	/* How many srtt periods does probe-rtt last top fraction */
287 static uint32_t rack_probertt_gpsrtt_cnt_div = 0;	/* How many srtt periods does probe-rtt last bottom fraction */
288 static uint32_t rack_min_probertt_hold = 40000;		/* Equal to delayed ack time */
289 static uint32_t rack_probertt_filter_life = 10000000;
290 static uint32_t rack_probertt_lower_within = 10;
291 static uint32_t rack_min_rtt_movement = 250000;	/* Must move at least 250ms (in microseconds)  to count as a lowering */
292 static int32_t rack_pace_one_seg = 0;		/* Shall we pace for less than 1.4Meg 1MSS at a time */
293 static int32_t rack_probertt_clear_is = 1;
294 static int32_t rack_max_drain_hbp = 1;		/* Extra drain times gpsrtt for highly buffered paths */
295 static int32_t rack_hbp_thresh = 3;		/* what is the divisor max_rtt/min_rtt to decided a hbp */
296 
297 /* Part of pacing */
298 static int32_t rack_max_per_above = 30;		/* When we go to increment stop if above 100+this% */
299 
300 /* Timely information */
301 /* Combine these two gives the range of 'no change' to bw */
302 /* ie the up/down provide the upper and lower bound */
303 static int32_t rack_gp_per_bw_mul_up = 2;	/* 2% */
304 static int32_t rack_gp_per_bw_mul_down = 4;	/* 4% */
305 static int32_t rack_gp_rtt_maxmul = 3;		/* 3 x maxmin */
306 static int32_t rack_gp_rtt_minmul = 1;		/* minrtt + (minrtt/mindiv) is lower rtt */
307 static int32_t rack_gp_rtt_mindiv = 4;		/* minrtt + (minrtt * minmul/mindiv) is lower rtt */
308 static int32_t rack_gp_decrease_per = 20;	/* 20% decrease in multipler */
309 static int32_t rack_gp_increase_per = 2;	/* 2% increase in multipler */
310 static int32_t rack_per_lower_bound = 50;	/* Don't allow to drop below this multiplier */
311 static int32_t rack_per_upper_bound_ss = 0;	/* Don't allow SS to grow above this */
312 static int32_t rack_per_upper_bound_ca = 0;	/* Don't allow CA to grow above this */
313 static int32_t rack_do_dyn_mul = 0;		/* Are the rack gp multipliers dynamic */
314 static int32_t rack_gp_no_rec_chg = 1;		/* Prohibit recovery from reducing it's multiplier */
315 static int32_t rack_timely_dec_clear = 6;	/* Do we clear decrement count at a value (6)? */
316 static int32_t rack_timely_max_push_rise = 3;	/* One round of pushing */
317 static int32_t rack_timely_max_push_drop = 3;	/* Three round of pushing */
318 static int32_t rack_timely_min_segs = 4;	/* 4 segment minimum */
319 static int32_t rack_use_max_for_nobackoff = 0;
320 static int32_t rack_timely_int_timely_only = 0;	/* do interim timely's only use the timely algo (no b/w changes)? */
321 static int32_t rack_timely_no_stopping = 0;
322 static int32_t rack_down_raise_thresh = 100;
323 static int32_t rack_req_segs = 1;
324 static uint64_t rack_bw_rate_cap = 0;
325 
326 /* Weird delayed ack mode */
327 static int32_t rack_use_imac_dack = 0;
328 /* Rack specific counters */
329 counter_u64_t rack_badfr;
330 counter_u64_t rack_badfr_bytes;
331 counter_u64_t rack_rtm_prr_retran;
332 counter_u64_t rack_rtm_prr_newdata;
333 counter_u64_t rack_timestamp_mismatch;
334 counter_u64_t rack_reorder_seen;
335 counter_u64_t rack_paced_segments;
336 counter_u64_t rack_unpaced_segments;
337 counter_u64_t rack_calc_zero;
338 counter_u64_t rack_calc_nonzero;
339 counter_u64_t rack_saw_enobuf;
340 counter_u64_t rack_saw_enobuf_hw;
341 counter_u64_t rack_saw_enetunreach;
342 counter_u64_t rack_per_timer_hole;
343 counter_u64_t rack_large_ackcmp;
344 counter_u64_t rack_small_ackcmp;
345 #ifdef INVARIANTS
346 counter_u64_t rack_adjust_map_bw;
347 #endif
348 /* Tail loss probe counters */
349 counter_u64_t rack_tlp_tot;
350 counter_u64_t rack_tlp_newdata;
351 counter_u64_t rack_tlp_retran;
352 counter_u64_t rack_tlp_retran_bytes;
353 counter_u64_t rack_tlp_retran_fail;
354 counter_u64_t rack_to_tot;
355 counter_u64_t rack_to_arm_rack;
356 counter_u64_t rack_to_arm_tlp;
357 counter_u64_t rack_hot_alloc;
358 counter_u64_t rack_to_alloc;
359 counter_u64_t rack_to_alloc_hard;
360 counter_u64_t rack_to_alloc_emerg;
361 counter_u64_t rack_to_alloc_limited;
362 counter_u64_t rack_alloc_limited_conns;
363 counter_u64_t rack_split_limited;
364 
365 #define MAX_NUM_OF_CNTS 13
366 counter_u64_t rack_proc_comp_ack[MAX_NUM_OF_CNTS];
367 counter_u64_t rack_multi_single_eq;
368 counter_u64_t rack_proc_non_comp_ack;
369 
370 counter_u64_t rack_fto_send;
371 counter_u64_t rack_fto_rsm_send;
372 counter_u64_t rack_nfto_resend;
373 counter_u64_t rack_non_fto_send;
374 counter_u64_t rack_extended_rfo;
375 
376 counter_u64_t rack_sack_proc_all;
377 counter_u64_t rack_sack_proc_short;
378 counter_u64_t rack_sack_proc_restart;
379 counter_u64_t rack_sack_attacks_detected;
380 counter_u64_t rack_sack_attacks_reversed;
381 counter_u64_t rack_sack_used_next_merge;
382 counter_u64_t rack_sack_splits;
383 counter_u64_t rack_sack_used_prev_merge;
384 counter_u64_t rack_sack_skipped_acked;
385 counter_u64_t rack_ack_total;
386 counter_u64_t rack_express_sack;
387 counter_u64_t rack_sack_total;
388 counter_u64_t rack_move_none;
389 counter_u64_t rack_move_some;
390 
391 counter_u64_t rack_used_tlpmethod;
392 counter_u64_t rack_used_tlpmethod2;
393 counter_u64_t rack_enter_tlp_calc;
394 counter_u64_t rack_input_idle_reduces;
395 counter_u64_t rack_collapsed_win;
396 counter_u64_t rack_tlp_does_nada;
397 counter_u64_t rack_try_scwnd;
398 counter_u64_t rack_hw_pace_init_fail;
399 counter_u64_t rack_hw_pace_lost;
400 counter_u64_t rack_sbsndptr_right;
401 counter_u64_t rack_sbsndptr_wrong;
402 
403 /* Temp CPU counters */
404 counter_u64_t rack_find_high;
405 
406 counter_u64_t rack_progress_drops;
407 counter_u64_t rack_out_size[TCP_MSS_ACCT_SIZE];
408 counter_u64_t rack_opts_arry[RACK_OPTS_SIZE];
409 
410 
411 #define	RACK_REXMTVAL(tp) max(rack_rto_min, ((tp)->t_srtt + ((tp)->t_rttvar << 2)))
412 
413 #define	RACK_TCPT_RANGESET(tv, value, tvmin, tvmax, slop) do {	\
414 	(tv) = (value) + slop;	 \
415 	if ((u_long)(tv) < (u_long)(tvmin)) \
416 		(tv) = (tvmin); \
417 	if ((u_long)(tv) > (u_long)(tvmax)) \
418 		(tv) = (tvmax); \
419 } while (0)
420 
421 static void
422 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line);
423 
424 static int
425 rack_process_ack(struct mbuf *m, struct tcphdr *th,
426     struct socket *so, struct tcpcb *tp, struct tcpopt *to,
427     uint32_t tiwin, int32_t tlen, int32_t * ofia, int32_t thflags, int32_t * ret_val);
428 static int
429 rack_process_data(struct mbuf *m, struct tcphdr *th,
430     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
431     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt);
432 static void
433 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack,
434    uint32_t th_ack, uint16_t nsegs, uint16_t type, int32_t recovery);
435 static struct rack_sendmap *rack_alloc(struct tcp_rack *rack);
436 static struct rack_sendmap *rack_alloc_limit(struct tcp_rack *rack,
437     uint8_t limit_type);
438 static struct rack_sendmap *
439 rack_check_recovery_mode(struct tcpcb *tp,
440     uint32_t tsused);
441 static void
442 rack_cong_signal(struct tcpcb *tp,
443 		 uint32_t type, uint32_t ack);
444 static void rack_counter_destroy(void);
445 static int
446 rack_ctloutput(struct socket *so, struct sockopt *sopt,
447     struct inpcb *inp, struct tcpcb *tp);
448 static int32_t rack_ctor(void *mem, int32_t size, void *arg, int32_t how);
449 static void
450 rack_set_pace_segments(struct tcpcb *tp, struct tcp_rack *rack, uint32_t line, uint64_t *fill_override);
451 static void
452 rack_do_segment(struct mbuf *m, struct tcphdr *th,
453     struct socket *so, struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
454     uint8_t iptos);
455 static void rack_dtor(void *mem, int32_t size, void *arg);
456 static void
457 rack_log_alt_to_to_cancel(struct tcp_rack *rack,
458     uint32_t flex1, uint32_t flex2,
459     uint32_t flex3, uint32_t flex4,
460     uint32_t flex5, uint32_t flex6,
461     uint16_t flex7, uint8_t mod);
462 
463 static void
464 rack_log_pacing_delay_calc(struct tcp_rack *rack, uint32_t len, uint32_t slot,
465    uint64_t bw_est, uint64_t bw, uint64_t len_time, int method, int line,
466    struct rack_sendmap *rsm, uint8_t quality);
467 static struct rack_sendmap *
468 rack_find_high_nonack(struct tcp_rack *rack,
469     struct rack_sendmap *rsm);
470 static struct rack_sendmap *rack_find_lowest_rsm(struct tcp_rack *rack);
471 static void rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm);
472 static void rack_fini(struct tcpcb *tp, int32_t tcb_is_purged);
473 static int
474 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
475     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
476 static void
477 rack_do_goodput_measurement(struct tcpcb *tp, struct tcp_rack *rack,
478 			    tcp_seq th_ack, int line, uint8_t quality);
479 static uint32_t
480 rack_get_pacing_len(struct tcp_rack *rack, uint64_t bw, uint32_t mss);
481 static int32_t rack_handoff_ok(struct tcpcb *tp);
482 static int32_t rack_init(struct tcpcb *tp);
483 static void rack_init_sysctls(void);
484 static void
485 rack_log_ack(struct tcpcb *tp, struct tcpopt *to,
486     struct tcphdr *th, int entered_rec, int dup_ack_struck);
487 static void
488 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
489     uint32_t seq_out, uint8_t th_flags, int32_t err, uint64_t ts,
490     struct rack_sendmap *hintrsm, uint16_t add_flags, struct mbuf *s_mb, uint32_t s_moff, int hw_tls);
491 
492 static void
493 rack_log_sack_passed(struct tcpcb *tp, struct tcp_rack *rack,
494     struct rack_sendmap *rsm);
495 static void rack_log_to_event(struct tcp_rack *rack, int32_t to_num, struct rack_sendmap *rsm);
496 static int32_t rack_output(struct tcpcb *tp);
497 
498 static uint32_t
499 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack,
500     struct sackblk *sack, struct tcpopt *to, struct rack_sendmap **prsm,
501     uint32_t cts, int *moved_two);
502 static void rack_post_recovery(struct tcpcb *tp, uint32_t th_seq);
503 static void rack_remxt_tmr(struct tcpcb *tp);
504 static int
505 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
506     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack);
507 static void rack_set_state(struct tcpcb *tp, struct tcp_rack *rack);
508 static int32_t rack_stopall(struct tcpcb *tp);
509 static void
510 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type,
511     uint32_t delta);
512 static int32_t rack_timer_active(struct tcpcb *tp, uint32_t timer_type);
513 static void rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line);
514 static void rack_timer_stop(struct tcpcb *tp, uint32_t timer_type);
515 static uint32_t
516 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
517     struct rack_sendmap *rsm, uint64_t ts, int32_t * lenp, uint16_t add_flag);
518 static void
519 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
520     struct rack_sendmap *rsm, uint64_t ts, uint16_t add_flag);
521 static int
522 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
523     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, tcp_seq th_ack);
524 static int32_t tcp_addrack(module_t mod, int32_t type, void *data);
525 static int
526 rack_do_close_wait(struct mbuf *m, struct tcphdr *th,
527     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
528     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
529 static int
530 rack_do_closing(struct mbuf *m, struct tcphdr *th,
531     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
532     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
533 static int
534 rack_do_established(struct mbuf *m, struct tcphdr *th,
535     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
536     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
537 static int
538 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th,
539     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
540     int32_t tlen, uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos);
541 static int
542 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th,
543     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
544     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
545 static int
546 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th,
547     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
548     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
549 static int
550 rack_do_lastack(struct mbuf *m, struct tcphdr *th,
551     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
552     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
553 static int
554 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th,
555     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
556     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
557 static int
558 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th,
559     struct socket *so, struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen,
560     int32_t tlen, uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos);
561 struct rack_sendmap *
562 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack,
563     uint32_t tsused);
564 static void tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt,
565     uint32_t len, uint32_t us_tim, int confidence, struct rack_sendmap *rsm, uint16_t rtrcnt);
566 static void
567      tcp_rack_partialack(struct tcpcb *tp);
568 static int
569 rack_set_profile(struct tcp_rack *rack, int prof);
570 static void
571 rack_apply_deferred_options(struct tcp_rack *rack);
572 
573 int32_t rack_clear_counter=0;
574 
575 static void
576 rack_set_cc_pacing(struct tcp_rack *rack)
577 {
578 	struct sockopt sopt;
579 	struct cc_newreno_opts opt;
580 	struct newreno old, *ptr;
581 	struct tcpcb *tp;
582 	int error;
583 
584 	if (rack->rc_pacing_cc_set)
585 		return;
586 
587 	tp = rack->rc_tp;
588 	if (tp->cc_algo == NULL) {
589 		/* Tcb is leaving */
590 		printf("No cc algorithm?\n");
591 		return;
592 	}
593 	rack->rc_pacing_cc_set = 1;
594 	if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
595 		/* Not new-reno we can't play games with beta! */
596 		goto out;
597 	}
598 	ptr = ((struct newreno *)tp->ccv->cc_data);
599 	if (CC_ALGO(tp)->ctl_output == NULL)  {
600 		/* Huh, why does new_reno no longer have a set function? */
601 		printf("no ctl_output for algo:%s\n", tp->cc_algo->name);
602 		goto out;
603 	}
604 	if (ptr == NULL) {
605 		/* Just the default values */
606 		old.beta = V_newreno_beta_ecn;
607 		old.beta_ecn = V_newreno_beta_ecn;
608 		old.newreno_flags = 0;
609 	} else {
610 		old.beta = ptr->beta;
611 		old.beta_ecn = ptr->beta_ecn;
612 		old.newreno_flags = ptr->newreno_flags;
613 	}
614 	sopt.sopt_valsize = sizeof(struct cc_newreno_opts);
615 	sopt.sopt_dir = SOPT_SET;
616 	opt.name = CC_NEWRENO_BETA;
617 	opt.val = rack->r_ctl.rc_saved_beta.beta;
618 	error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
619 	if (error)  {
620 		printf("Error returned by ctl_output %d\n", error);
621 		goto out;
622 	}
623 	/*
624 	 * Hack alert we need to set in our newreno_flags
625 	 * so that Abe behavior is also applied.
626 	 */
627 	((struct newreno *)tp->ccv->cc_data)->newreno_flags = CC_NEWRENO_BETA_ECN;
628 	opt.name = CC_NEWRENO_BETA_ECN;
629 	opt.val = rack->r_ctl.rc_saved_beta.beta_ecn;
630 	error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
631 	if (error) {
632 		printf("Error returned by ctl_output %d\n", error);
633 		goto out;
634 	}
635 	/* Save off the original values for restoral */
636 	memcpy(&rack->r_ctl.rc_saved_beta, &old, sizeof(struct newreno));
637 out:
638 	if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
639 		union tcp_log_stackspecific log;
640 		struct timeval tv;
641 
642 		ptr = ((struct newreno *)tp->ccv->cc_data);
643 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
644 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
645 		if (ptr) {
646 			log.u_bbr.flex1 = ptr->beta;
647 			log.u_bbr.flex2 = ptr->beta_ecn;
648 			log.u_bbr.flex3 = ptr->newreno_flags;
649 		}
650 		log.u_bbr.flex4 = rack->r_ctl.rc_saved_beta.beta;
651 		log.u_bbr.flex5 = rack->r_ctl.rc_saved_beta.beta_ecn;
652 		log.u_bbr.flex6 = rack->r_ctl.rc_saved_beta.newreno_flags;
653 		log.u_bbr.flex7 = rack->gp_ready;
654 		log.u_bbr.flex7 <<= 1;
655 		log.u_bbr.flex7 |= rack->use_fixed_rate;
656 		log.u_bbr.flex7 <<= 1;
657 		log.u_bbr.flex7 |= rack->rc_pacing_cc_set;
658 		log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
659 		log.u_bbr.flex8 = 3;
660 		tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, error,
661 			       0, &log, false, NULL, NULL, 0, &tv);
662 	}
663 }
664 
665 static void
666 rack_undo_cc_pacing(struct tcp_rack *rack)
667 {
668 	struct newreno old, *ptr;
669 	struct tcpcb *tp;
670 
671 	if (rack->rc_pacing_cc_set == 0)
672 		return;
673 	tp = rack->rc_tp;
674 	rack->rc_pacing_cc_set = 0;
675 	if (tp->cc_algo == NULL)
676 		/* Tcb is leaving */
677 		return;
678 	if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
679 		/* Not new-reno nothing to do! */
680 		return;
681 	}
682 	ptr = ((struct newreno *)tp->ccv->cc_data);
683 	if (ptr == NULL) {
684 		/*
685 		 * This happens at rack_fini() if the
686 		 * cc module gets freed on us. In that
687 		 * case we loose our "new" settings but
688 		 * thats ok, since the tcb is going away anyway.
689 		 */
690 		return;
691 	}
692 	/* Grab out our set values */
693 	memcpy(&old, ptr, sizeof(struct newreno));
694 	/* Copy back in the original values */
695 	memcpy(ptr, &rack->r_ctl.rc_saved_beta, sizeof(struct newreno));
696 	/* Now save back the values we had set in (for when pacing is restored) */
697 	memcpy(&rack->r_ctl.rc_saved_beta, &old, sizeof(struct newreno));
698 	if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
699 		union tcp_log_stackspecific log;
700 		struct timeval tv;
701 
702 		ptr = ((struct newreno *)tp->ccv->cc_data);
703 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
704 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
705 		log.u_bbr.flex1 = ptr->beta;
706 		log.u_bbr.flex2 = ptr->beta_ecn;
707 		log.u_bbr.flex3 = ptr->newreno_flags;
708 		log.u_bbr.flex4 = rack->r_ctl.rc_saved_beta.beta;
709 		log.u_bbr.flex5 = rack->r_ctl.rc_saved_beta.beta_ecn;
710 		log.u_bbr.flex6 = rack->r_ctl.rc_saved_beta.newreno_flags;
711 		log.u_bbr.flex7 = rack->gp_ready;
712 		log.u_bbr.flex7 <<= 1;
713 		log.u_bbr.flex7 |= rack->use_fixed_rate;
714 		log.u_bbr.flex7 <<= 1;
715 		log.u_bbr.flex7 |= rack->rc_pacing_cc_set;
716 		log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
717 		log.u_bbr.flex8 = 4;
718 		tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
719 			       0, &log, false, NULL, NULL, 0, &tv);
720 	}
721 }
722 
723 #ifdef NETFLIX_PEAKRATE
724 static inline void
725 rack_update_peakrate_thr(struct tcpcb *tp)
726 {
727 	/* Keep in mind that t_maxpeakrate is in B/s. */
728 	uint64_t peak;
729 	peak = uqmax((tp->t_maxseg * 2),
730 		     (((uint64_t)tp->t_maxpeakrate * (uint64_t)(tp->t_srtt)) / (uint64_t)HPTS_USEC_IN_SEC));
731 	tp->t_peakrate_thr = (uint32_t)uqmin(peak, UINT32_MAX);
732 }
733 #endif
734 
735 static int
736 sysctl_rack_clear(SYSCTL_HANDLER_ARGS)
737 {
738 	uint32_t stat;
739 	int32_t error;
740 	int i;
741 
742 	error = SYSCTL_OUT(req, &rack_clear_counter, sizeof(uint32_t));
743 	if (error || req->newptr == NULL)
744 		return error;
745 
746 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
747 	if (error)
748 		return (error);
749 	if (stat == 1) {
750 #ifdef INVARIANTS
751 		printf("Clearing RACK counters\n");
752 #endif
753 		counter_u64_zero(rack_badfr);
754 		counter_u64_zero(rack_badfr_bytes);
755 		counter_u64_zero(rack_rtm_prr_retran);
756 		counter_u64_zero(rack_rtm_prr_newdata);
757 		counter_u64_zero(rack_timestamp_mismatch);
758 		counter_u64_zero(rack_reorder_seen);
759 		counter_u64_zero(rack_tlp_tot);
760 		counter_u64_zero(rack_tlp_newdata);
761 		counter_u64_zero(rack_tlp_retran);
762 		counter_u64_zero(rack_tlp_retran_bytes);
763 		counter_u64_zero(rack_tlp_retran_fail);
764 		counter_u64_zero(rack_to_tot);
765 		counter_u64_zero(rack_to_arm_rack);
766 		counter_u64_zero(rack_to_arm_tlp);
767 		counter_u64_zero(rack_paced_segments);
768 		counter_u64_zero(rack_calc_zero);
769 		counter_u64_zero(rack_calc_nonzero);
770 		counter_u64_zero(rack_unpaced_segments);
771 		counter_u64_zero(rack_saw_enobuf);
772 		counter_u64_zero(rack_saw_enobuf_hw);
773 		counter_u64_zero(rack_saw_enetunreach);
774 		counter_u64_zero(rack_per_timer_hole);
775 		counter_u64_zero(rack_large_ackcmp);
776 		counter_u64_zero(rack_small_ackcmp);
777 #ifdef INVARIANTS
778 		counter_u64_zero(rack_adjust_map_bw);
779 #endif
780 		counter_u64_zero(rack_to_alloc_hard);
781 		counter_u64_zero(rack_to_alloc_emerg);
782 		counter_u64_zero(rack_sack_proc_all);
783 		counter_u64_zero(rack_fto_send);
784 		counter_u64_zero(rack_fto_rsm_send);
785 		counter_u64_zero(rack_extended_rfo);
786 		counter_u64_zero(rack_hw_pace_init_fail);
787 		counter_u64_zero(rack_hw_pace_lost);
788 		counter_u64_zero(rack_sbsndptr_wrong);
789 		counter_u64_zero(rack_sbsndptr_right);
790 		counter_u64_zero(rack_non_fto_send);
791 		counter_u64_zero(rack_nfto_resend);
792 		counter_u64_zero(rack_sack_proc_short);
793 		counter_u64_zero(rack_sack_proc_restart);
794 		counter_u64_zero(rack_to_alloc);
795 		counter_u64_zero(rack_to_alloc_limited);
796 		counter_u64_zero(rack_alloc_limited_conns);
797 		counter_u64_zero(rack_split_limited);
798 		for (i = 0; i < MAX_NUM_OF_CNTS; i++) {
799 			counter_u64_zero(rack_proc_comp_ack[i]);
800 		}
801 		counter_u64_zero(rack_multi_single_eq);
802 		counter_u64_zero(rack_proc_non_comp_ack);
803 		counter_u64_zero(rack_find_high);
804 		counter_u64_zero(rack_sack_attacks_detected);
805 		counter_u64_zero(rack_sack_attacks_reversed);
806 		counter_u64_zero(rack_sack_used_next_merge);
807 		counter_u64_zero(rack_sack_used_prev_merge);
808 		counter_u64_zero(rack_sack_splits);
809 		counter_u64_zero(rack_sack_skipped_acked);
810 		counter_u64_zero(rack_ack_total);
811 		counter_u64_zero(rack_express_sack);
812 		counter_u64_zero(rack_sack_total);
813 		counter_u64_zero(rack_move_none);
814 		counter_u64_zero(rack_move_some);
815 		counter_u64_zero(rack_used_tlpmethod);
816 		counter_u64_zero(rack_used_tlpmethod2);
817 		counter_u64_zero(rack_enter_tlp_calc);
818 		counter_u64_zero(rack_progress_drops);
819 		counter_u64_zero(rack_tlp_does_nada);
820 		counter_u64_zero(rack_try_scwnd);
821 		counter_u64_zero(rack_collapsed_win);
822 	}
823 	rack_clear_counter = 0;
824 	return (0);
825 }
826 
827 static void
828 rack_init_sysctls(void)
829 {
830 	int i;
831 	struct sysctl_oid *rack_counters;
832 	struct sysctl_oid *rack_attack;
833 	struct sysctl_oid *rack_pacing;
834 	struct sysctl_oid *rack_timely;
835 	struct sysctl_oid *rack_timers;
836 	struct sysctl_oid *rack_tlp;
837 	struct sysctl_oid *rack_misc;
838 	struct sysctl_oid *rack_measure;
839 	struct sysctl_oid *rack_probertt;
840 	struct sysctl_oid *rack_hw_pacing;
841 
842 	rack_attack = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
843 	    SYSCTL_CHILDREN(rack_sysctl_root),
844 	    OID_AUTO,
845 	    "sack_attack",
846 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
847 	    "Rack Sack Attack Counters and Controls");
848 	rack_counters = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
849 	    SYSCTL_CHILDREN(rack_sysctl_root),
850 	    OID_AUTO,
851 	    "stats",
852 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
853 	    "Rack Counters");
854 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
855 	    SYSCTL_CHILDREN(rack_sysctl_root),
856 	    OID_AUTO, "rate_sample_method", CTLFLAG_RW,
857 	    &rack_rate_sample_method , USE_RTT_LOW,
858 	    "What method should we use for rate sampling 0=high, 1=low ");
859 	/* Probe rtt related controls */
860 	rack_probertt = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
861 	    SYSCTL_CHILDREN(rack_sysctl_root),
862 	    OID_AUTO,
863 	    "probertt",
864 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
865 	    "ProbeRTT related Controls");
866 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
867 	    SYSCTL_CHILDREN(rack_probertt),
868 	    OID_AUTO, "exit_per_hpb", CTLFLAG_RW,
869 	    &rack_atexit_prtt_hbp, 130,
870 	    "What percentage above goodput do we clamp CA/SS to at exit on high-BDP path 110%");
871 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
872 	    SYSCTL_CHILDREN(rack_probertt),
873 	    OID_AUTO, "exit_per_nonhpb", CTLFLAG_RW,
874 	    &rack_atexit_prtt, 130,
875 	    "What percentage above goodput do we clamp CA/SS to at exit on a non high-BDP path 100%");
876 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
877 	    SYSCTL_CHILDREN(rack_probertt),
878 	    OID_AUTO, "gp_per_mul", CTLFLAG_RW,
879 	    &rack_per_of_gp_probertt, 60,
880 	    "What percentage of goodput do we pace at in probertt");
881 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
882 	    SYSCTL_CHILDREN(rack_probertt),
883 	    OID_AUTO, "gp_per_reduce", CTLFLAG_RW,
884 	    &rack_per_of_gp_probertt_reduce, 10,
885 	    "What percentage of goodput do we reduce every gp_srtt");
886 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
887 	    SYSCTL_CHILDREN(rack_probertt),
888 	    OID_AUTO, "gp_per_low", CTLFLAG_RW,
889 	    &rack_per_of_gp_lowthresh, 40,
890 	    "What percentage of goodput do we allow the multiplier to fall to");
891 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
892 	    SYSCTL_CHILDREN(rack_probertt),
893 	    OID_AUTO, "time_between", CTLFLAG_RW,
894 	    & rack_time_between_probertt, 96000000,
895 	    "How many useconds between the lowest rtt falling must past before we enter probertt");
896 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
897 	    SYSCTL_CHILDREN(rack_probertt),
898 	    OID_AUTO, "safety", CTLFLAG_RW,
899 	    &rack_probe_rtt_safety_val, 2000000,
900 	    "If not zero, provides a maximum usecond that you can stay in probertt (2sec = 2000000)");
901 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
902 	    SYSCTL_CHILDREN(rack_probertt),
903 	    OID_AUTO, "sets_cwnd", CTLFLAG_RW,
904 	    &rack_probe_rtt_sets_cwnd, 0,
905 	    "Do we set the cwnd too (if always_lower is on)");
906 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
907 	    SYSCTL_CHILDREN(rack_probertt),
908 	    OID_AUTO, "maxdrainsrtts", CTLFLAG_RW,
909 	    &rack_max_drain_wait, 2,
910 	    "Maximum number of gp_srtt's to hold in drain waiting for flight to reach goal");
911 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
912 	    SYSCTL_CHILDREN(rack_probertt),
913 	    OID_AUTO, "mustdrainsrtts", CTLFLAG_RW,
914 	    &rack_must_drain, 1,
915 	    "We must drain this many gp_srtt's waiting for flight to reach goal");
916 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
917 	    SYSCTL_CHILDREN(rack_probertt),
918 	    OID_AUTO, "goal_use_min_entry", CTLFLAG_RW,
919 	    &rack_probertt_use_min_rtt_entry, 1,
920 	    "Should we use the min-rtt to calculate the goal rtt (else gp_srtt) at entry");
921 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
922 	    SYSCTL_CHILDREN(rack_probertt),
923 	    OID_AUTO, "goal_use_min_exit", CTLFLAG_RW,
924 	    &rack_probertt_use_min_rtt_exit, 0,
925 	    "How to set cwnd at exit, 0 - dynamic, 1 - use min-rtt, 2 - use curgprtt, 3 - entry gp-rtt");
926 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
927 	    SYSCTL_CHILDREN(rack_probertt),
928 	    OID_AUTO, "length_div", CTLFLAG_RW,
929 	    &rack_probertt_gpsrtt_cnt_div, 0,
930 	    "How many recent goodput srtt periods plus hold tim does probertt last (bottom of fraction)");
931 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
932 	    SYSCTL_CHILDREN(rack_probertt),
933 	    OID_AUTO, "length_mul", CTLFLAG_RW,
934 	    &rack_probertt_gpsrtt_cnt_mul, 0,
935 	    "How many recent goodput srtt periods plus hold tim does probertt last (top of fraction)");
936 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
937 	    SYSCTL_CHILDREN(rack_probertt),
938 	    OID_AUTO, "holdtim_at_target", CTLFLAG_RW,
939 	    &rack_min_probertt_hold, 200000,
940 	    "What is the minimum time we hold probertt at target");
941 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
942 	    SYSCTL_CHILDREN(rack_probertt),
943 	    OID_AUTO, "filter_life", CTLFLAG_RW,
944 	    &rack_probertt_filter_life, 10000000,
945 	    "What is the time for the filters life in useconds");
946 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
947 	    SYSCTL_CHILDREN(rack_probertt),
948 	    OID_AUTO, "lower_within", CTLFLAG_RW,
949 	    &rack_probertt_lower_within, 10,
950 	    "If the rtt goes lower within this percentage of the time, go into probe-rtt");
951 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
952 	    SYSCTL_CHILDREN(rack_probertt),
953 	    OID_AUTO, "must_move", CTLFLAG_RW,
954 	    &rack_min_rtt_movement, 250,
955 	    "How much is the minimum movement in rtt to count as a drop for probertt purposes");
956 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
957 	    SYSCTL_CHILDREN(rack_probertt),
958 	    OID_AUTO, "clear_is_cnts", CTLFLAG_RW,
959 	    &rack_probertt_clear_is, 1,
960 	    "Do we clear I/S counts on exiting probe-rtt");
961 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
962 	    SYSCTL_CHILDREN(rack_probertt),
963 	    OID_AUTO, "hbp_extra_drain", CTLFLAG_RW,
964 	    &rack_max_drain_hbp, 1,
965 	    "How many extra drain gpsrtt's do we get in highly buffered paths");
966 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
967 	    SYSCTL_CHILDREN(rack_probertt),
968 	    OID_AUTO, "hbp_threshold", CTLFLAG_RW,
969 	    &rack_hbp_thresh, 3,
970 	    "We are highly buffered if min_rtt_seen / max_rtt_seen > this-threshold");
971 	/* Pacing related sysctls */
972 	rack_pacing = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
973 	    SYSCTL_CHILDREN(rack_sysctl_root),
974 	    OID_AUTO,
975 	    "pacing",
976 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
977 	    "Pacing related Controls");
978 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
979 	    SYSCTL_CHILDREN(rack_pacing),
980 	    OID_AUTO, "max_pace_over", CTLFLAG_RW,
981 	    &rack_max_per_above, 30,
982 	    "What is the maximum allowable percentage that we can pace above (so 30 = 130% of our goal)");
983 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
984 	    SYSCTL_CHILDREN(rack_pacing),
985 	    OID_AUTO, "pace_to_one", CTLFLAG_RW,
986 	    &rack_pace_one_seg, 0,
987 	    "Do we allow low b/w pacing of 1MSS instead of two");
988 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
989 	    SYSCTL_CHILDREN(rack_pacing),
990 	    OID_AUTO, "limit_wsrtt", CTLFLAG_RW,
991 	    &rack_limit_time_with_srtt, 0,
992 	    "Do we limit pacing time based on srtt");
993 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
994 	    SYSCTL_CHILDREN(rack_pacing),
995 	    OID_AUTO, "init_win", CTLFLAG_RW,
996 	    &rack_default_init_window, 0,
997 	    "Do we have a rack initial window 0 = system default");
998 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
999 	    SYSCTL_CHILDREN(rack_pacing),
1000 	    OID_AUTO, "gp_per_ss", CTLFLAG_RW,
1001 	    &rack_per_of_gp_ss, 250,
1002 	    "If non zero, what percentage of goodput to pace at in slow start");
1003 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
1004 	    SYSCTL_CHILDREN(rack_pacing),
1005 	    OID_AUTO, "gp_per_ca", CTLFLAG_RW,
1006 	    &rack_per_of_gp_ca, 150,
1007 	    "If non zero, what percentage of goodput to pace at in congestion avoidance");
1008 	SYSCTL_ADD_U16(&rack_sysctl_ctx,
1009 	    SYSCTL_CHILDREN(rack_pacing),
1010 	    OID_AUTO, "gp_per_rec", CTLFLAG_RW,
1011 	    &rack_per_of_gp_rec, 200,
1012 	    "If non zero, what percentage of goodput to pace at in recovery");
1013 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1014 	    SYSCTL_CHILDREN(rack_pacing),
1015 	    OID_AUTO, "pace_max_seg", CTLFLAG_RW,
1016 	    &rack_hptsi_segments, 40,
1017 	    "What size is the max for TSO segments in pacing and burst mitigation");
1018 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1019 	    SYSCTL_CHILDREN(rack_pacing),
1020 	    OID_AUTO, "burst_reduces", CTLFLAG_RW,
1021 	    &rack_slot_reduction, 4,
1022 	    "When doing only burst mitigation what is the reduce divisor");
1023 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1024 	    SYSCTL_CHILDREN(rack_sysctl_root),
1025 	    OID_AUTO, "use_pacing", CTLFLAG_RW,
1026 	    &rack_pace_every_seg, 0,
1027 	    "If set we use pacing, if clear we use only the original burst mitigation");
1028 	SYSCTL_ADD_U64(&rack_sysctl_ctx,
1029 	    SYSCTL_CHILDREN(rack_pacing),
1030 	    OID_AUTO, "rate_cap", CTLFLAG_RW,
1031 	    &rack_bw_rate_cap, 0,
1032 	    "If set we apply this value to the absolute rate cap used by pacing");
1033 	SYSCTL_ADD_U8(&rack_sysctl_ctx,
1034 	    SYSCTL_CHILDREN(rack_sysctl_root),
1035 	    OID_AUTO, "req_measure_cnt", CTLFLAG_RW,
1036 	    &rack_req_measurements, 1,
1037 	    "If doing dynamic pacing, how many measurements must be in before we start pacing?");
1038 	/* Hardware pacing */
1039 	rack_hw_pacing = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1040 	    SYSCTL_CHILDREN(rack_sysctl_root),
1041 	    OID_AUTO,
1042 	    "hdwr_pacing",
1043 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1044 	    "Pacing related Controls");
1045 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1046 	    SYSCTL_CHILDREN(rack_hw_pacing),
1047 	    OID_AUTO, "rwnd_factor", CTLFLAG_RW,
1048 	    &rack_hw_rwnd_factor, 2,
1049 	    "How many times does snd_wnd need to be bigger than pace_max_seg so we will hold off and get more acks?");
1050 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1051 	    SYSCTL_CHILDREN(rack_hw_pacing),
1052 	    OID_AUTO, "pace_enobuf_mult", CTLFLAG_RW,
1053 	    &rack_enobuf_hw_boost_mult, 2,
1054 	    "By how many time_betweens should we boost the pacing time if we see a ENOBUFS?");
1055 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1056 	    SYSCTL_CHILDREN(rack_hw_pacing),
1057 	    OID_AUTO, "pace_enobuf_max", CTLFLAG_RW,
1058 	    &rack_enobuf_hw_max, 2,
1059 	    "What is the max boost the pacing time if we see a ENOBUFS?");
1060 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1061 	    SYSCTL_CHILDREN(rack_hw_pacing),
1062 	    OID_AUTO, "pace_enobuf_min", CTLFLAG_RW,
1063 	    &rack_enobuf_hw_min, 2,
1064 	    "What is the min boost the pacing time if we see a ENOBUFS?");
1065 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1066 	    SYSCTL_CHILDREN(rack_hw_pacing),
1067 	    OID_AUTO, "enable", CTLFLAG_RW,
1068 	    &rack_enable_hw_pacing, 0,
1069 	    "Should RACK attempt to use hw pacing?");
1070 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1071 	    SYSCTL_CHILDREN(rack_hw_pacing),
1072 	    OID_AUTO, "rate_cap", CTLFLAG_RW,
1073 	    &rack_hw_rate_caps, 1,
1074 	    "Does the highest hardware pacing rate cap the rate we will send at??");
1075 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1076 	    SYSCTL_CHILDREN(rack_hw_pacing),
1077 	    OID_AUTO, "rate_min", CTLFLAG_RW,
1078 	    &rack_hw_rate_min, 0,
1079 	    "Do we need a minimum estimate of this many bytes per second in order to engage hw pacing?");
1080 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1081 	    SYSCTL_CHILDREN(rack_hw_pacing),
1082 	    OID_AUTO, "rate_to_low", CTLFLAG_RW,
1083 	    &rack_hw_rate_to_low, 0,
1084 	    "If we fall below this rate, dis-engage hw pacing?");
1085 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1086 	    SYSCTL_CHILDREN(rack_hw_pacing),
1087 	    OID_AUTO, "up_only", CTLFLAG_RW,
1088 	    &rack_hw_up_only, 1,
1089 	    "Do we allow hw pacing to lower the rate selected?");
1090 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1091 	    SYSCTL_CHILDREN(rack_hw_pacing),
1092 	    OID_AUTO, "extra_mss_precise", CTLFLAG_RW,
1093 	    &rack_hw_pace_extra_slots, 2,
1094 	    "If the rates between software and hardware match precisely how many extra time_betweens do we get?");
1095 	rack_timely = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1096 	    SYSCTL_CHILDREN(rack_sysctl_root),
1097 	    OID_AUTO,
1098 	    "timely",
1099 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1100 	    "Rack Timely RTT Controls");
1101 	/* Timely based GP dynmics */
1102 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1103 	    SYSCTL_CHILDREN(rack_timely),
1104 	    OID_AUTO, "upper", CTLFLAG_RW,
1105 	    &rack_gp_per_bw_mul_up, 2,
1106 	    "Rack timely upper range for equal b/w (in percentage)");
1107 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1108 	    SYSCTL_CHILDREN(rack_timely),
1109 	    OID_AUTO, "lower", CTLFLAG_RW,
1110 	    &rack_gp_per_bw_mul_down, 4,
1111 	    "Rack timely lower range for equal b/w (in percentage)");
1112 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1113 	    SYSCTL_CHILDREN(rack_timely),
1114 	    OID_AUTO, "rtt_max_mul", CTLFLAG_RW,
1115 	    &rack_gp_rtt_maxmul, 3,
1116 	    "Rack timely multipler of lowest rtt for rtt_max");
1117 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1118 	    SYSCTL_CHILDREN(rack_timely),
1119 	    OID_AUTO, "rtt_min_div", CTLFLAG_RW,
1120 	    &rack_gp_rtt_mindiv, 4,
1121 	    "Rack timely divisor used for rtt + (rtt * mul/divisor) for check for lower rtt");
1122 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1123 	    SYSCTL_CHILDREN(rack_timely),
1124 	    OID_AUTO, "rtt_min_mul", CTLFLAG_RW,
1125 	    &rack_gp_rtt_minmul, 1,
1126 	    "Rack timely multiplier used for rtt + (rtt * mul/divisor) for check for lower rtt");
1127 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1128 	    SYSCTL_CHILDREN(rack_timely),
1129 	    OID_AUTO, "decrease", CTLFLAG_RW,
1130 	    &rack_gp_decrease_per, 20,
1131 	    "Rack timely decrease percentage of our GP multiplication factor");
1132 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1133 	    SYSCTL_CHILDREN(rack_timely),
1134 	    OID_AUTO, "increase", CTLFLAG_RW,
1135 	    &rack_gp_increase_per, 2,
1136 	    "Rack timely increase perentage of our GP multiplication factor");
1137 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1138 	    SYSCTL_CHILDREN(rack_timely),
1139 	    OID_AUTO, "lowerbound", CTLFLAG_RW,
1140 	    &rack_per_lower_bound, 50,
1141 	    "Rack timely lowest percentage we allow GP multiplier to fall to");
1142 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1143 	    SYSCTL_CHILDREN(rack_timely),
1144 	    OID_AUTO, "upperboundss", CTLFLAG_RW,
1145 	    &rack_per_upper_bound_ss, 0,
1146 	    "Rack timely higest percentage we allow GP multiplier in SS to raise to (0 is no upperbound)");
1147 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1148 	    SYSCTL_CHILDREN(rack_timely),
1149 	    OID_AUTO, "upperboundca", CTLFLAG_RW,
1150 	    &rack_per_upper_bound_ca, 0,
1151 	    "Rack timely higest percentage we allow GP multiplier to CA raise to (0 is no upperbound)");
1152 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1153 	    SYSCTL_CHILDREN(rack_timely),
1154 	    OID_AUTO, "dynamicgp", CTLFLAG_RW,
1155 	    &rack_do_dyn_mul, 0,
1156 	    "Rack timely do we enable dynmaic timely goodput by default");
1157 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1158 	    SYSCTL_CHILDREN(rack_timely),
1159 	    OID_AUTO, "no_rec_red", CTLFLAG_RW,
1160 	    &rack_gp_no_rec_chg, 1,
1161 	    "Rack timely do we prohibit the recovery multiplier from being lowered");
1162 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1163 	    SYSCTL_CHILDREN(rack_timely),
1164 	    OID_AUTO, "red_clear_cnt", CTLFLAG_RW,
1165 	    &rack_timely_dec_clear, 6,
1166 	    "Rack timely what threshold do we count to before another boost during b/w decent");
1167 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1168 	    SYSCTL_CHILDREN(rack_timely),
1169 	    OID_AUTO, "max_push_rise", CTLFLAG_RW,
1170 	    &rack_timely_max_push_rise, 3,
1171 	    "Rack timely how many times do we push up with b/w increase");
1172 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1173 	    SYSCTL_CHILDREN(rack_timely),
1174 	    OID_AUTO, "max_push_drop", CTLFLAG_RW,
1175 	    &rack_timely_max_push_drop, 3,
1176 	    "Rack timely how many times do we push back on b/w decent");
1177 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1178 	    SYSCTL_CHILDREN(rack_timely),
1179 	    OID_AUTO, "min_segs", CTLFLAG_RW,
1180 	    &rack_timely_min_segs, 4,
1181 	    "Rack timely when setting the cwnd what is the min num segments");
1182 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1183 	    SYSCTL_CHILDREN(rack_timely),
1184 	    OID_AUTO, "noback_max", CTLFLAG_RW,
1185 	    &rack_use_max_for_nobackoff, 0,
1186 	    "Rack timely when deciding if to backoff on a loss, do we use under max rtt else min");
1187 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1188 	    SYSCTL_CHILDREN(rack_timely),
1189 	    OID_AUTO, "interim_timely_only", CTLFLAG_RW,
1190 	    &rack_timely_int_timely_only, 0,
1191 	    "Rack timely when doing interim timely's do we only do timely (no b/w consideration)");
1192 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1193 	    SYSCTL_CHILDREN(rack_timely),
1194 	    OID_AUTO, "nonstop", CTLFLAG_RW,
1195 	    &rack_timely_no_stopping, 0,
1196 	    "Rack timely don't stop increase");
1197 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1198 	    SYSCTL_CHILDREN(rack_timely),
1199 	    OID_AUTO, "dec_raise_thresh", CTLFLAG_RW,
1200 	    &rack_down_raise_thresh, 100,
1201 	    "If the CA or SS is below this threshold raise on the first 3 b/w lowers (0=always)");
1202 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1203 	    SYSCTL_CHILDREN(rack_timely),
1204 	    OID_AUTO, "bottom_drag_segs", CTLFLAG_RW,
1205 	    &rack_req_segs, 1,
1206 	    "Bottom dragging if not these many segments outstanding and room");
1207 
1208 	/* TLP and Rack related parameters */
1209 	rack_tlp = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1210 	    SYSCTL_CHILDREN(rack_sysctl_root),
1211 	    OID_AUTO,
1212 	    "tlp",
1213 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1214 	    "TLP and Rack related Controls");
1215 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1216 	    SYSCTL_CHILDREN(rack_tlp),
1217 	    OID_AUTO, "use_rrr", CTLFLAG_RW,
1218 	    &use_rack_rr, 1,
1219 	    "Do we use Rack Rapid Recovery");
1220 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1221 	    SYSCTL_CHILDREN(rack_tlp),
1222 	    OID_AUTO, "post_rec_labc", CTLFLAG_RW,
1223 	    &rack_max_abc_post_recovery, 2,
1224 	    "Since we do early recovery, do we override the l_abc to a value, if so what?");
1225 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1226 	    SYSCTL_CHILDREN(rack_tlp),
1227 	    OID_AUTO, "nonrxt_use_cr", CTLFLAG_RW,
1228 	    &rack_non_rxt_use_cr, 0,
1229 	    "Do we use ss/ca rate if in recovery we are transmitting a new data chunk");
1230 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1231 	    SYSCTL_CHILDREN(rack_tlp),
1232 	    OID_AUTO, "tlpmethod", CTLFLAG_RW,
1233 	    &rack_tlp_threshold_use, TLP_USE_TWO_ONE,
1234 	    "What method do we do for TLP time calc 0=no-de-ack-comp, 1=ID, 2=2.1, 3=2.2");
1235 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1236 	    SYSCTL_CHILDREN(rack_tlp),
1237 	    OID_AUTO, "limit", CTLFLAG_RW,
1238 	    &rack_tlp_limit, 2,
1239 	    "How many TLP's can be sent without sending new data");
1240 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1241 	    SYSCTL_CHILDREN(rack_tlp),
1242 	    OID_AUTO, "use_greater", CTLFLAG_RW,
1243 	    &rack_tlp_use_greater, 1,
1244 	    "Should we use the rack_rtt time if its greater than srtt");
1245 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1246 	    SYSCTL_CHILDREN(rack_tlp),
1247 	    OID_AUTO, "tlpminto", CTLFLAG_RW,
1248 	    &rack_tlp_min, 10000,
1249 	    "TLP minimum timeout per the specification (in microseconds)");
1250 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1251 	    SYSCTL_CHILDREN(rack_tlp),
1252 	    OID_AUTO, "send_oldest", CTLFLAG_RW,
1253 	    &rack_always_send_oldest, 0,
1254 	    "Should we always send the oldest TLP and RACK-TLP");
1255 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1256 	    SYSCTL_CHILDREN(rack_tlp),
1257 	    OID_AUTO, "rack_tlimit", CTLFLAG_RW,
1258 	    &rack_limited_retran, 0,
1259 	    "How many times can a rack timeout drive out sends");
1260 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1261 	    SYSCTL_CHILDREN(rack_tlp),
1262 	    OID_AUTO, "tlp_cwnd_flag", CTLFLAG_RW,
1263 	    &rack_lower_cwnd_at_tlp, 0,
1264 	    "When a TLP completes a retran should we enter recovery");
1265 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1266 	    SYSCTL_CHILDREN(rack_tlp),
1267 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1268 	    &rack_reorder_thresh, 2,
1269 	    "What factor for rack will be added when seeing reordering (shift right)");
1270 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1271 	    SYSCTL_CHILDREN(rack_tlp),
1272 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1273 	    &rack_tlp_thresh, 1,
1274 	    "What divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1275 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1276 	    SYSCTL_CHILDREN(rack_tlp),
1277 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1278 	    &rack_reorder_fade, 60000000,
1279 	    "Does reorder detection fade, if so how many microseconds (0 means never)");
1280 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1281 	    SYSCTL_CHILDREN(rack_tlp),
1282 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1283 	    &rack_pkt_delay, 1000,
1284 	    "Extra RACK time (in microseconds) besides reordering thresh");
1285 
1286 	/* Timer related controls */
1287 	rack_timers = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1288 	    SYSCTL_CHILDREN(rack_sysctl_root),
1289 	    OID_AUTO,
1290 	    "timers",
1291 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1292 	    "Timer related controls");
1293 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1294 	    SYSCTL_CHILDREN(rack_timers),
1295 	    OID_AUTO, "persmin", CTLFLAG_RW,
1296 	    &rack_persist_min, 250000,
1297 	    "What is the minimum time in microseconds between persists");
1298 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1299 	    SYSCTL_CHILDREN(rack_timers),
1300 	    OID_AUTO, "persmax", CTLFLAG_RW,
1301 	    &rack_persist_max, 2000000,
1302 	    "What is the largest delay in microseconds between persists");
1303 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1304 	    SYSCTL_CHILDREN(rack_timers),
1305 	    OID_AUTO, "delayed_ack", CTLFLAG_RW,
1306 	    &rack_delayed_ack_time, 40000,
1307 	    "Delayed ack time (40ms in microseconds)");
1308 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1309 	    SYSCTL_CHILDREN(rack_timers),
1310 	    OID_AUTO, "minrto", CTLFLAG_RW,
1311 	    &rack_rto_min, 30000,
1312 	    "Minimum RTO in microseconds -- set with caution below 1000 due to TLP");
1313 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1314 	    SYSCTL_CHILDREN(rack_timers),
1315 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1316 	    &rack_rto_max, 4000000,
1317 	    "Maxiumum RTO in microseconds -- should be at least as large as min_rto");
1318 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1319 	    SYSCTL_CHILDREN(rack_timers),
1320 	    OID_AUTO, "minto", CTLFLAG_RW,
1321 	    &rack_min_to, 1000,
1322 	    "Minimum rack timeout in microseconds");
1323 	/* Measure controls */
1324 	rack_measure = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(rack_sysctl_root),
1326 	    OID_AUTO,
1327 	    "measure",
1328 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1329 	    "Measure related controls");
1330 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1331 	    SYSCTL_CHILDREN(rack_measure),
1332 	    OID_AUTO, "wma_divisor", CTLFLAG_RW,
1333 	    &rack_wma_divisor, 8,
1334 	    "When doing b/w calculation what is the  divisor for the WMA");
1335 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1336 	    SYSCTL_CHILDREN(rack_measure),
1337 	    OID_AUTO, "end_cwnd", CTLFLAG_RW,
1338 	    &rack_cwnd_block_ends_measure, 0,
1339 	    "Does a cwnd just-return end the measurement window (app limited)");
1340 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1341 	    SYSCTL_CHILDREN(rack_measure),
1342 	    OID_AUTO, "end_rwnd", CTLFLAG_RW,
1343 	    &rack_rwnd_block_ends_measure, 0,
1344 	    "Does an rwnd just-return end the measurement window (app limited -- not persists)");
1345 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1346 	    SYSCTL_CHILDREN(rack_measure),
1347 	    OID_AUTO, "min_target", CTLFLAG_RW,
1348 	    &rack_def_data_window, 20,
1349 	    "What is the minimum target window (in mss) for a GP measurements");
1350 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1351 	    SYSCTL_CHILDREN(rack_measure),
1352 	    OID_AUTO, "goal_bdp", CTLFLAG_RW,
1353 	    &rack_goal_bdp, 2,
1354 	    "What is the goal BDP to measure");
1355 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1356 	    SYSCTL_CHILDREN(rack_measure),
1357 	    OID_AUTO, "min_srtts", CTLFLAG_RW,
1358 	    &rack_min_srtts, 1,
1359 	    "What is the goal BDP to measure");
1360 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1361 	    SYSCTL_CHILDREN(rack_measure),
1362 	    OID_AUTO, "min_measure_tim", CTLFLAG_RW,
1363 	    &rack_min_measure_usec, 0,
1364 	    "What is the Minimum time time for a measurement if 0, this is off");
1365 	/* Misc rack controls */
1366 	rack_misc = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(rack_sysctl_root),
1368 	    OID_AUTO,
1369 	    "misc",
1370 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1371 	    "Misc related controls");
1372 #ifdef TCP_ACCOUNTING
1373 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1374 	    SYSCTL_CHILDREN(rack_misc),
1375 	    OID_AUTO, "tcp_acct", CTLFLAG_RW,
1376 	    &rack_tcp_accounting, 0,
1377 	    "Should we turn on TCP accounting for all rack sessions?");
1378 #endif
1379 
1380 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1381 	    SYSCTL_CHILDREN(rack_misc),
1382 	    OID_AUTO, "rack_dsack_ctl", CTLFLAG_RW,
1383 	    &rack_dsack_std_based, 3,
1384 	    "How do we process dsack with respect to rack timers, bit field, 3 is standards based?");
1385 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1386 	    SYSCTL_CHILDREN(rack_misc),
1387 	    OID_AUTO, "prr_addback_max", CTLFLAG_RW,
1388 	    &rack_prr_addbackmax, 2,
1389 	    "What is the maximum number of MSS we allow to be added back if prr can't send all its data?");
1390 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1391 	    SYSCTL_CHILDREN(rack_misc),
1392 	    OID_AUTO, "stats_gets_ms", CTLFLAG_RW,
1393 	    &rack_stats_gets_ms_rtt, 1,
1394 	    "What do we feed the stats framework (1 = ms_rtt, 0 = us_rtt, 2 = ms_rtt from hdwr, > 2 usec rtt from hdwr)?");
1395 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1396 	    SYSCTL_CHILDREN(rack_misc),
1397 	    OID_AUTO, "clientlowbuf", CTLFLAG_RW,
1398 	    &rack_client_low_buf, 0,
1399 	    "Client low buffer level (below this we are more aggressive in DGP exiting recovery (0 = off)?");
1400 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1401 	    SYSCTL_CHILDREN(rack_misc),
1402 	    OID_AUTO, "defprofile", CTLFLAG_RW,
1403 	    &rack_def_profile, 0,
1404 	    "Should RACK use a default profile (0=no, num == profile num)?");
1405 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1406 	    SYSCTL_CHILDREN(rack_misc),
1407 	    OID_AUTO, "cmpack", CTLFLAG_RW,
1408 	    &rack_use_cmp_acks, 1,
1409 	    "Should RACK have LRO send compressed acks");
1410 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1411 	    SYSCTL_CHILDREN(rack_misc),
1412 	    OID_AUTO, "fsb", CTLFLAG_RW,
1413 	    &rack_use_fsb, 1,
1414 	    "Should RACK use the fast send block?");
1415 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1416 	    SYSCTL_CHILDREN(rack_misc),
1417 	    OID_AUTO, "rfo", CTLFLAG_RW,
1418 	    &rack_use_rfo, 1,
1419 	    "Should RACK use rack_fast_output()?");
1420 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1421 	    SYSCTL_CHILDREN(rack_misc),
1422 	    OID_AUTO, "rsmrfo", CTLFLAG_RW,
1423 	    &rack_use_rsm_rfo, 1,
1424 	    "Should RACK use rack_fast_rsm_output()?");
1425 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1426 	    SYSCTL_CHILDREN(rack_misc),
1427 	    OID_AUTO, "shared_cwnd", CTLFLAG_RW,
1428 	    &rack_enable_shared_cwnd, 1,
1429 	    "Should RACK try to use the shared cwnd on connections where allowed");
1430 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1431 	    SYSCTL_CHILDREN(rack_misc),
1432 	    OID_AUTO, "limits_on_scwnd", CTLFLAG_RW,
1433 	    &rack_limits_scwnd, 1,
1434 	    "Should RACK place low end time limits on the shared cwnd feature");
1435 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1436 	    SYSCTL_CHILDREN(rack_misc),
1437 	    OID_AUTO, "non_paced_lro_queue", CTLFLAG_RW,
1438 	    &rack_enable_mqueue_for_nonpaced, 0,
1439 	    "Should RACK use mbuf queuing for non-paced connections");
1440 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1441 	    SYSCTL_CHILDREN(rack_misc),
1442 	    OID_AUTO, "iMac_dack", CTLFLAG_RW,
1443 	    &rack_use_imac_dack, 0,
1444 	    "Should RACK try to emulate iMac delayed ack");
1445 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1446 	    SYSCTL_CHILDREN(rack_misc),
1447 	    OID_AUTO, "no_prr", CTLFLAG_RW,
1448 	    &rack_disable_prr, 0,
1449 	    "Should RACK not use prr and only pace (must have pacing on)");
1450 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1451 	    SYSCTL_CHILDREN(rack_misc),
1452 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1453 	    &rack_verbose_logging, 0,
1454 	    "Should RACK black box logging be verbose");
1455 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1456 	    SYSCTL_CHILDREN(rack_misc),
1457 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1458 	    &rack_ignore_data_after_close, 1,
1459 	    "Do we hold off sending a RST until all pending data is ack'd");
1460 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1461 	    SYSCTL_CHILDREN(rack_misc),
1462 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1463 	    &rack_sack_not_required, 1,
1464 	    "Do we allow rack to run on connections not supporting SACK");
1465 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1466 	    SYSCTL_CHILDREN(rack_misc),
1467 	    OID_AUTO, "prr_sendalot", CTLFLAG_RW,
1468 	    &rack_send_a_lot_in_prr, 1,
1469 	    "Send a lot in prr");
1470 	SYSCTL_ADD_S32(&rack_sysctl_ctx,
1471 	    SYSCTL_CHILDREN(rack_misc),
1472 	    OID_AUTO, "autoscale", CTLFLAG_RW,
1473 	    &rack_autosndbuf_inc, 20,
1474 	    "What percentage should rack scale up its snd buffer by?");
1475 	/* Sack Attacker detection stuff */
1476 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1477 	    SYSCTL_CHILDREN(rack_attack),
1478 	    OID_AUTO, "detect_highsackratio", CTLFLAG_RW,
1479 	    &rack_highest_sack_thresh_seen, 0,
1480 	    "Highest sack to ack ratio seen");
1481 	SYSCTL_ADD_U32(&rack_sysctl_ctx,
1482 	    SYSCTL_CHILDREN(rack_attack),
1483 	    OID_AUTO, "detect_highmoveratio", CTLFLAG_RW,
1484 	    &rack_highest_move_thresh_seen, 0,
1485 	    "Highest move to non-move ratio seen");
1486 	rack_ack_total = counter_u64_alloc(M_WAITOK);
1487 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1488 	    SYSCTL_CHILDREN(rack_attack),
1489 	    OID_AUTO, "acktotal", CTLFLAG_RD,
1490 	    &rack_ack_total,
1491 	    "Total number of Ack's");
1492 	rack_express_sack = counter_u64_alloc(M_WAITOK);
1493 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(rack_attack),
1495 	    OID_AUTO, "exp_sacktotal", CTLFLAG_RD,
1496 	    &rack_express_sack,
1497 	    "Total expresss number of Sack's");
1498 	rack_sack_total = counter_u64_alloc(M_WAITOK);
1499 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1500 	    SYSCTL_CHILDREN(rack_attack),
1501 	    OID_AUTO, "sacktotal", CTLFLAG_RD,
1502 	    &rack_sack_total,
1503 	    "Total number of SACKs");
1504 	rack_move_none = counter_u64_alloc(M_WAITOK);
1505 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1506 	    SYSCTL_CHILDREN(rack_attack),
1507 	    OID_AUTO, "move_none", CTLFLAG_RD,
1508 	    &rack_move_none,
1509 	    "Total number of SACK index reuse of postions under threshold");
1510 	rack_move_some = counter_u64_alloc(M_WAITOK);
1511 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1512 	    SYSCTL_CHILDREN(rack_attack),
1513 	    OID_AUTO, "move_some", CTLFLAG_RD,
1514 	    &rack_move_some,
1515 	    "Total number of SACK index reuse of postions over threshold");
1516 	rack_sack_attacks_detected = counter_u64_alloc(M_WAITOK);
1517 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1518 	    SYSCTL_CHILDREN(rack_attack),
1519 	    OID_AUTO, "attacks", CTLFLAG_RD,
1520 	    &rack_sack_attacks_detected,
1521 	    "Total number of SACK attackers that had sack disabled");
1522 	rack_sack_attacks_reversed = counter_u64_alloc(M_WAITOK);
1523 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1524 	    SYSCTL_CHILDREN(rack_attack),
1525 	    OID_AUTO, "reversed", CTLFLAG_RD,
1526 	    &rack_sack_attacks_reversed,
1527 	    "Total number of SACK attackers that were later determined false positive");
1528 	rack_sack_used_next_merge = counter_u64_alloc(M_WAITOK);
1529 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1530 	    SYSCTL_CHILDREN(rack_attack),
1531 	    OID_AUTO, "nextmerge", CTLFLAG_RD,
1532 	    &rack_sack_used_next_merge,
1533 	    "Total number of times we used the next merge");
1534 	rack_sack_used_prev_merge = counter_u64_alloc(M_WAITOK);
1535 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(rack_attack),
1537 	    OID_AUTO, "prevmerge", CTLFLAG_RD,
1538 	    &rack_sack_used_prev_merge,
1539 	    "Total number of times we used the prev merge");
1540 	/* Counters */
1541 	rack_fto_send = counter_u64_alloc(M_WAITOK);
1542 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1543 	    SYSCTL_CHILDREN(rack_counters),
1544 	    OID_AUTO, "fto_send", CTLFLAG_RD,
1545 	    &rack_fto_send, "Total number of rack_fast_output sends");
1546 	rack_fto_rsm_send = counter_u64_alloc(M_WAITOK);
1547 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1548 	    SYSCTL_CHILDREN(rack_counters),
1549 	    OID_AUTO, "fto_rsm_send", CTLFLAG_RD,
1550 	    &rack_fto_rsm_send, "Total number of rack_fast_rsm_output sends");
1551 	rack_nfto_resend = counter_u64_alloc(M_WAITOK);
1552 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1553 	    SYSCTL_CHILDREN(rack_counters),
1554 	    OID_AUTO, "nfto_resend", CTLFLAG_RD,
1555 	    &rack_nfto_resend, "Total number of rack_output retransmissions");
1556 	rack_non_fto_send = counter_u64_alloc(M_WAITOK);
1557 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(rack_counters),
1559 	    OID_AUTO, "nfto_send", CTLFLAG_RD,
1560 	    &rack_non_fto_send, "Total number of rack_output first sends");
1561 	rack_extended_rfo = counter_u64_alloc(M_WAITOK);
1562 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(rack_counters),
1564 	    OID_AUTO, "rfo_extended", CTLFLAG_RD,
1565 	    &rack_extended_rfo, "Total number of times we extended rfo");
1566 
1567 	rack_hw_pace_init_fail = counter_u64_alloc(M_WAITOK);
1568 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1569 	    SYSCTL_CHILDREN(rack_counters),
1570 	    OID_AUTO, "hwpace_init_fail", CTLFLAG_RD,
1571 	    &rack_hw_pace_init_fail, "Total number of times we failed to initialize hw pacing");
1572 	rack_hw_pace_lost = counter_u64_alloc(M_WAITOK);
1573 
1574 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1575 	    SYSCTL_CHILDREN(rack_counters),
1576 	    OID_AUTO, "hwpace_lost", CTLFLAG_RD,
1577 	    &rack_hw_pace_lost, "Total number of times we failed to initialize hw pacing");
1578 	rack_badfr = counter_u64_alloc(M_WAITOK);
1579 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1580 	    SYSCTL_CHILDREN(rack_counters),
1581 	    OID_AUTO, "badfr", CTLFLAG_RD,
1582 	    &rack_badfr, "Total number of bad FRs");
1583 	rack_badfr_bytes = counter_u64_alloc(M_WAITOK);
1584 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1585 	    SYSCTL_CHILDREN(rack_counters),
1586 	    OID_AUTO, "badfr_bytes", CTLFLAG_RD,
1587 	    &rack_badfr_bytes, "Total number of bad FRs");
1588 	rack_rtm_prr_retran = counter_u64_alloc(M_WAITOK);
1589 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1590 	    SYSCTL_CHILDREN(rack_counters),
1591 	    OID_AUTO, "prrsndret", CTLFLAG_RD,
1592 	    &rack_rtm_prr_retran,
1593 	    "Total number of prr based retransmits");
1594 	rack_rtm_prr_newdata = counter_u64_alloc(M_WAITOK);
1595 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1596 	    SYSCTL_CHILDREN(rack_counters),
1597 	    OID_AUTO, "prrsndnew", CTLFLAG_RD,
1598 	    &rack_rtm_prr_newdata,
1599 	    "Total number of prr based new transmits");
1600 	rack_timestamp_mismatch = counter_u64_alloc(M_WAITOK);
1601 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1602 	    SYSCTL_CHILDREN(rack_counters),
1603 	    OID_AUTO, "tsnf", CTLFLAG_RD,
1604 	    &rack_timestamp_mismatch,
1605 	    "Total number of timestamps that we could not find the reported ts");
1606 	rack_find_high = counter_u64_alloc(M_WAITOK);
1607 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(rack_counters),
1609 	    OID_AUTO, "findhigh", CTLFLAG_RD,
1610 	    &rack_find_high,
1611 	    "Total number of FIN causing find-high");
1612 	rack_reorder_seen = counter_u64_alloc(M_WAITOK);
1613 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1614 	    SYSCTL_CHILDREN(rack_counters),
1615 	    OID_AUTO, "reordering", CTLFLAG_RD,
1616 	    &rack_reorder_seen,
1617 	    "Total number of times we added delay due to reordering");
1618 	rack_tlp_tot = counter_u64_alloc(M_WAITOK);
1619 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1620 	    SYSCTL_CHILDREN(rack_counters),
1621 	    OID_AUTO, "tlp_to_total", CTLFLAG_RD,
1622 	    &rack_tlp_tot,
1623 	    "Total number of tail loss probe expirations");
1624 	rack_tlp_newdata = counter_u64_alloc(M_WAITOK);
1625 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1626 	    SYSCTL_CHILDREN(rack_counters),
1627 	    OID_AUTO, "tlp_new", CTLFLAG_RD,
1628 	    &rack_tlp_newdata,
1629 	    "Total number of tail loss probe sending new data");
1630 	rack_tlp_retran = counter_u64_alloc(M_WAITOK);
1631 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1632 	    SYSCTL_CHILDREN(rack_counters),
1633 	    OID_AUTO, "tlp_retran", CTLFLAG_RD,
1634 	    &rack_tlp_retran,
1635 	    "Total number of tail loss probe sending retransmitted data");
1636 	rack_tlp_retran_bytes = counter_u64_alloc(M_WAITOK);
1637 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1638 	    SYSCTL_CHILDREN(rack_counters),
1639 	    OID_AUTO, "tlp_retran_bytes", CTLFLAG_RD,
1640 	    &rack_tlp_retran_bytes,
1641 	    "Total bytes of tail loss probe sending retransmitted data");
1642 	rack_tlp_retran_fail = counter_u64_alloc(M_WAITOK);
1643 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1644 	    SYSCTL_CHILDREN(rack_counters),
1645 	    OID_AUTO, "tlp_retran_fail", CTLFLAG_RD,
1646 	    &rack_tlp_retran_fail,
1647 	    "Total number of tail loss probe sending retransmitted data that failed (wait for t3)");
1648 	rack_to_tot = counter_u64_alloc(M_WAITOK);
1649 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1650 	    SYSCTL_CHILDREN(rack_counters),
1651 	    OID_AUTO, "rack_to_tot", CTLFLAG_RD,
1652 	    &rack_to_tot,
1653 	    "Total number of times the rack to expired");
1654 	rack_to_arm_rack = counter_u64_alloc(M_WAITOK);
1655 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(rack_counters),
1657 	    OID_AUTO, "arm_rack", CTLFLAG_RD,
1658 	    &rack_to_arm_rack,
1659 	    "Total number of times the rack timer armed");
1660 	rack_to_arm_tlp = counter_u64_alloc(M_WAITOK);
1661 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1662 	    SYSCTL_CHILDREN(rack_counters),
1663 	    OID_AUTO, "arm_tlp", CTLFLAG_RD,
1664 	    &rack_to_arm_tlp,
1665 	    "Total number of times the tlp timer armed");
1666 	rack_calc_zero = counter_u64_alloc(M_WAITOK);
1667 	rack_calc_nonzero = counter_u64_alloc(M_WAITOK);
1668 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1669 	    SYSCTL_CHILDREN(rack_counters),
1670 	    OID_AUTO, "calc_zero", CTLFLAG_RD,
1671 	    &rack_calc_zero,
1672 	    "Total number of times pacing time worked out to zero");
1673 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1674 	    SYSCTL_CHILDREN(rack_counters),
1675 	    OID_AUTO, "calc_nonzero", CTLFLAG_RD,
1676 	    &rack_calc_nonzero,
1677 	    "Total number of times pacing time worked out to non-zero");
1678 	rack_paced_segments = counter_u64_alloc(M_WAITOK);
1679 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1680 	    SYSCTL_CHILDREN(rack_counters),
1681 	    OID_AUTO, "paced", CTLFLAG_RD,
1682 	    &rack_paced_segments,
1683 	    "Total number of times a segment send caused hptsi");
1684 	rack_unpaced_segments = counter_u64_alloc(M_WAITOK);
1685 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1686 	    SYSCTL_CHILDREN(rack_counters),
1687 	    OID_AUTO, "unpaced", CTLFLAG_RD,
1688 	    &rack_unpaced_segments,
1689 	    "Total number of times a segment did not cause hptsi");
1690 	rack_saw_enobuf = counter_u64_alloc(M_WAITOK);
1691 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1692 	    SYSCTL_CHILDREN(rack_counters),
1693 	    OID_AUTO, "saw_enobufs", CTLFLAG_RD,
1694 	    &rack_saw_enobuf,
1695 	    "Total number of times a sends returned enobuf for non-hdwr paced connections");
1696 	rack_saw_enobuf_hw = counter_u64_alloc(M_WAITOK);
1697 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1698 	    SYSCTL_CHILDREN(rack_counters),
1699 	    OID_AUTO, "saw_enobufs_hw", CTLFLAG_RD,
1700 	    &rack_saw_enobuf_hw,
1701 	    "Total number of times a send returned enobuf for hdwr paced connections");
1702 	rack_saw_enetunreach = counter_u64_alloc(M_WAITOK);
1703 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1704 	    SYSCTL_CHILDREN(rack_counters),
1705 	    OID_AUTO, "saw_enetunreach", CTLFLAG_RD,
1706 	    &rack_saw_enetunreach,
1707 	    "Total number of times a send received a enetunreachable");
1708 	rack_hot_alloc = counter_u64_alloc(M_WAITOK);
1709 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1710 	    SYSCTL_CHILDREN(rack_counters),
1711 	    OID_AUTO, "alloc_hot", CTLFLAG_RD,
1712 	    &rack_hot_alloc,
1713 	    "Total allocations from the top of our list");
1714 	rack_to_alloc = counter_u64_alloc(M_WAITOK);
1715 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1716 	    SYSCTL_CHILDREN(rack_counters),
1717 	    OID_AUTO, "allocs", CTLFLAG_RD,
1718 	    &rack_to_alloc,
1719 	    "Total allocations of tracking structures");
1720 	rack_to_alloc_hard = counter_u64_alloc(M_WAITOK);
1721 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1722 	    SYSCTL_CHILDREN(rack_counters),
1723 	    OID_AUTO, "allochard", CTLFLAG_RD,
1724 	    &rack_to_alloc_hard,
1725 	    "Total allocations done with sleeping the hard way");
1726 	rack_to_alloc_emerg = counter_u64_alloc(M_WAITOK);
1727 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(rack_counters),
1729 	    OID_AUTO, "allocemerg", CTLFLAG_RD,
1730 	    &rack_to_alloc_emerg,
1731 	    "Total allocations done from emergency cache");
1732 	rack_to_alloc_limited = counter_u64_alloc(M_WAITOK);
1733 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1734 	    SYSCTL_CHILDREN(rack_counters),
1735 	    OID_AUTO, "alloc_limited", CTLFLAG_RD,
1736 	    &rack_to_alloc_limited,
1737 	    "Total allocations dropped due to limit");
1738 	rack_alloc_limited_conns = counter_u64_alloc(M_WAITOK);
1739 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1740 	    SYSCTL_CHILDREN(rack_counters),
1741 	    OID_AUTO, "alloc_limited_conns", CTLFLAG_RD,
1742 	    &rack_alloc_limited_conns,
1743 	    "Connections with allocations dropped due to limit");
1744 	rack_split_limited = counter_u64_alloc(M_WAITOK);
1745 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1746 	    SYSCTL_CHILDREN(rack_counters),
1747 	    OID_AUTO, "split_limited", CTLFLAG_RD,
1748 	    &rack_split_limited,
1749 	    "Split allocations dropped due to limit");
1750 
1751 	for (i = 0; i < MAX_NUM_OF_CNTS; i++) {
1752 		char name[32];
1753 		sprintf(name, "cmp_ack_cnt_%d", i);
1754 		rack_proc_comp_ack[i] = counter_u64_alloc(M_WAITOK);
1755 		SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1756 				       SYSCTL_CHILDREN(rack_counters),
1757 				       OID_AUTO, name, CTLFLAG_RD,
1758 				       &rack_proc_comp_ack[i],
1759 				       "Number of compressed acks we processed");
1760 	}
1761 	rack_large_ackcmp = counter_u64_alloc(M_WAITOK);
1762 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1763 	    SYSCTL_CHILDREN(rack_counters),
1764 	    OID_AUTO, "cmp_large_mbufs", CTLFLAG_RD,
1765 	    &rack_large_ackcmp,
1766 	    "Number of TCP connections with large mbuf's for compressed acks");
1767 	rack_small_ackcmp = counter_u64_alloc(M_WAITOK);
1768 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(rack_counters),
1770 	    OID_AUTO, "cmp_small_mbufs", CTLFLAG_RD,
1771 	    &rack_small_ackcmp,
1772 	    "Number of TCP connections with small mbuf's for compressed acks");
1773 #ifdef INVARIANTS
1774 	rack_adjust_map_bw = counter_u64_alloc(M_WAITOK);
1775 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1776 	    SYSCTL_CHILDREN(rack_counters),
1777 	    OID_AUTO, "map_adjust_req", CTLFLAG_RD,
1778 	    &rack_adjust_map_bw,
1779 	    "Number of times we hit the case where the sb went up and down on a sendmap entry");
1780 #endif
1781 	rack_multi_single_eq = counter_u64_alloc(M_WAITOK);
1782 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1783 	    SYSCTL_CHILDREN(rack_counters),
1784 	    OID_AUTO, "cmp_ack_equiv", CTLFLAG_RD,
1785 	    &rack_multi_single_eq,
1786 	    "Number of compressed acks total represented");
1787 	rack_proc_non_comp_ack = counter_u64_alloc(M_WAITOK);
1788 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1789 	    SYSCTL_CHILDREN(rack_counters),
1790 	    OID_AUTO, "cmp_ack_not", CTLFLAG_RD,
1791 	    &rack_proc_non_comp_ack,
1792 	    "Number of non compresseds acks that we processed");
1793 
1794 
1795 	rack_sack_proc_all = counter_u64_alloc(M_WAITOK);
1796 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1797 	    SYSCTL_CHILDREN(rack_counters),
1798 	    OID_AUTO, "sack_long", CTLFLAG_RD,
1799 	    &rack_sack_proc_all,
1800 	    "Total times we had to walk whole list for sack processing");
1801 	rack_sack_proc_restart = counter_u64_alloc(M_WAITOK);
1802 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1803 	    SYSCTL_CHILDREN(rack_counters),
1804 	    OID_AUTO, "sack_restart", CTLFLAG_RD,
1805 	    &rack_sack_proc_restart,
1806 	    "Total times we had to walk whole list due to a restart");
1807 	rack_sack_proc_short = counter_u64_alloc(M_WAITOK);
1808 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1809 	    SYSCTL_CHILDREN(rack_counters),
1810 	    OID_AUTO, "sack_short", CTLFLAG_RD,
1811 	    &rack_sack_proc_short,
1812 	    "Total times we took shortcut for sack processing");
1813 	rack_enter_tlp_calc = counter_u64_alloc(M_WAITOK);
1814 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1815 	    SYSCTL_CHILDREN(rack_counters),
1816 	    OID_AUTO, "tlp_calc_entered", CTLFLAG_RD,
1817 	    &rack_enter_tlp_calc,
1818 	    "Total times we called calc-tlp");
1819 	rack_used_tlpmethod = counter_u64_alloc(M_WAITOK);
1820 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1821 	    SYSCTL_CHILDREN(rack_counters),
1822 	    OID_AUTO, "hit_tlp_method", CTLFLAG_RD,
1823 	    &rack_used_tlpmethod,
1824 	    "Total number of runt sacks");
1825 	rack_used_tlpmethod2 = counter_u64_alloc(M_WAITOK);
1826 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1827 	    SYSCTL_CHILDREN(rack_counters),
1828 	    OID_AUTO, "hit_tlp_method2", CTLFLAG_RD,
1829 	    &rack_used_tlpmethod2,
1830 	    "Total number of times we hit TLP method 2");
1831 	rack_sack_skipped_acked = counter_u64_alloc(M_WAITOK);
1832 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1833 	    SYSCTL_CHILDREN(rack_attack),
1834 	    OID_AUTO, "skipacked", CTLFLAG_RD,
1835 	    &rack_sack_skipped_acked,
1836 	    "Total number of times we skipped previously sacked");
1837 	rack_sack_splits = counter_u64_alloc(M_WAITOK);
1838 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1839 	    SYSCTL_CHILDREN(rack_attack),
1840 	    OID_AUTO, "ofsplit", CTLFLAG_RD,
1841 	    &rack_sack_splits,
1842 	    "Total number of times we did the old fashion tree split");
1843 	rack_progress_drops = counter_u64_alloc(M_WAITOK);
1844 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1845 	    SYSCTL_CHILDREN(rack_counters),
1846 	    OID_AUTO, "prog_drops", CTLFLAG_RD,
1847 	    &rack_progress_drops,
1848 	    "Total number of progress drops");
1849 	rack_input_idle_reduces = counter_u64_alloc(M_WAITOK);
1850 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1851 	    SYSCTL_CHILDREN(rack_counters),
1852 	    OID_AUTO, "idle_reduce_oninput", CTLFLAG_RD,
1853 	    &rack_input_idle_reduces,
1854 	    "Total number of idle reductions on input");
1855 	rack_collapsed_win = counter_u64_alloc(M_WAITOK);
1856 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1857 	    SYSCTL_CHILDREN(rack_counters),
1858 	    OID_AUTO, "collapsed_win", CTLFLAG_RD,
1859 	    &rack_collapsed_win,
1860 	    "Total number of collapsed windows");
1861 	rack_tlp_does_nada = counter_u64_alloc(M_WAITOK);
1862 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1863 	    SYSCTL_CHILDREN(rack_counters),
1864 	    OID_AUTO, "tlp_nada", CTLFLAG_RD,
1865 	    &rack_tlp_does_nada,
1866 	    "Total number of nada tlp calls");
1867 	rack_try_scwnd = counter_u64_alloc(M_WAITOK);
1868 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1869 	    SYSCTL_CHILDREN(rack_counters),
1870 	    OID_AUTO, "tried_scwnd", CTLFLAG_RD,
1871 	    &rack_try_scwnd,
1872 	    "Total number of scwnd attempts");
1873 
1874 	rack_per_timer_hole = counter_u64_alloc(M_WAITOK);
1875 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1876 	    SYSCTL_CHILDREN(rack_counters),
1877 	    OID_AUTO, "timer_hole", CTLFLAG_RD,
1878 	    &rack_per_timer_hole,
1879 	    "Total persists start in timer hole");
1880 
1881 	rack_sbsndptr_wrong = counter_u64_alloc(M_WAITOK);
1882 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1883 	    SYSCTL_CHILDREN(rack_counters),
1884 	    OID_AUTO, "sndptr_wrong", CTLFLAG_RD,
1885 	    &rack_sbsndptr_wrong, "Total number of times the saved sbsndptr was incorret");
1886 	rack_sbsndptr_right = counter_u64_alloc(M_WAITOK);
1887 	SYSCTL_ADD_COUNTER_U64(&rack_sysctl_ctx,
1888 	    SYSCTL_CHILDREN(rack_counters),
1889 	    OID_AUTO, "sndptr_right", CTLFLAG_RD,
1890 	    &rack_sbsndptr_right, "Total number of times the saved sbsndptr was corret");
1891 
1892 	COUNTER_ARRAY_ALLOC(rack_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1893 	SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
1894 	    OID_AUTO, "outsize", CTLFLAG_RD,
1895 	    rack_out_size, TCP_MSS_ACCT_SIZE, "MSS send sizes");
1896 	COUNTER_ARRAY_ALLOC(rack_opts_arry, RACK_OPTS_SIZE, M_WAITOK);
1897 	SYSCTL_ADD_COUNTER_U64_ARRAY(&rack_sysctl_ctx, SYSCTL_CHILDREN(rack_sysctl_root),
1898 	    OID_AUTO, "opts", CTLFLAG_RD,
1899 	    rack_opts_arry, RACK_OPTS_SIZE, "RACK Option Stats");
1900 	SYSCTL_ADD_PROC(&rack_sysctl_ctx,
1901 	    SYSCTL_CHILDREN(rack_sysctl_root),
1902 	    OID_AUTO, "clear", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1903 	    &rack_clear_counter, 0, sysctl_rack_clear, "IU", "Clear counters");
1904 }
1905 
1906 static __inline int
1907 rb_map_cmp(struct rack_sendmap *b, struct rack_sendmap *a)
1908 {
1909 	if (SEQ_GEQ(b->r_start, a->r_start) &&
1910 	    SEQ_LT(b->r_start, a->r_end)) {
1911 		/*
1912 		 * The entry b is within the
1913 		 * block a. i.e.:
1914 		 * a --   |-------------|
1915 		 * b --   |----|
1916 		 * <or>
1917 		 * b --       |------|
1918 		 * <or>
1919 		 * b --       |-----------|
1920 		 */
1921 		return (0);
1922 	} else if (SEQ_GEQ(b->r_start, a->r_end)) {
1923 		/*
1924 		 * b falls as either the next
1925 		 * sequence block after a so a
1926 		 * is said to be smaller than b.
1927 		 * i.e:
1928 		 * a --   |------|
1929 		 * b --          |--------|
1930 		 * or
1931 		 * b --              |-----|
1932 		 */
1933 		return (1);
1934 	}
1935 	/*
1936 	 * Whats left is where a is
1937 	 * larger than b. i.e:
1938 	 * a --         |-------|
1939 	 * b --  |---|
1940 	 * or even possibly
1941 	 * b --   |--------------|
1942 	 */
1943 	return (-1);
1944 }
1945 
1946 RB_PROTOTYPE(rack_rb_tree_head, rack_sendmap, r_next, rb_map_cmp);
1947 RB_GENERATE(rack_rb_tree_head, rack_sendmap, r_next, rb_map_cmp);
1948 
1949 static uint32_t
1950 rc_init_window(struct tcp_rack *rack)
1951 {
1952 	uint32_t win;
1953 
1954 	if (rack->rc_init_win == 0) {
1955 		/*
1956 		 * Nothing set by the user, use the system stack
1957 		 * default.
1958 		 */
1959 		return (tcp_compute_initwnd(tcp_maxseg(rack->rc_tp)));
1960 	}
1961 	win = ctf_fixed_maxseg(rack->rc_tp) * rack->rc_init_win;
1962 	return (win);
1963 }
1964 
1965 static uint64_t
1966 rack_get_fixed_pacing_bw(struct tcp_rack *rack)
1967 {
1968 	if (IN_FASTRECOVERY(rack->rc_tp->t_flags))
1969 		return (rack->r_ctl.rc_fixed_pacing_rate_rec);
1970 	else if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh)
1971 		return (rack->r_ctl.rc_fixed_pacing_rate_ss);
1972 	else
1973 		return (rack->r_ctl.rc_fixed_pacing_rate_ca);
1974 }
1975 
1976 static uint64_t
1977 rack_get_bw(struct tcp_rack *rack)
1978 {
1979 	if (rack->use_fixed_rate) {
1980 		/* Return the fixed pacing rate */
1981 		return (rack_get_fixed_pacing_bw(rack));
1982 	}
1983 	if (rack->r_ctl.gp_bw == 0) {
1984 		/*
1985 		 * We have yet no b/w measurement,
1986 		 * if we have a user set initial bw
1987 		 * return it. If we don't have that and
1988 		 * we have an srtt, use the tcp IW (10) to
1989 		 * calculate a fictional b/w over the SRTT
1990 		 * which is more or less a guess. Note
1991 		 * we don't use our IW from rack on purpose
1992 		 * so if we have like IW=30, we are not
1993 		 * calculating a "huge" b/w.
1994 		 */
1995 		uint64_t bw, srtt;
1996 		if (rack->r_ctl.init_rate)
1997 			return (rack->r_ctl.init_rate);
1998 
1999 		/* Has the user set a max peak rate? */
2000 #ifdef NETFLIX_PEAKRATE
2001 		if (rack->rc_tp->t_maxpeakrate)
2002 			return (rack->rc_tp->t_maxpeakrate);
2003 #endif
2004 		/* Ok lets come up with the IW guess, if we have a srtt */
2005 		if (rack->rc_tp->t_srtt == 0) {
2006 			/*
2007 			 * Go with old pacing method
2008 			 * i.e. burst mitigation only.
2009 			 */
2010 			return (0);
2011 		}
2012 		/* Ok lets get the initial TCP win (not racks) */
2013 		bw = tcp_compute_initwnd(tcp_maxseg(rack->rc_tp));
2014 		srtt = (uint64_t)rack->rc_tp->t_srtt;
2015 		bw *= (uint64_t)USECS_IN_SECOND;
2016 		bw /= srtt;
2017 		if (rack->r_ctl.bw_rate_cap && (bw > rack->r_ctl.bw_rate_cap))
2018 			bw = rack->r_ctl.bw_rate_cap;
2019 		return (bw);
2020 	} else {
2021 		uint64_t bw;
2022 
2023 		if (rack->r_ctl.num_measurements >= RACK_REQ_AVG) {
2024 			/* Averaging is done, we can return the value */
2025 			bw = rack->r_ctl.gp_bw;
2026 		} else {
2027 			/* Still doing initial average must calculate */
2028 			bw = rack->r_ctl.gp_bw / rack->r_ctl.num_measurements;
2029 		}
2030 #ifdef NETFLIX_PEAKRATE
2031 		if ((rack->rc_tp->t_maxpeakrate) &&
2032 		    (bw > rack->rc_tp->t_maxpeakrate)) {
2033 			/* The user has set a peak rate to pace at
2034 			 * don't allow us to pace faster than that.
2035 			 */
2036 			return (rack->rc_tp->t_maxpeakrate);
2037 		}
2038 #endif
2039 		if (rack->r_ctl.bw_rate_cap && (bw > rack->r_ctl.bw_rate_cap))
2040 			bw = rack->r_ctl.bw_rate_cap;
2041 		return (bw);
2042 	}
2043 }
2044 
2045 static uint16_t
2046 rack_get_output_gain(struct tcp_rack *rack, struct rack_sendmap *rsm)
2047 {
2048 	if (rack->use_fixed_rate) {
2049 		return (100);
2050 	} else if (rack->in_probe_rtt && (rsm == NULL))
2051 		return (rack->r_ctl.rack_per_of_gp_probertt);
2052 	else if ((IN_FASTRECOVERY(rack->rc_tp->t_flags) &&
2053 		  rack->r_ctl.rack_per_of_gp_rec)) {
2054 		if (rsm) {
2055 			/* a retransmission always use the recovery rate */
2056 			return (rack->r_ctl.rack_per_of_gp_rec);
2057 		} else if (rack->rack_rec_nonrxt_use_cr) {
2058 			/* Directed to use the configured rate */
2059 			goto configured_rate;
2060 		} else if (rack->rack_no_prr &&
2061 			   (rack->r_ctl.rack_per_of_gp_rec > 100)) {
2062 			/* No PRR, lets just use the b/w estimate only */
2063 			return (100);
2064 		} else {
2065 			/*
2066 			 * Here we may have a non-retransmit but we
2067 			 * have no overrides, so just use the recovery
2068 			 * rate (prr is in effect).
2069 			 */
2070 			return (rack->r_ctl.rack_per_of_gp_rec);
2071 		}
2072 	}
2073 configured_rate:
2074 	/* For the configured rate we look at our cwnd vs the ssthresh */
2075 	if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh)
2076 		return (rack->r_ctl.rack_per_of_gp_ss);
2077 	else
2078 		return (rack->r_ctl.rack_per_of_gp_ca);
2079 }
2080 
2081 static void
2082 rack_log_dsack_event(struct tcp_rack *rack, uint8_t mod, uint32_t flex4, uint32_t flex5, uint32_t flex6)
2083 {
2084 	/*
2085 	 * Types of logs (mod value)
2086 	 * 1 = dsack_persists reduced by 1 via T-O or fast recovery exit.
2087 	 * 2 = a dsack round begins, persist is reset to 16.
2088 	 * 3 = a dsack round ends
2089 	 * 4 = Dsack option increases rack rtt flex5 is the srtt input, flex6 is thresh
2090 	 * 5 = Socket option set changing the control flags rc_rack_tmr_std_based, rc_rack_use_dsack
2091 	 * 6 = Final rack rtt, flex4 is srtt and flex6 is final limited thresh.
2092 	 */
2093 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2094 		union tcp_log_stackspecific log;
2095 		struct timeval tv;
2096 
2097 		memset(&log, 0, sizeof(log));
2098 		log.u_bbr.flex1 = rack->rc_rack_tmr_std_based;
2099 		log.u_bbr.flex1 <<= 1;
2100 		log.u_bbr.flex1 |= rack->rc_rack_use_dsack;
2101 		log.u_bbr.flex1 <<= 1;
2102 		log.u_bbr.flex1 |= rack->rc_dsack_round_seen;
2103 		log.u_bbr.flex2 = rack->r_ctl.dsack_round_end;
2104 		log.u_bbr.flex3 = rack->r_ctl.num_dsack;
2105 		log.u_bbr.flex4 = flex4;
2106 		log.u_bbr.flex5 = flex5;
2107 		log.u_bbr.flex6 = flex6;
2108 		log.u_bbr.flex7 = rack->r_ctl.dsack_persist;
2109 		log.u_bbr.flex8 = mod;
2110 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2111 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2112 		    &rack->rc_inp->inp_socket->so_rcv,
2113 		    &rack->rc_inp->inp_socket->so_snd,
2114 		    RACK_DSACK_HANDLING, 0,
2115 		    0, &log, false, &tv);
2116 	}
2117 }
2118 
2119 static void
2120 rack_log_hdwr_pacing(struct tcp_rack *rack,
2121 		     uint64_t rate, uint64_t hw_rate, int line,
2122 		     int error, uint16_t mod)
2123 {
2124 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2125 		union tcp_log_stackspecific log;
2126 		struct timeval tv;
2127 		const struct ifnet *ifp;
2128 
2129 		memset(&log, 0, sizeof(log));
2130 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2131 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2132 		if (rack->r_ctl.crte) {
2133 			ifp = rack->r_ctl.crte->ptbl->rs_ifp;
2134 		} else if (rack->rc_inp->inp_route.ro_nh &&
2135 			   rack->rc_inp->inp_route.ro_nh->nh_ifp) {
2136 			ifp = rack->rc_inp->inp_route.ro_nh->nh_ifp;
2137 		} else
2138 			ifp = NULL;
2139 		if (ifp) {
2140 			log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2141 			log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2142 		}
2143 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2144 		log.u_bbr.bw_inuse = rate;
2145 		log.u_bbr.flex5 = line;
2146 		log.u_bbr.flex6 = error;
2147 		log.u_bbr.flex7 = mod;
2148 		log.u_bbr.applimited = rack->r_ctl.rc_pace_max_segs;
2149 		log.u_bbr.flex8 = rack->use_fixed_rate;
2150 		log.u_bbr.flex8 <<= 1;
2151 		log.u_bbr.flex8 |= rack->rack_hdrw_pacing;
2152 		log.u_bbr.pkts_out = rack->rc_tp->t_maxseg;
2153 		log.u_bbr.delRate = rack->r_ctl.crte_prev_rate;
2154 		if (rack->r_ctl.crte)
2155 			log.u_bbr.cur_del_rate = rack->r_ctl.crte->rate;
2156 		else
2157 			log.u_bbr.cur_del_rate = 0;
2158 		log.u_bbr.rttProp = rack->r_ctl.last_hw_bw_req;
2159 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2160 		    &rack->rc_inp->inp_socket->so_rcv,
2161 		    &rack->rc_inp->inp_socket->so_snd,
2162 		    BBR_LOG_HDWR_PACE, 0,
2163 		    0, &log, false, &tv);
2164 	}
2165 }
2166 
2167 static uint64_t
2168 rack_get_output_bw(struct tcp_rack *rack, uint64_t bw, struct rack_sendmap *rsm, int *capped)
2169 {
2170 	/*
2171 	 * We allow rack_per_of_gp_xx to dictate our bw rate we want.
2172 	 */
2173 	uint64_t bw_est, high_rate;
2174 	uint64_t gain;
2175 
2176 	gain = (uint64_t)rack_get_output_gain(rack, rsm);
2177 	bw_est = bw * gain;
2178 	bw_est /= (uint64_t)100;
2179 	/* Never fall below the minimum (def 64kbps) */
2180 	if (bw_est < RACK_MIN_BW)
2181 		bw_est = RACK_MIN_BW;
2182 	if (rack->r_rack_hw_rate_caps) {
2183 		/* Rate caps are in place */
2184 		if (rack->r_ctl.crte != NULL) {
2185 			/* We have a hdwr rate already */
2186 			high_rate = tcp_hw_highest_rate(rack->r_ctl.crte);
2187 			if (bw_est >= high_rate) {
2188 				/* We are capping bw at the highest rate table entry */
2189 				rack_log_hdwr_pacing(rack,
2190 						     bw_est, high_rate, __LINE__,
2191 						     0, 3);
2192 				bw_est = high_rate;
2193 				if (capped)
2194 					*capped = 1;
2195 			}
2196 		} else if ((rack->rack_hdrw_pacing == 0) &&
2197 			   (rack->rack_hdw_pace_ena) &&
2198 			   (rack->rack_attempt_hdwr_pace == 0) &&
2199 			   (rack->rc_inp->inp_route.ro_nh != NULL) &&
2200 			   (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
2201 			/*
2202 			 * Special case, we have not yet attempted hardware
2203 			 * pacing, and yet we may, when we do, find out if we are
2204 			 * above the highest rate. We need to know the maxbw for the interface
2205 			 * in question (if it supports ratelimiting). We get back
2206 			 * a 0, if the interface is not found in the RL lists.
2207 			 */
2208 			high_rate = tcp_hw_highest_rate_ifp(rack->rc_inp->inp_route.ro_nh->nh_ifp, rack->rc_inp);
2209 			if (high_rate) {
2210 				/* Yep, we have a rate is it above this rate? */
2211 				if (bw_est > high_rate) {
2212 					bw_est = high_rate;
2213 					if (capped)
2214 						*capped = 1;
2215 				}
2216 			}
2217 		}
2218 	}
2219 	return (bw_est);
2220 }
2221 
2222 static void
2223 rack_log_retran_reason(struct tcp_rack *rack, struct rack_sendmap *rsm, uint32_t tsused, uint32_t thresh, int mod)
2224 {
2225 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2226 		union tcp_log_stackspecific log;
2227 		struct timeval tv;
2228 
2229 		if ((mod != 1) && (rack_verbose_logging == 0)) {
2230 			/*
2231 			 * We get 3 values currently for mod
2232 			 * 1 - We are retransmitting and this tells the reason.
2233 			 * 2 - We are clearing a dup-ack count.
2234 			 * 3 - We are incrementing a dup-ack count.
2235 			 *
2236 			 * The clear/increment are only logged
2237 			 * if you have BBverbose on.
2238 			 */
2239 			return;
2240 		}
2241 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2242 		log.u_bbr.flex1 = tsused;
2243 		log.u_bbr.flex2 = thresh;
2244 		log.u_bbr.flex3 = rsm->r_flags;
2245 		log.u_bbr.flex4 = rsm->r_dupack;
2246 		log.u_bbr.flex5 = rsm->r_start;
2247 		log.u_bbr.flex6 = rsm->r_end;
2248 		log.u_bbr.flex8 = mod;
2249 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2250 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2251 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2252 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2253 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2254 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2255 		log.u_bbr.pacing_gain = rack->r_must_retran;
2256 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2257 		    &rack->rc_inp->inp_socket->so_rcv,
2258 		    &rack->rc_inp->inp_socket->so_snd,
2259 		    BBR_LOG_SETTINGS_CHG, 0,
2260 		    0, &log, false, &tv);
2261 	}
2262 }
2263 
2264 static void
2265 rack_log_to_start(struct tcp_rack *rack, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2266 {
2267 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2268 		union tcp_log_stackspecific log;
2269 		struct timeval tv;
2270 
2271 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2272 		log.u_bbr.flex1 = rack->rc_tp->t_srtt;
2273 		log.u_bbr.flex2 = to;
2274 		log.u_bbr.flex3 = rack->r_ctl.rc_hpts_flags;
2275 		log.u_bbr.flex4 = slot;
2276 		log.u_bbr.flex5 = rack->rc_inp->inp_hptsslot;
2277 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2278 		log.u_bbr.flex7 = rack->rc_in_persist;
2279 		log.u_bbr.flex8 = which;
2280 		if (rack->rack_no_prr)
2281 			log.u_bbr.pkts_out = 0;
2282 		else
2283 			log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
2284 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2285 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2286 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2287 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2288 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2289 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2290 		log.u_bbr.pacing_gain = rack->r_must_retran;
2291 		log.u_bbr.lt_epoch = rack->rc_tp->t_rxtshift;
2292 		log.u_bbr.lost = rack_rto_min;
2293 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2294 		    &rack->rc_inp->inp_socket->so_rcv,
2295 		    &rack->rc_inp->inp_socket->so_snd,
2296 		    BBR_LOG_TIMERSTAR, 0,
2297 		    0, &log, false, &tv);
2298 	}
2299 }
2300 
2301 static void
2302 rack_log_to_event(struct tcp_rack *rack, int32_t to_num, struct rack_sendmap *rsm)
2303 {
2304 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2305 		union tcp_log_stackspecific log;
2306 		struct timeval tv;
2307 
2308 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2309 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2310 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2311 		log.u_bbr.flex8 = to_num;
2312 		log.u_bbr.flex1 = rack->r_ctl.rc_rack_min_rtt;
2313 		log.u_bbr.flex2 = rack->rc_rack_rtt;
2314 		if (rsm == NULL)
2315 			log.u_bbr.flex3 = 0;
2316 		else
2317 			log.u_bbr.flex3 = rsm->r_end - rsm->r_start;
2318 		if (rack->rack_no_prr)
2319 			log.u_bbr.flex5 = 0;
2320 		else
2321 			log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2322 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2323 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2324 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2325 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2326 		log.u_bbr.pacing_gain = rack->r_must_retran;
2327 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2328 		    &rack->rc_inp->inp_socket->so_rcv,
2329 		    &rack->rc_inp->inp_socket->so_snd,
2330 		    BBR_LOG_RTO, 0,
2331 		    0, &log, false, &tv);
2332 	}
2333 }
2334 
2335 static void
2336 rack_log_map_chg(struct tcpcb *tp, struct tcp_rack *rack,
2337 		 struct rack_sendmap *prev,
2338 		 struct rack_sendmap *rsm,
2339 		 struct rack_sendmap *next,
2340 		 int flag, uint32_t th_ack, int line)
2341 {
2342 	if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2343 		union tcp_log_stackspecific log;
2344 		struct timeval tv;
2345 
2346 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2347 		log.u_bbr.flex8 = flag;
2348 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2349 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2350 		log.u_bbr.cur_del_rate = (uint64_t)prev;
2351 		log.u_bbr.delRate = (uint64_t)rsm;
2352 		log.u_bbr.rttProp = (uint64_t)next;
2353 		log.u_bbr.flex7 = 0;
2354 		if (prev) {
2355 			log.u_bbr.flex1 = prev->r_start;
2356 			log.u_bbr.flex2 = prev->r_end;
2357 			log.u_bbr.flex7 |= 0x4;
2358 		}
2359 		if (rsm) {
2360 			log.u_bbr.flex3 = rsm->r_start;
2361 			log.u_bbr.flex4 = rsm->r_end;
2362 			log.u_bbr.flex7 |= 0x2;
2363 		}
2364 		if (next) {
2365 			log.u_bbr.flex5 = next->r_start;
2366 			log.u_bbr.flex6 = next->r_end;
2367 			log.u_bbr.flex7 |= 0x1;
2368 		}
2369 		log.u_bbr.applimited = line;
2370 		log.u_bbr.pkts_out = th_ack;
2371 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2372 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2373 		if (rack->rack_no_prr)
2374 			log.u_bbr.lost = 0;
2375 		else
2376 			log.u_bbr.lost = rack->r_ctl.rc_prr_sndcnt;
2377 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2378 		    &rack->rc_inp->inp_socket->so_rcv,
2379 		    &rack->rc_inp->inp_socket->so_snd,
2380 		    TCP_LOG_MAPCHG, 0,
2381 		    0, &log, false, &tv);
2382 	}
2383 }
2384 
2385 static void
2386 rack_log_rtt_upd(struct tcpcb *tp, struct tcp_rack *rack, uint32_t t, uint32_t len,
2387 		 struct rack_sendmap *rsm, int conf)
2388 {
2389 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2390 		union tcp_log_stackspecific log;
2391 		struct timeval tv;
2392 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2393 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2394 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2395 		log.u_bbr.flex1 = t;
2396 		log.u_bbr.flex2 = len;
2397 		log.u_bbr.flex3 = rack->r_ctl.rc_rack_min_rtt;
2398 		log.u_bbr.flex4 = rack->r_ctl.rack_rs.rs_rtt_lowest;
2399 		log.u_bbr.flex5 = rack->r_ctl.rack_rs.rs_rtt_highest;
2400 		log.u_bbr.flex6 = rack->r_ctl.rack_rs.rs_us_rtrcnt;
2401 		log.u_bbr.flex7 = conf;
2402 		log.u_bbr.rttProp = (uint64_t)rack->r_ctl.rack_rs.rs_rtt_tot;
2403 		log.u_bbr.flex8 = rack->r_ctl.rc_rate_sample_method;
2404 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2405 		log.u_bbr.delivered = rack->r_ctl.rack_rs.rs_us_rtrcnt;
2406 		log.u_bbr.pkts_out = rack->r_ctl.rack_rs.rs_flags;
2407 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2408 		if (rsm) {
2409 			log.u_bbr.pkt_epoch = rsm->r_start;
2410 			log.u_bbr.lost = rsm->r_end;
2411 			log.u_bbr.cwnd_gain = rsm->r_rtr_cnt;
2412 			log.u_bbr.pacing_gain = rsm->r_flags;
2413 		} else {
2414 			/* Its a SYN */
2415 			log.u_bbr.pkt_epoch = rack->rc_tp->iss;
2416 			log.u_bbr.lost = 0;
2417 			log.u_bbr.cwnd_gain = 0;
2418 			log.u_bbr.pacing_gain = 0;
2419 		}
2420 		/* Write out general bits of interest rrs here */
2421 		log.u_bbr.use_lt_bw = rack->rc_highly_buffered;
2422 		log.u_bbr.use_lt_bw <<= 1;
2423 		log.u_bbr.use_lt_bw |= rack->forced_ack;
2424 		log.u_bbr.use_lt_bw <<= 1;
2425 		log.u_bbr.use_lt_bw |= rack->rc_gp_dyn_mul;
2426 		log.u_bbr.use_lt_bw <<= 1;
2427 		log.u_bbr.use_lt_bw |= rack->in_probe_rtt;
2428 		log.u_bbr.use_lt_bw <<= 1;
2429 		log.u_bbr.use_lt_bw |= rack->measure_saw_probe_rtt;
2430 		log.u_bbr.use_lt_bw <<= 1;
2431 		log.u_bbr.use_lt_bw |= rack->app_limited_needs_set;
2432 		log.u_bbr.use_lt_bw <<= 1;
2433 		log.u_bbr.use_lt_bw |= rack->rc_gp_filled;
2434 		log.u_bbr.use_lt_bw <<= 1;
2435 		log.u_bbr.use_lt_bw |= rack->rc_dragged_bottom;
2436 		log.u_bbr.applimited = rack->r_ctl.rc_target_probertt_flight;
2437 		log.u_bbr.epoch = rack->r_ctl.rc_time_probertt_starts;
2438 		log.u_bbr.lt_epoch = rack->r_ctl.rc_time_probertt_entered;
2439 		log.u_bbr.cur_del_rate = rack->r_ctl.rc_lower_rtt_us_cts;
2440 		log.u_bbr.delRate = rack->r_ctl.rc_gp_srtt;
2441 		log.u_bbr.bw_inuse = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
2442 		log.u_bbr.bw_inuse <<= 32;
2443 		if (rsm)
2444 			log.u_bbr.bw_inuse |= ((uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
2445 		TCP_LOG_EVENTP(tp, NULL,
2446 		    &rack->rc_inp->inp_socket->so_rcv,
2447 		    &rack->rc_inp->inp_socket->so_snd,
2448 		    BBR_LOG_BBRRTT, 0,
2449 		    0, &log, false, &tv);
2450 
2451 
2452 	}
2453 }
2454 
2455 static void
2456 rack_log_rtt_sample(struct tcp_rack *rack, uint32_t rtt)
2457 {
2458 	/*
2459 	 * Log the rtt sample we are
2460 	 * applying to the srtt algorithm in
2461 	 * useconds.
2462 	 */
2463 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2464 		union tcp_log_stackspecific log;
2465 		struct timeval tv;
2466 
2467 		/* Convert our ms to a microsecond */
2468 		memset(&log, 0, sizeof(log));
2469 		log.u_bbr.flex1 = rtt;
2470 		log.u_bbr.flex2 = rack->r_ctl.ack_count;
2471 		log.u_bbr.flex3 = rack->r_ctl.sack_count;
2472 		log.u_bbr.flex4 = rack->r_ctl.sack_noextra_move;
2473 		log.u_bbr.flex5 = rack->r_ctl.sack_moved_extra;
2474 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2475 		log.u_bbr.flex7 = 1;
2476 		log.u_bbr.flex8 = rack->sack_attack_disable;
2477 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2478 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2479 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2480 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2481 		log.u_bbr.pacing_gain = rack->r_must_retran;
2482 		/*
2483 		 * We capture in delRate the upper 32 bits as
2484 		 * the confidence level we had declared, and the
2485 		 * lower 32 bits as the actual RTT using the arrival
2486 		 * timestamp.
2487 		 */
2488 		log.u_bbr.delRate = rack->r_ctl.rack_rs.confidence;
2489 		log.u_bbr.delRate <<= 32;
2490 		log.u_bbr.delRate |= rack->r_ctl.rack_rs.rs_us_rtt;
2491 		/* Lets capture all the things that make up t_rtxcur */
2492 		log.u_bbr.applimited = rack_rto_min;
2493 		log.u_bbr.epoch = rack_rto_max;
2494 		log.u_bbr.lt_epoch = rack->r_ctl.timer_slop;
2495 		log.u_bbr.lost = rack_rto_min;
2496 		log.u_bbr.pkt_epoch = TICKS_2_USEC(tcp_rexmit_slop);
2497 		log.u_bbr.rttProp = RACK_REXMTVAL(rack->rc_tp);
2498 		log.u_bbr.bw_inuse = rack->r_ctl.act_rcv_time.tv_sec;
2499 		log.u_bbr.bw_inuse *= HPTS_USEC_IN_SEC;
2500 		log.u_bbr.bw_inuse += rack->r_ctl.act_rcv_time.tv_usec;
2501 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2502 		    &rack->rc_inp->inp_socket->so_rcv,
2503 		    &rack->rc_inp->inp_socket->so_snd,
2504 		    TCP_LOG_RTT, 0,
2505 		    0, &log, false, &tv);
2506 	}
2507 }
2508 
2509 static void
2510 rack_log_rtt_sample_calc(struct tcp_rack *rack, uint32_t rtt, uint32_t send_time, uint32_t ack_time, int where)
2511 {
2512 	if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2513 		union tcp_log_stackspecific log;
2514 		struct timeval tv;
2515 
2516 		/* Convert our ms to a microsecond */
2517 		memset(&log, 0, sizeof(log));
2518 		log.u_bbr.flex1 = rtt;
2519 		log.u_bbr.flex2 = send_time;
2520 		log.u_bbr.flex3 = ack_time;
2521 		log.u_bbr.flex4 = where;
2522 		log.u_bbr.flex7 = 2;
2523 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2524 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2525 		    &rack->rc_inp->inp_socket->so_rcv,
2526 		    &rack->rc_inp->inp_socket->so_snd,
2527 		    TCP_LOG_RTT, 0,
2528 		    0, &log, false, &tv);
2529 	}
2530 }
2531 
2532 
2533 
2534 static inline void
2535 rack_log_progress_event(struct tcp_rack *rack, struct tcpcb *tp, uint32_t tick,  int event, int line)
2536 {
2537 	if (rack_verbose_logging && (tp->t_logstate != TCP_LOG_STATE_OFF)) {
2538 		union tcp_log_stackspecific log;
2539 		struct timeval tv;
2540 
2541 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2542 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2543 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2544 		log.u_bbr.flex1 = line;
2545 		log.u_bbr.flex2 = tick;
2546 		log.u_bbr.flex3 = tp->t_maxunacktime;
2547 		log.u_bbr.flex4 = tp->t_acktime;
2548 		log.u_bbr.flex8 = event;
2549 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2550 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2551 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2552 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2553 		log.u_bbr.pacing_gain = rack->r_must_retran;
2554 		TCP_LOG_EVENTP(tp, NULL,
2555 		    &rack->rc_inp->inp_socket->so_rcv,
2556 		    &rack->rc_inp->inp_socket->so_snd,
2557 		    BBR_LOG_PROGRESS, 0,
2558 		    0, &log, false, &tv);
2559 	}
2560 }
2561 
2562 static void
2563 rack_log_type_bbrsnd(struct tcp_rack *rack, uint32_t len, uint32_t slot, uint32_t cts, struct timeval *tv)
2564 {
2565 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2566 		union tcp_log_stackspecific log;
2567 
2568 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2569 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2570 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2571 		log.u_bbr.flex1 = slot;
2572 		if (rack->rack_no_prr)
2573 			log.u_bbr.flex2 = 0;
2574 		else
2575 			log.u_bbr.flex2 = rack->r_ctl.rc_prr_sndcnt;
2576 		log.u_bbr.flex7 = (0x0000ffff & rack->r_ctl.rc_hpts_flags);
2577 		log.u_bbr.flex8 = rack->rc_in_persist;
2578 		log.u_bbr.timeStamp = cts;
2579 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2580 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2581 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2582 		log.u_bbr.pacing_gain = rack->r_must_retran;
2583 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2584 		    &rack->rc_inp->inp_socket->so_rcv,
2585 		    &rack->rc_inp->inp_socket->so_snd,
2586 		    BBR_LOG_BBRSND, 0,
2587 		    0, &log, false, tv);
2588 	}
2589 }
2590 
2591 static void
2592 rack_log_doseg_done(struct tcp_rack *rack, uint32_t cts, int32_t nxt_pkt, int32_t did_out, int way_out, int nsegs)
2593 {
2594 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2595 		union tcp_log_stackspecific log;
2596 		struct timeval tv;
2597 
2598 		memset(&log, 0, sizeof(log));
2599 		log.u_bbr.flex1 = did_out;
2600 		log.u_bbr.flex2 = nxt_pkt;
2601 		log.u_bbr.flex3 = way_out;
2602 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
2603 		if (rack->rack_no_prr)
2604 			log.u_bbr.flex5 = 0;
2605 		else
2606 			log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2607 		log.u_bbr.flex6 = nsegs;
2608 		log.u_bbr.applimited = rack->r_ctl.rc_pace_min_segs;
2609 		log.u_bbr.flex7 = rack->rc_ack_can_sendout_data;	/* Do we have ack-can-send set */
2610 		log.u_bbr.flex7 <<= 1;
2611 		log.u_bbr.flex7 |= rack->r_fast_output;	/* is fast output primed */
2612 		log.u_bbr.flex7 <<= 1;
2613 		log.u_bbr.flex7 |= rack->r_wanted_output;	/* Do we want output */
2614 		log.u_bbr.flex8 = rack->rc_in_persist;
2615 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2616 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2617 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2618 		log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
2619 		log.u_bbr.use_lt_bw <<= 1;
2620 		log.u_bbr.use_lt_bw |= rack->r_might_revert;
2621 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2622 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2623 		log.u_bbr.pacing_gain = rack->r_must_retran;
2624 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2625 		    &rack->rc_inp->inp_socket->so_rcv,
2626 		    &rack->rc_inp->inp_socket->so_snd,
2627 		    BBR_LOG_DOSEG_DONE, 0,
2628 		    0, &log, false, &tv);
2629 	}
2630 }
2631 
2632 static void
2633 rack_log_type_pacing_sizes(struct tcpcb *tp, struct tcp_rack *rack, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint8_t frm)
2634 {
2635 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2636 		union tcp_log_stackspecific log;
2637 		struct timeval tv;
2638 		uint32_t cts;
2639 
2640 		memset(&log, 0, sizeof(log));
2641 		cts = tcp_get_usecs(&tv);
2642 		log.u_bbr.flex1 = rack->r_ctl.rc_pace_min_segs;
2643 		log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
2644 		log.u_bbr.flex4 = arg1;
2645 		log.u_bbr.flex5 = arg2;
2646 		log.u_bbr.flex6 = arg3;
2647 		log.u_bbr.flex8 = frm;
2648 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2649 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2650 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2651 		log.u_bbr.applimited = rack->r_ctl.rc_sacked;
2652 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2653 		log.u_bbr.pacing_gain = rack->r_must_retran;
2654 		TCP_LOG_EVENTP(tp, NULL,
2655 		    &tp->t_inpcb->inp_socket->so_rcv,
2656 		    &tp->t_inpcb->inp_socket->so_snd,
2657 		    TCP_HDWR_PACE_SIZE, 0,
2658 		    0, &log, false, &tv);
2659 	}
2660 }
2661 
2662 static void
2663 rack_log_type_just_return(struct tcp_rack *rack, uint32_t cts, uint32_t tlen, uint32_t slot,
2664 			  uint8_t hpts_calling, int reason, uint32_t cwnd_to_use)
2665 {
2666 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2667 		union tcp_log_stackspecific log;
2668 		struct timeval tv;
2669 
2670 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2671 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2672 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2673 		log.u_bbr.flex1 = slot;
2674 		log.u_bbr.flex2 = rack->r_ctl.rc_hpts_flags;
2675 		log.u_bbr.flex4 = reason;
2676 		if (rack->rack_no_prr)
2677 			log.u_bbr.flex5 = 0;
2678 		else
2679 			log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2680 		log.u_bbr.flex7 = hpts_calling;
2681 		log.u_bbr.flex8 = rack->rc_in_persist;
2682 		log.u_bbr.lt_epoch = cwnd_to_use;
2683 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2684 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2685 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2686 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2687 		log.u_bbr.pacing_gain = rack->r_must_retran;
2688 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2689 		    &rack->rc_inp->inp_socket->so_rcv,
2690 		    &rack->rc_inp->inp_socket->so_snd,
2691 		    BBR_LOG_JUSTRET, 0,
2692 		    tlen, &log, false, &tv);
2693 	}
2694 }
2695 
2696 static void
2697 rack_log_to_cancel(struct tcp_rack *rack, int32_t hpts_removed, int line, uint32_t us_cts,
2698 		   struct timeval *tv, uint32_t flags_on_entry)
2699 {
2700 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2701 		union tcp_log_stackspecific log;
2702 
2703 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2704 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
2705 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
2706 		log.u_bbr.flex1 = line;
2707 		log.u_bbr.flex2 = rack->r_ctl.rc_last_output_to;
2708 		log.u_bbr.flex3 = flags_on_entry;
2709 		log.u_bbr.flex4 = us_cts;
2710 		if (rack->rack_no_prr)
2711 			log.u_bbr.flex5 = 0;
2712 		else
2713 			log.u_bbr.flex5 = rack->r_ctl.rc_prr_sndcnt;
2714 		log.u_bbr.flex6 = rack->rc_tp->t_rxtcur;
2715 		log.u_bbr.flex7 = hpts_removed;
2716 		log.u_bbr.flex8 = 1;
2717 		log.u_bbr.applimited = rack->r_ctl.rc_hpts_flags;
2718 		log.u_bbr.timeStamp = us_cts;
2719 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2720 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2721 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2722 		log.u_bbr.pacing_gain = rack->r_must_retran;
2723 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2724 		    &rack->rc_inp->inp_socket->so_rcv,
2725 		    &rack->rc_inp->inp_socket->so_snd,
2726 		    BBR_LOG_TIMERCANC, 0,
2727 		    0, &log, false, tv);
2728 	}
2729 }
2730 
2731 static void
2732 rack_log_alt_to_to_cancel(struct tcp_rack *rack,
2733 			  uint32_t flex1, uint32_t flex2,
2734 			  uint32_t flex3, uint32_t flex4,
2735 			  uint32_t flex5, uint32_t flex6,
2736 			  uint16_t flex7, uint8_t mod)
2737 {
2738 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2739 		union tcp_log_stackspecific log;
2740 		struct timeval tv;
2741 
2742 		if (mod == 1) {
2743 			/* No you can't use 1, its for the real to cancel */
2744 			return;
2745 		}
2746 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2747 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2748 		log.u_bbr.flex1 = flex1;
2749 		log.u_bbr.flex2 = flex2;
2750 		log.u_bbr.flex3 = flex3;
2751 		log.u_bbr.flex4 = flex4;
2752 		log.u_bbr.flex5 = flex5;
2753 		log.u_bbr.flex6 = flex6;
2754 		log.u_bbr.flex7 = flex7;
2755 		log.u_bbr.flex8 = mod;
2756 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2757 		    &rack->rc_inp->inp_socket->so_rcv,
2758 		    &rack->rc_inp->inp_socket->so_snd,
2759 		    BBR_LOG_TIMERCANC, 0,
2760 		    0, &log, false, &tv);
2761 	}
2762 }
2763 
2764 static void
2765 rack_log_to_processing(struct tcp_rack *rack, uint32_t cts, int32_t ret, int32_t timers)
2766 {
2767 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2768 		union tcp_log_stackspecific log;
2769 		struct timeval tv;
2770 
2771 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2772 		log.u_bbr.flex1 = timers;
2773 		log.u_bbr.flex2 = ret;
2774 		log.u_bbr.flex3 = rack->r_ctl.rc_timer_exp;
2775 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
2776 		log.u_bbr.flex5 = cts;
2777 		if (rack->rack_no_prr)
2778 			log.u_bbr.flex6 = 0;
2779 		else
2780 			log.u_bbr.flex6 = rack->r_ctl.rc_prr_sndcnt;
2781 		log.u_bbr.pkts_out = rack->r_ctl.rc_out_at_rto;
2782 		log.u_bbr.delivered = rack->r_ctl.rc_snd_max_at_rto;
2783 		log.u_bbr.pacing_gain = rack->r_must_retran;
2784 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2785 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2786 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2787 		    &rack->rc_inp->inp_socket->so_rcv,
2788 		    &rack->rc_inp->inp_socket->so_snd,
2789 		    BBR_LOG_TO_PROCESS, 0,
2790 		    0, &log, false, &tv);
2791 	}
2792 }
2793 
2794 static void
2795 rack_log_to_prr(struct tcp_rack *rack, int frm, int orig_cwnd)
2796 {
2797 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2798 		union tcp_log_stackspecific log;
2799 		struct timeval tv;
2800 
2801 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2802 		log.u_bbr.flex1 = rack->r_ctl.rc_prr_out;
2803 		log.u_bbr.flex2 = rack->r_ctl.rc_prr_recovery_fs;
2804 		if (rack->rack_no_prr)
2805 			log.u_bbr.flex3 = 0;
2806 		else
2807 			log.u_bbr.flex3 = rack->r_ctl.rc_prr_sndcnt;
2808 		log.u_bbr.flex4 = rack->r_ctl.rc_prr_delivered;
2809 		log.u_bbr.flex5 = rack->r_ctl.rc_sacked;
2810 		log.u_bbr.flex6 = rack->r_ctl.rc_holes_rxt;
2811 		log.u_bbr.flex8 = frm;
2812 		log.u_bbr.pkts_out = orig_cwnd;
2813 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2814 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2815 		log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
2816 		log.u_bbr.use_lt_bw <<= 1;
2817 		log.u_bbr.use_lt_bw |= rack->r_might_revert;
2818 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2819 		    &rack->rc_inp->inp_socket->so_rcv,
2820 		    &rack->rc_inp->inp_socket->so_snd,
2821 		    BBR_LOG_BBRUPD, 0,
2822 		    0, &log, false, &tv);
2823 	}
2824 }
2825 
2826 #ifdef NETFLIX_EXP_DETECTION
2827 static void
2828 rack_log_sad(struct tcp_rack *rack, int event)
2829 {
2830 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2831 		union tcp_log_stackspecific log;
2832 		struct timeval tv;
2833 
2834 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
2835 		log.u_bbr.flex1 = rack->r_ctl.sack_count;
2836 		log.u_bbr.flex2 = rack->r_ctl.ack_count;
2837 		log.u_bbr.flex3 = rack->r_ctl.sack_moved_extra;
2838 		log.u_bbr.flex4 = rack->r_ctl.sack_noextra_move;
2839 		log.u_bbr.flex5 = rack->r_ctl.rc_num_maps_alloced;
2840 		log.u_bbr.flex6 = tcp_sack_to_ack_thresh;
2841 		log.u_bbr.pkts_out = tcp_sack_to_move_thresh;
2842 		log.u_bbr.lt_epoch = (tcp_force_detection << 8);
2843 		log.u_bbr.lt_epoch |= rack->do_detection;
2844 		log.u_bbr.applimited = tcp_map_minimum;
2845 		log.u_bbr.flex7 = rack->sack_attack_disable;
2846 		log.u_bbr.flex8 = event;
2847 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
2848 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
2849 		log.u_bbr.delivered = tcp_sad_decay_val;
2850 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
2851 		    &rack->rc_inp->inp_socket->so_rcv,
2852 		    &rack->rc_inp->inp_socket->so_snd,
2853 		    TCP_SAD_DETECTION, 0,
2854 		    0, &log, false, &tv);
2855 	}
2856 }
2857 #endif
2858 
2859 static void
2860 rack_counter_destroy(void)
2861 {
2862 	int i;
2863 
2864 	counter_u64_free(rack_fto_send);
2865 	counter_u64_free(rack_fto_rsm_send);
2866 	counter_u64_free(rack_nfto_resend);
2867 	counter_u64_free(rack_hw_pace_init_fail);
2868 	counter_u64_free(rack_hw_pace_lost);
2869 	counter_u64_free(rack_non_fto_send);
2870 	counter_u64_free(rack_extended_rfo);
2871 	counter_u64_free(rack_ack_total);
2872 	counter_u64_free(rack_express_sack);
2873 	counter_u64_free(rack_sack_total);
2874 	counter_u64_free(rack_move_none);
2875 	counter_u64_free(rack_move_some);
2876 	counter_u64_free(rack_sack_attacks_detected);
2877 	counter_u64_free(rack_sack_attacks_reversed);
2878 	counter_u64_free(rack_sack_used_next_merge);
2879 	counter_u64_free(rack_sack_used_prev_merge);
2880 	counter_u64_free(rack_badfr);
2881 	counter_u64_free(rack_badfr_bytes);
2882 	counter_u64_free(rack_rtm_prr_retran);
2883 	counter_u64_free(rack_rtm_prr_newdata);
2884 	counter_u64_free(rack_timestamp_mismatch);
2885 	counter_u64_free(rack_find_high);
2886 	counter_u64_free(rack_reorder_seen);
2887 	counter_u64_free(rack_tlp_tot);
2888 	counter_u64_free(rack_tlp_newdata);
2889 	counter_u64_free(rack_tlp_retran);
2890 	counter_u64_free(rack_tlp_retran_bytes);
2891 	counter_u64_free(rack_tlp_retran_fail);
2892 	counter_u64_free(rack_to_tot);
2893 	counter_u64_free(rack_to_arm_rack);
2894 	counter_u64_free(rack_to_arm_tlp);
2895 	counter_u64_free(rack_calc_zero);
2896 	counter_u64_free(rack_calc_nonzero);
2897 	counter_u64_free(rack_paced_segments);
2898 	counter_u64_free(rack_unpaced_segments);
2899 	counter_u64_free(rack_saw_enobuf);
2900 	counter_u64_free(rack_saw_enobuf_hw);
2901 	counter_u64_free(rack_saw_enetunreach);
2902 	counter_u64_free(rack_hot_alloc);
2903 	counter_u64_free(rack_to_alloc);
2904 	counter_u64_free(rack_to_alloc_hard);
2905 	counter_u64_free(rack_to_alloc_emerg);
2906 	counter_u64_free(rack_to_alloc_limited);
2907 	counter_u64_free(rack_alloc_limited_conns);
2908 	counter_u64_free(rack_split_limited);
2909 	for (i = 0; i < MAX_NUM_OF_CNTS; i++) {
2910 		counter_u64_free(rack_proc_comp_ack[i]);
2911 	}
2912 	counter_u64_free(rack_multi_single_eq);
2913 	counter_u64_free(rack_proc_non_comp_ack);
2914 	counter_u64_free(rack_sack_proc_all);
2915 	counter_u64_free(rack_sack_proc_restart);
2916 	counter_u64_free(rack_sack_proc_short);
2917 	counter_u64_free(rack_enter_tlp_calc);
2918 	counter_u64_free(rack_used_tlpmethod);
2919 	counter_u64_free(rack_used_tlpmethod2);
2920 	counter_u64_free(rack_sack_skipped_acked);
2921 	counter_u64_free(rack_sack_splits);
2922 	counter_u64_free(rack_progress_drops);
2923 	counter_u64_free(rack_input_idle_reduces);
2924 	counter_u64_free(rack_collapsed_win);
2925 	counter_u64_free(rack_tlp_does_nada);
2926 	counter_u64_free(rack_try_scwnd);
2927 	counter_u64_free(rack_per_timer_hole);
2928 	counter_u64_free(rack_large_ackcmp);
2929 	counter_u64_free(rack_small_ackcmp);
2930 #ifdef INVARIANTS
2931 	counter_u64_free(rack_adjust_map_bw);
2932 #endif
2933 	COUNTER_ARRAY_FREE(rack_out_size, TCP_MSS_ACCT_SIZE);
2934 	COUNTER_ARRAY_FREE(rack_opts_arry, RACK_OPTS_SIZE);
2935 }
2936 
2937 static struct rack_sendmap *
2938 rack_alloc(struct tcp_rack *rack)
2939 {
2940 	struct rack_sendmap *rsm;
2941 
2942 	/*
2943 	 * First get the top of the list it in
2944 	 * theory is the "hottest" rsm we have,
2945 	 * possibly just freed by ack processing.
2946 	 */
2947 	if (rack->rc_free_cnt > rack_free_cache) {
2948 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
2949 		TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2950 		counter_u64_add(rack_hot_alloc, 1);
2951 		rack->rc_free_cnt--;
2952 		return (rsm);
2953 	}
2954 	/*
2955 	 * Once we get under our free cache we probably
2956 	 * no longer have a "hot" one available. Lets
2957 	 * get one from UMA.
2958 	 */
2959 	rsm = uma_zalloc(rack_zone, M_NOWAIT);
2960 	if (rsm) {
2961 		rack->r_ctl.rc_num_maps_alloced++;
2962 		counter_u64_add(rack_to_alloc, 1);
2963 		return (rsm);
2964 	}
2965 	/*
2966 	 * Dig in to our aux rsm's (the last two) since
2967 	 * UMA failed to get us one.
2968 	 */
2969 	if (rack->rc_free_cnt) {
2970 		counter_u64_add(rack_to_alloc_emerg, 1);
2971 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
2972 		TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
2973 		rack->rc_free_cnt--;
2974 		return (rsm);
2975 	}
2976 	return (NULL);
2977 }
2978 
2979 static struct rack_sendmap *
2980 rack_alloc_full_limit(struct tcp_rack *rack)
2981 {
2982 	if ((V_tcp_map_entries_limit > 0) &&
2983 	    (rack->do_detection == 0) &&
2984 	    (rack->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
2985 		counter_u64_add(rack_to_alloc_limited, 1);
2986 		if (!rack->alloc_limit_reported) {
2987 			rack->alloc_limit_reported = 1;
2988 			counter_u64_add(rack_alloc_limited_conns, 1);
2989 		}
2990 		return (NULL);
2991 	}
2992 	return (rack_alloc(rack));
2993 }
2994 
2995 /* wrapper to allocate a sendmap entry, subject to a specific limit */
2996 static struct rack_sendmap *
2997 rack_alloc_limit(struct tcp_rack *rack, uint8_t limit_type)
2998 {
2999 	struct rack_sendmap *rsm;
3000 
3001 	if (limit_type) {
3002 		/* currently there is only one limit type */
3003 		if (V_tcp_map_split_limit > 0 &&
3004 		    (rack->do_detection == 0) &&
3005 		    rack->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3006 			counter_u64_add(rack_split_limited, 1);
3007 			if (!rack->alloc_limit_reported) {
3008 				rack->alloc_limit_reported = 1;
3009 				counter_u64_add(rack_alloc_limited_conns, 1);
3010 			}
3011 			return (NULL);
3012 		}
3013 	}
3014 
3015 	/* allocate and mark in the limit type, if set */
3016 	rsm = rack_alloc(rack);
3017 	if (rsm != NULL && limit_type) {
3018 		rsm->r_limit_type = limit_type;
3019 		rack->r_ctl.rc_num_split_allocs++;
3020 	}
3021 	return (rsm);
3022 }
3023 
3024 static void
3025 rack_free(struct tcp_rack *rack, struct rack_sendmap *rsm)
3026 {
3027 	if (rsm->r_flags & RACK_APP_LIMITED) {
3028 		if (rack->r_ctl.rc_app_limited_cnt > 0) {
3029 			rack->r_ctl.rc_app_limited_cnt--;
3030 		}
3031 	}
3032 	if (rsm->r_limit_type) {
3033 		/* currently there is only one limit type */
3034 		rack->r_ctl.rc_num_split_allocs--;
3035 	}
3036 	if (rsm == rack->r_ctl.rc_first_appl) {
3037 		if (rack->r_ctl.rc_app_limited_cnt == 0)
3038 			rack->r_ctl.rc_first_appl = NULL;
3039 		else {
3040 			/* Follow the next one out */
3041 			struct rack_sendmap fe;
3042 
3043 			fe.r_start = rsm->r_nseq_appl;
3044 			rack->r_ctl.rc_first_appl = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
3045 		}
3046 	}
3047 	if (rsm == rack->r_ctl.rc_resend)
3048 		rack->r_ctl.rc_resend = NULL;
3049 	if (rsm == rack->r_ctl.rc_rsm_at_retran)
3050 		rack->r_ctl.rc_rsm_at_retran = NULL;
3051 	if (rsm == rack->r_ctl.rc_end_appl)
3052 		rack->r_ctl.rc_end_appl = NULL;
3053 	if (rack->r_ctl.rc_tlpsend == rsm)
3054 		rack->r_ctl.rc_tlpsend = NULL;
3055 	if (rack->r_ctl.rc_sacklast == rsm)
3056 		rack->r_ctl.rc_sacklast = NULL;
3057 	memset(rsm, 0, sizeof(struct rack_sendmap));
3058 	TAILQ_INSERT_HEAD(&rack->r_ctl.rc_free, rsm, r_tnext);
3059 	rack->rc_free_cnt++;
3060 }
3061 
3062 static void
3063 rack_free_trim(struct tcp_rack *rack)
3064 {
3065 	struct rack_sendmap *rsm;
3066 
3067 	/*
3068 	 * Free up all the tail entries until
3069 	 * we get our list down to the limit.
3070 	 */
3071 	while (rack->rc_free_cnt > rack_free_cache) {
3072 		rsm = TAILQ_LAST(&rack->r_ctl.rc_free, rack_head);
3073 		TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
3074 		rack->rc_free_cnt--;
3075 		uma_zfree(rack_zone, rsm);
3076 	}
3077 }
3078 
3079 
3080 static uint32_t
3081 rack_get_measure_window(struct tcpcb *tp, struct tcp_rack *rack)
3082 {
3083 	uint64_t srtt, bw, len, tim;
3084 	uint32_t segsiz, def_len, minl;
3085 
3086 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
3087 	def_len = rack_def_data_window * segsiz;
3088 	if (rack->rc_gp_filled == 0) {
3089 		/*
3090 		 * We have no measurement (IW is in flight?) so
3091 		 * we can only guess using our data_window sysctl
3092 		 * value (usually 20MSS).
3093 		 */
3094 		return (def_len);
3095 	}
3096 	/*
3097 	 * Now we have a number of factors to consider.
3098 	 *
3099 	 * 1) We have a desired BDP which is usually
3100 	 *    at least 2.
3101 	 * 2) We have a minimum number of rtt's usually 1 SRTT
3102 	 *    but we allow it too to be more.
3103 	 * 3) We want to make sure a measurement last N useconds (if
3104 	 *    we have set rack_min_measure_usec.
3105 	 *
3106 	 * We handle the first concern here by trying to create a data
3107 	 * window of max(rack_def_data_window, DesiredBDP). The
3108 	 * second concern we handle in not letting the measurement
3109 	 * window end normally until at least the required SRTT's
3110 	 * have gone by which is done further below in
3111 	 * rack_enough_for_measurement(). Finally the third concern
3112 	 * we also handle here by calculating how long that time
3113 	 * would take at the current BW and then return the
3114 	 * max of our first calculation and that length. Note
3115 	 * that if rack_min_measure_usec is 0, we don't deal
3116 	 * with concern 3. Also for both Concern 1 and 3 an
3117 	 * application limited period could end the measurement
3118 	 * earlier.
3119 	 *
3120 	 * So lets calculate the BDP with the "known" b/w using
3121 	 * the SRTT has our rtt and then multiply it by the
3122 	 * goal.
3123 	 */
3124 	bw = rack_get_bw(rack);
3125 	srtt = (uint64_t)tp->t_srtt;
3126 	len = bw * srtt;
3127 	len /= (uint64_t)HPTS_USEC_IN_SEC;
3128 	len *= max(1, rack_goal_bdp);
3129 	/* Now we need to round up to the nearest MSS */
3130 	len = roundup(len, segsiz);
3131 	if (rack_min_measure_usec) {
3132 		/* Now calculate our min length for this b/w */
3133 		tim = rack_min_measure_usec;
3134 		minl = (tim * bw) / (uint64_t)HPTS_USEC_IN_SEC;
3135 		if (minl == 0)
3136 			minl = 1;
3137 		minl = roundup(minl, segsiz);
3138 		if (len < minl)
3139 			len = minl;
3140 	}
3141 	/*
3142 	 * Now if we have a very small window we want
3143 	 * to attempt to get the window that is
3144 	 * as small as possible. This happens on
3145 	 * low b/w connections and we don't want to
3146 	 * span huge numbers of rtt's between measurements.
3147 	 *
3148 	 * We basically include 2 over our "MIN window" so
3149 	 * that the measurement can be shortened (possibly) by
3150 	 * an ack'ed packet.
3151 	 */
3152 	if (len < def_len)
3153 		return (max((uint32_t)len, ((MIN_GP_WIN+2) * segsiz)));
3154 	else
3155 		return (max((uint32_t)len, def_len));
3156 
3157 }
3158 
3159 static int
3160 rack_enough_for_measurement(struct tcpcb *tp, struct tcp_rack *rack, tcp_seq th_ack, uint8_t *quality)
3161 {
3162 	uint32_t tim, srtts, segsiz;
3163 
3164 	/*
3165 	 * Has enough time passed for the GP measurement to be valid?
3166 	 */
3167 	if ((tp->snd_max == tp->snd_una) ||
3168 	    (th_ack == tp->snd_max)){
3169 		/* All is acked */
3170 		*quality = RACK_QUALITY_ALLACKED;
3171 		return (1);
3172 	}
3173 	if (SEQ_LT(th_ack, tp->gput_seq)) {
3174 		/* Not enough bytes yet */
3175 		return (0);
3176 	}
3177 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
3178 	if (SEQ_LT(th_ack, tp->gput_ack) &&
3179 	    ((th_ack - tp->gput_seq) < max(rc_init_window(rack), (MIN_GP_WIN * segsiz)))) {
3180 		/* Not enough bytes yet */
3181 		return (0);
3182 	}
3183 	if (rack->r_ctl.rc_first_appl &&
3184 	    (SEQ_GEQ(th_ack, rack->r_ctl.rc_first_appl->r_end))) {
3185 		/*
3186 		 * We are up to the app limited send point
3187 		 * we have to measure irrespective of the time..
3188 		 */
3189 		*quality = RACK_QUALITY_APPLIMITED;
3190 		return (1);
3191 	}
3192 	/* Now what about time? */
3193 	srtts = (rack->r_ctl.rc_gp_srtt * rack_min_srtts);
3194 	tim = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - tp->gput_ts;
3195 	if (tim >= srtts) {
3196 		*quality = RACK_QUALITY_HIGH;
3197 		return (1);
3198 	}
3199 	/* Nope not even a full SRTT has passed */
3200 	return (0);
3201 }
3202 
3203 static void
3204 rack_log_timely(struct tcp_rack *rack,
3205 		uint32_t logged, uint64_t cur_bw, uint64_t low_bnd,
3206 		uint64_t up_bnd, int line, uint8_t method)
3207 {
3208 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
3209 		union tcp_log_stackspecific log;
3210 		struct timeval tv;
3211 
3212 		memset(&log, 0, sizeof(log));
3213 		log.u_bbr.flex1 = logged;
3214 		log.u_bbr.flex2 = rack->rc_gp_timely_inc_cnt;
3215 		log.u_bbr.flex2 <<= 4;
3216 		log.u_bbr.flex2 |= rack->rc_gp_timely_dec_cnt;
3217 		log.u_bbr.flex2 <<= 4;
3218 		log.u_bbr.flex2 |= rack->rc_gp_incr;
3219 		log.u_bbr.flex2 <<= 4;
3220 		log.u_bbr.flex2 |= rack->rc_gp_bwred;
3221 		log.u_bbr.flex3 = rack->rc_gp_incr;
3222 		log.u_bbr.flex4 = rack->r_ctl.rack_per_of_gp_ss;
3223 		log.u_bbr.flex5 = rack->r_ctl.rack_per_of_gp_ca;
3224 		log.u_bbr.flex6 = rack->r_ctl.rack_per_of_gp_rec;
3225 		log.u_bbr.flex7 = rack->rc_gp_bwred;
3226 		log.u_bbr.flex8 = method;
3227 		log.u_bbr.cur_del_rate = cur_bw;
3228 		log.u_bbr.delRate = low_bnd;
3229 		log.u_bbr.bw_inuse = up_bnd;
3230 		log.u_bbr.rttProp = rack_get_bw(rack);
3231 		log.u_bbr.pkt_epoch = line;
3232 		log.u_bbr.pkts_out = rack->r_ctl.rc_rtt_diff;
3233 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
3234 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
3235 		log.u_bbr.epoch = rack->r_ctl.rc_gp_srtt;
3236 		log.u_bbr.lt_epoch = rack->r_ctl.rc_prev_gp_srtt;
3237 		log.u_bbr.cwnd_gain = rack->rc_dragged_bottom;
3238 		log.u_bbr.cwnd_gain <<= 1;
3239 		log.u_bbr.cwnd_gain |= rack->rc_gp_saw_rec;
3240 		log.u_bbr.cwnd_gain <<= 1;
3241 		log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ss;
3242 		log.u_bbr.cwnd_gain <<= 1;
3243 		log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ca;
3244 		log.u_bbr.lost = rack->r_ctl.rc_loss_count;
3245 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
3246 		    &rack->rc_inp->inp_socket->so_rcv,
3247 		    &rack->rc_inp->inp_socket->so_snd,
3248 		    TCP_TIMELY_WORK, 0,
3249 		    0, &log, false, &tv);
3250 	}
3251 }
3252 
3253 static int
3254 rack_bw_can_be_raised(struct tcp_rack *rack, uint64_t cur_bw, uint64_t last_bw_est, uint16_t mult)
3255 {
3256 	/*
3257 	 * Before we increase we need to know if
3258 	 * the estimate just made was less than
3259 	 * our pacing goal (i.e. (cur_bw * mult) > last_bw_est)
3260 	 *
3261 	 * If we already are pacing at a fast enough
3262 	 * rate to push us faster there is no sense of
3263 	 * increasing.
3264 	 *
3265 	 * We first caculate our actual pacing rate (ss or ca multipler
3266 	 * times our cur_bw).
3267 	 *
3268 	 * Then we take the last measured rate and multipy by our
3269 	 * maximum pacing overage to give us a max allowable rate.
3270 	 *
3271 	 * If our act_rate is smaller than our max_allowable rate
3272 	 * then we should increase. Else we should hold steady.
3273 	 *
3274 	 */
3275 	uint64_t act_rate, max_allow_rate;
3276 
3277 	if (rack_timely_no_stopping)
3278 		return (1);
3279 
3280 	if ((cur_bw == 0) || (last_bw_est == 0)) {
3281 		/*
3282 		 * Initial startup case or
3283 		 * everything is acked case.
3284 		 */
3285 		rack_log_timely(rack,  mult, cur_bw, 0, 0,
3286 				__LINE__, 9);
3287 		return (1);
3288 	}
3289 	if (mult <= 100) {
3290 		/*
3291 		 * We can always pace at or slightly above our rate.
3292 		 */
3293 		rack_log_timely(rack,  mult, cur_bw, 0, 0,
3294 				__LINE__, 9);
3295 		return (1);
3296 	}
3297 	act_rate = cur_bw * (uint64_t)mult;
3298 	act_rate /= 100;
3299 	max_allow_rate = last_bw_est * ((uint64_t)rack_max_per_above + (uint64_t)100);
3300 	max_allow_rate /= 100;
3301 	if (act_rate < max_allow_rate) {
3302 		/*
3303 		 * Here the rate we are actually pacing at
3304 		 * is smaller than 10% above our last measurement.
3305 		 * This means we are pacing below what we would
3306 		 * like to try to achieve (plus some wiggle room).
3307 		 */
3308 		rack_log_timely(rack,  mult, cur_bw, act_rate, max_allow_rate,
3309 				__LINE__, 9);
3310 		return (1);
3311 	} else {
3312 		/*
3313 		 * Here we are already pacing at least rack_max_per_above(10%)
3314 		 * what we are getting back. This indicates most likely
3315 		 * that we are being limited (cwnd/rwnd/app) and can't
3316 		 * get any more b/w. There is no sense of trying to
3317 		 * raise up the pacing rate its not speeding us up
3318 		 * and we already are pacing faster than we are getting.
3319 		 */
3320 		rack_log_timely(rack,  mult, cur_bw, act_rate, max_allow_rate,
3321 				__LINE__, 8);
3322 		return (0);
3323 	}
3324 }
3325 
3326 static void
3327 rack_validate_multipliers_at_or_above100(struct tcp_rack *rack)
3328 {
3329 	/*
3330 	 * When we drag bottom, we want to assure
3331 	 * that no multiplier is below 1.0, if so
3332 	 * we want to restore it to at least that.
3333 	 */
3334 	if (rack->r_ctl.rack_per_of_gp_rec  < 100) {
3335 		/* This is unlikely we usually do not touch recovery */
3336 		rack->r_ctl.rack_per_of_gp_rec = 100;
3337 	}
3338 	if (rack->r_ctl.rack_per_of_gp_ca < 100) {
3339 		rack->r_ctl.rack_per_of_gp_ca = 100;
3340 	}
3341 	if (rack->r_ctl.rack_per_of_gp_ss < 100) {
3342 		rack->r_ctl.rack_per_of_gp_ss = 100;
3343 	}
3344 }
3345 
3346 static void
3347 rack_validate_multipliers_at_or_below_100(struct tcp_rack *rack)
3348 {
3349 	if (rack->r_ctl.rack_per_of_gp_ca > 100) {
3350 		rack->r_ctl.rack_per_of_gp_ca = 100;
3351 	}
3352 	if (rack->r_ctl.rack_per_of_gp_ss > 100) {
3353 		rack->r_ctl.rack_per_of_gp_ss = 100;
3354 	}
3355 }
3356 
3357 static void
3358 rack_increase_bw_mul(struct tcp_rack *rack, int timely_says, uint64_t cur_bw, uint64_t last_bw_est, int override)
3359 {
3360 	int32_t  calc, logged, plus;
3361 
3362 	logged = 0;
3363 
3364 	if (override) {
3365 		/*
3366 		 * override is passed when we are
3367 		 * loosing b/w and making one last
3368 		 * gasp at trying to not loose out
3369 		 * to a new-reno flow.
3370 		 */
3371 		goto extra_boost;
3372 	}
3373 	/* In classic timely we boost by 5x if we have 5 increases in a row, lets not */
3374 	if (rack->rc_gp_incr &&
3375 	    ((rack->rc_gp_timely_inc_cnt + 1) >= RACK_TIMELY_CNT_BOOST)) {
3376 		/*
3377 		 * Reset and get 5 strokes more before the boost. Note
3378 		 * that the count is 0 based so we have to add one.
3379 		 */
3380 extra_boost:
3381 		plus = (uint32_t)rack_gp_increase_per * RACK_TIMELY_CNT_BOOST;
3382 		rack->rc_gp_timely_inc_cnt = 0;
3383 	} else
3384 		plus = (uint32_t)rack_gp_increase_per;
3385 	/* Must be at least 1% increase for true timely increases */
3386 	if ((plus < 1) &&
3387 	    ((rack->r_ctl.rc_rtt_diff <= 0) || (timely_says <= 0)))
3388 		plus = 1;
3389 	if (rack->rc_gp_saw_rec &&
3390 	    (rack->rc_gp_no_rec_chg == 0) &&
3391 	    rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3392 				  rack->r_ctl.rack_per_of_gp_rec)) {
3393 		/* We have been in recovery ding it too */
3394 		calc = rack->r_ctl.rack_per_of_gp_rec + plus;
3395 		if (calc > 0xffff)
3396 			calc = 0xffff;
3397 		logged |= 1;
3398 		rack->r_ctl.rack_per_of_gp_rec = (uint16_t)calc;
3399 		if (rack_per_upper_bound_ss &&
3400 		    (rack->rc_dragged_bottom == 0) &&
3401 		    (rack->r_ctl.rack_per_of_gp_rec > rack_per_upper_bound_ss))
3402 			rack->r_ctl.rack_per_of_gp_rec = rack_per_upper_bound_ss;
3403 	}
3404 	if (rack->rc_gp_saw_ca &&
3405 	    (rack->rc_gp_saw_ss == 0) &&
3406 	    rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3407 				  rack->r_ctl.rack_per_of_gp_ca)) {
3408 		/* In CA */
3409 		calc = rack->r_ctl.rack_per_of_gp_ca + plus;
3410 		if (calc > 0xffff)
3411 			calc = 0xffff;
3412 		logged |= 2;
3413 		rack->r_ctl.rack_per_of_gp_ca = (uint16_t)calc;
3414 		if (rack_per_upper_bound_ca &&
3415 		    (rack->rc_dragged_bottom == 0) &&
3416 		    (rack->r_ctl.rack_per_of_gp_ca > rack_per_upper_bound_ca))
3417 			rack->r_ctl.rack_per_of_gp_ca = rack_per_upper_bound_ca;
3418 	}
3419 	if (rack->rc_gp_saw_ss &&
3420 	    rack_bw_can_be_raised(rack, cur_bw, last_bw_est,
3421 				  rack->r_ctl.rack_per_of_gp_ss)) {
3422 		/* In SS */
3423 		calc = rack->r_ctl.rack_per_of_gp_ss + plus;
3424 		if (calc > 0xffff)
3425 			calc = 0xffff;
3426 		rack->r_ctl.rack_per_of_gp_ss = (uint16_t)calc;
3427 		if (rack_per_upper_bound_ss &&
3428 		    (rack->rc_dragged_bottom == 0) &&
3429 		    (rack->r_ctl.rack_per_of_gp_ss > rack_per_upper_bound_ss))
3430 			rack->r_ctl.rack_per_of_gp_ss = rack_per_upper_bound_ss;
3431 		logged |= 4;
3432 	}
3433 	if (logged &&
3434 	    (rack->rc_gp_incr == 0)){
3435 		/* Go into increment mode */
3436 		rack->rc_gp_incr = 1;
3437 		rack->rc_gp_timely_inc_cnt = 0;
3438 	}
3439 	if (rack->rc_gp_incr &&
3440 	    logged &&
3441 	    (rack->rc_gp_timely_inc_cnt < RACK_TIMELY_CNT_BOOST)) {
3442 		rack->rc_gp_timely_inc_cnt++;
3443 	}
3444 	rack_log_timely(rack,  logged, plus, 0, 0,
3445 			__LINE__, 1);
3446 }
3447 
3448 static uint32_t
3449 rack_get_decrease(struct tcp_rack *rack, uint32_t curper, int32_t rtt_diff)
3450 {
3451 	/*
3452 	 * norm_grad = rtt_diff / minrtt;
3453 	 * new_per = curper * (1 - B * norm_grad)
3454 	 *
3455 	 * B = rack_gp_decrease_per (default 10%)
3456 	 * rtt_dif = input var current rtt-diff
3457 	 * curper = input var current percentage
3458 	 * minrtt = from rack filter
3459 	 *
3460 	 */
3461 	uint64_t perf;
3462 
3463 	perf = (((uint64_t)curper * ((uint64_t)1000000 -
3464 		    ((uint64_t)rack_gp_decrease_per * (uint64_t)10000 *
3465 		     (((uint64_t)rtt_diff * (uint64_t)1000000)/
3466 		      (uint64_t)get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt)))/
3467 		     (uint64_t)1000000)) /
3468 		(uint64_t)1000000);
3469 	if (perf > curper) {
3470 		/* TSNH */
3471 		perf = curper - 1;
3472 	}
3473 	return ((uint32_t)perf);
3474 }
3475 
3476 static uint32_t
3477 rack_decrease_highrtt(struct tcp_rack *rack, uint32_t curper, uint32_t rtt)
3478 {
3479 	/*
3480 	 *                                   highrttthresh
3481 	 * result = curper * (1 - (B * ( 1 -  ------          ))
3482 	 *                                     gp_srtt
3483 	 *
3484 	 * B = rack_gp_decrease_per (default 10%)
3485 	 * highrttthresh = filter_min * rack_gp_rtt_maxmul
3486 	 */
3487 	uint64_t perf;
3488 	uint32_t highrttthresh;
3489 
3490 	highrttthresh = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_maxmul;
3491 
3492 	perf = (((uint64_t)curper * ((uint64_t)1000000 -
3493 				     ((uint64_t)rack_gp_decrease_per * ((uint64_t)1000000 -
3494 					((uint64_t)highrttthresh * (uint64_t)1000000) /
3495 						    (uint64_t)rtt)) / 100)) /(uint64_t)1000000);
3496 	return (perf);
3497 }
3498 
3499 static void
3500 rack_decrease_bw_mul(struct tcp_rack *rack, int timely_says, uint32_t rtt, int32_t rtt_diff)
3501 {
3502 	uint64_t logvar, logvar2, logvar3;
3503 	uint32_t logged, new_per, ss_red, ca_red, rec_red, alt, val;
3504 
3505 	if (rack->rc_gp_incr) {
3506 		/* Turn off increment counting */
3507 		rack->rc_gp_incr = 0;
3508 		rack->rc_gp_timely_inc_cnt = 0;
3509 	}
3510 	ss_red = ca_red = rec_red = 0;
3511 	logged = 0;
3512 	/* Calculate the reduction value */
3513 	if (rtt_diff < 0) {
3514 		rtt_diff *= -1;
3515 	}
3516 	/* Must be at least 1% reduction */
3517 	if (rack->rc_gp_saw_rec && (rack->rc_gp_no_rec_chg == 0)) {
3518 		/* We have been in recovery ding it too */
3519 		if (timely_says == 2) {
3520 			new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_rec, rtt);
3521 			alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3522 			if (alt < new_per)
3523 				val = alt;
3524 			else
3525 				val = new_per;
3526 		} else
3527 			 val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3528 		if (rack->r_ctl.rack_per_of_gp_rec > val) {
3529 			rec_red = (rack->r_ctl.rack_per_of_gp_rec - val);
3530 			rack->r_ctl.rack_per_of_gp_rec = (uint16_t)val;
3531 		} else {
3532 			rack->r_ctl.rack_per_of_gp_rec = rack_per_lower_bound;
3533 			rec_red = 0;
3534 		}
3535 		if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_rec)
3536 			rack->r_ctl.rack_per_of_gp_rec = rack_per_lower_bound;
3537 		logged |= 1;
3538 	}
3539 	if (rack->rc_gp_saw_ss) {
3540 		/* Sent in SS */
3541 		if (timely_says == 2) {
3542 			new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_ss, rtt);
3543 			alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3544 			if (alt < new_per)
3545 				val = alt;
3546 			else
3547 				val = new_per;
3548 		} else
3549 			val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_ss, rtt_diff);
3550 		if (rack->r_ctl.rack_per_of_gp_ss > new_per) {
3551 			ss_red = rack->r_ctl.rack_per_of_gp_ss - val;
3552 			rack->r_ctl.rack_per_of_gp_ss = (uint16_t)val;
3553 		} else {
3554 			ss_red = new_per;
3555 			rack->r_ctl.rack_per_of_gp_ss = rack_per_lower_bound;
3556 			logvar = new_per;
3557 			logvar <<= 32;
3558 			logvar |= alt;
3559 			logvar2 = (uint32_t)rtt;
3560 			logvar2 <<= 32;
3561 			logvar2 |= (uint32_t)rtt_diff;
3562 			logvar3 = rack_gp_rtt_maxmul;
3563 			logvar3 <<= 32;
3564 			logvar3 |= get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3565 			rack_log_timely(rack, timely_says,
3566 					logvar2, logvar3,
3567 					logvar, __LINE__, 10);
3568 		}
3569 		if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_ss)
3570 			rack->r_ctl.rack_per_of_gp_ss = rack_per_lower_bound;
3571 		logged |= 4;
3572 	} else if (rack->rc_gp_saw_ca) {
3573 		/* Sent in CA */
3574 		if (timely_says == 2) {
3575 			new_per = rack_decrease_highrtt(rack, rack->r_ctl.rack_per_of_gp_ca, rtt);
3576 			alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_rec, rtt_diff);
3577 			if (alt < new_per)
3578 				val = alt;
3579 			else
3580 				val = new_per;
3581 		} else
3582 			val = new_per = alt = rack_get_decrease(rack, rack->r_ctl.rack_per_of_gp_ca, rtt_diff);
3583 		if (rack->r_ctl.rack_per_of_gp_ca > val) {
3584 			ca_red = rack->r_ctl.rack_per_of_gp_ca - val;
3585 			rack->r_ctl.rack_per_of_gp_ca = (uint16_t)val;
3586 		} else {
3587 			rack->r_ctl.rack_per_of_gp_ca = rack_per_lower_bound;
3588 			ca_red = 0;
3589 			logvar = new_per;
3590 			logvar <<= 32;
3591 			logvar |= alt;
3592 			logvar2 = (uint32_t)rtt;
3593 			logvar2 <<= 32;
3594 			logvar2 |= (uint32_t)rtt_diff;
3595 			logvar3 = rack_gp_rtt_maxmul;
3596 			logvar3 <<= 32;
3597 			logvar3 |= get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3598 			rack_log_timely(rack, timely_says,
3599 					logvar2, logvar3,
3600 					logvar, __LINE__, 10);
3601 		}
3602 		if (rack_per_lower_bound > rack->r_ctl.rack_per_of_gp_ca)
3603 			rack->r_ctl.rack_per_of_gp_ca = rack_per_lower_bound;
3604 		logged |= 2;
3605 	}
3606 	if (rack->rc_gp_timely_dec_cnt < 0x7) {
3607 		rack->rc_gp_timely_dec_cnt++;
3608 		if (rack_timely_dec_clear &&
3609 		    (rack->rc_gp_timely_dec_cnt == rack_timely_dec_clear))
3610 			rack->rc_gp_timely_dec_cnt = 0;
3611 	}
3612 	logvar = ss_red;
3613 	logvar <<= 32;
3614 	logvar |= ca_red;
3615 	rack_log_timely(rack,  logged, rec_red, rack_per_lower_bound, logvar,
3616 			__LINE__, 2);
3617 }
3618 
3619 static void
3620 rack_log_rtt_shrinks(struct tcp_rack *rack, uint32_t us_cts,
3621 		     uint32_t rtt, uint32_t line, uint8_t reas)
3622 {
3623 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
3624 		union tcp_log_stackspecific log;
3625 		struct timeval tv;
3626 
3627 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
3628 		log.u_bbr.flex1 = line;
3629 		log.u_bbr.flex2 = rack->r_ctl.rc_time_probertt_starts;
3630 		log.u_bbr.flex3 = rack->r_ctl.rc_lower_rtt_us_cts;
3631 		log.u_bbr.flex4 = rack->r_ctl.rack_per_of_gp_ss;
3632 		log.u_bbr.flex5 = rtt;
3633 		log.u_bbr.flex6 = rack->rc_highly_buffered;
3634 		log.u_bbr.flex6 <<= 1;
3635 		log.u_bbr.flex6 |= rack->forced_ack;
3636 		log.u_bbr.flex6 <<= 1;
3637 		log.u_bbr.flex6 |= rack->rc_gp_dyn_mul;
3638 		log.u_bbr.flex6 <<= 1;
3639 		log.u_bbr.flex6 |= rack->in_probe_rtt;
3640 		log.u_bbr.flex6 <<= 1;
3641 		log.u_bbr.flex6 |= rack->measure_saw_probe_rtt;
3642 		log.u_bbr.flex7 = rack->r_ctl.rack_per_of_gp_probertt;
3643 		log.u_bbr.pacing_gain = rack->r_ctl.rack_per_of_gp_ca;
3644 		log.u_bbr.cwnd_gain = rack->r_ctl.rack_per_of_gp_rec;
3645 		log.u_bbr.flex8 = reas;
3646 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
3647 		log.u_bbr.delRate = rack_get_bw(rack);
3648 		log.u_bbr.cur_del_rate = rack->r_ctl.rc_highest_us_rtt;
3649 		log.u_bbr.cur_del_rate <<= 32;
3650 		log.u_bbr.cur_del_rate |= rack->r_ctl.rc_lowest_us_rtt;
3651 		log.u_bbr.applimited = rack->r_ctl.rc_time_probertt_entered;
3652 		log.u_bbr.pkts_out = rack->r_ctl.rc_rtt_diff;
3653 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
3654 		log.u_bbr.epoch = rack->r_ctl.rc_gp_srtt;
3655 		log.u_bbr.lt_epoch = rack->r_ctl.rc_prev_gp_srtt;
3656 		log.u_bbr.pkt_epoch = rack->r_ctl.rc_lower_rtt_us_cts;
3657 		log.u_bbr.delivered = rack->r_ctl.rc_target_probertt_flight;
3658 		log.u_bbr.lost = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3659 		log.u_bbr.rttProp = us_cts;
3660 		log.u_bbr.rttProp <<= 32;
3661 		log.u_bbr.rttProp |= rack->r_ctl.rc_entry_gp_rtt;
3662 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
3663 		    &rack->rc_inp->inp_socket->so_rcv,
3664 		    &rack->rc_inp->inp_socket->so_snd,
3665 		    BBR_LOG_RTT_SHRINKS, 0,
3666 		    0, &log, false, &rack->r_ctl.act_rcv_time);
3667 	}
3668 }
3669 
3670 static void
3671 rack_set_prtt_target(struct tcp_rack *rack, uint32_t segsiz, uint32_t rtt)
3672 {
3673 	uint64_t bwdp;
3674 
3675 	bwdp = rack_get_bw(rack);
3676 	bwdp *= (uint64_t)rtt;
3677 	bwdp /= (uint64_t)HPTS_USEC_IN_SEC;
3678 	rack->r_ctl.rc_target_probertt_flight = roundup((uint32_t)bwdp, segsiz);
3679 	if (rack->r_ctl.rc_target_probertt_flight < (segsiz * rack_timely_min_segs)) {
3680 		/*
3681 		 * A window protocol must be able to have 4 packets
3682 		 * outstanding as the floor in order to function
3683 		 * (especially considering delayed ack :D).
3684 		 */
3685 		rack->r_ctl.rc_target_probertt_flight = (segsiz * rack_timely_min_segs);
3686 	}
3687 }
3688 
3689 static void
3690 rack_enter_probertt(struct tcp_rack *rack, uint32_t us_cts)
3691 {
3692 	/**
3693 	 * ProbeRTT is a bit different in rack_pacing than in
3694 	 * BBR. It is like BBR in that it uses the lowering of
3695 	 * the RTT as a signal that we saw something new and
3696 	 * counts from there for how long between. But it is
3697 	 * different in that its quite simple. It does not
3698 	 * play with the cwnd and wait until we get down
3699 	 * to N segments outstanding and hold that for
3700 	 * 200ms. Instead it just sets the pacing reduction
3701 	 * rate to a set percentage (70 by default) and hold
3702 	 * that for a number of recent GP Srtt's.
3703 	 */
3704 	uint32_t segsiz;
3705 
3706 	if (rack->rc_gp_dyn_mul == 0)
3707 		return;
3708 
3709 	if (rack->rc_tp->snd_max == rack->rc_tp->snd_una) {
3710 		/* We are idle */
3711 		return;
3712 	}
3713 	if ((rack->rc_tp->t_flags & TF_GPUTINPROG) &&
3714 	    SEQ_GT(rack->rc_tp->snd_una, rack->rc_tp->gput_seq)) {
3715 		/*
3716 		 * Stop the goodput now, the idea here is
3717 		 * that future measurements with in_probe_rtt
3718 		 * won't register if they are not greater so
3719 		 * we want to get what info (if any) is available
3720 		 * now.
3721 		 */
3722 		rack_do_goodput_measurement(rack->rc_tp, rack,
3723 					    rack->rc_tp->snd_una, __LINE__,
3724 					    RACK_QUALITY_PROBERTT);
3725 	}
3726 	rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
3727 	rack->r_ctl.rc_time_probertt_entered = us_cts;
3728 	segsiz = min(ctf_fixed_maxseg(rack->rc_tp),
3729 		     rack->r_ctl.rc_pace_min_segs);
3730 	rack->in_probe_rtt = 1;
3731 	rack->measure_saw_probe_rtt = 1;
3732 	rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
3733 	rack->r_ctl.rc_time_probertt_starts = 0;
3734 	rack->r_ctl.rc_entry_gp_rtt = rack->r_ctl.rc_gp_srtt;
3735 	if (rack_probertt_use_min_rtt_entry)
3736 		rack_set_prtt_target(rack, segsiz, get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt));
3737 	else
3738 		rack_set_prtt_target(rack, segsiz, rack->r_ctl.rc_gp_srtt);
3739 	rack_log_rtt_shrinks(rack,  us_cts,  get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3740 			     __LINE__, RACK_RTTS_ENTERPROBE);
3741 }
3742 
3743 static void
3744 rack_exit_probertt(struct tcp_rack *rack, uint32_t us_cts)
3745 {
3746 	struct rack_sendmap *rsm;
3747 	uint32_t segsiz;
3748 
3749 	segsiz = min(ctf_fixed_maxseg(rack->rc_tp),
3750 		     rack->r_ctl.rc_pace_min_segs);
3751 	rack->in_probe_rtt = 0;
3752 	if ((rack->rc_tp->t_flags & TF_GPUTINPROG) &&
3753 	    SEQ_GT(rack->rc_tp->snd_una, rack->rc_tp->gput_seq)) {
3754 		/*
3755 		 * Stop the goodput now, the idea here is
3756 		 * that future measurements with in_probe_rtt
3757 		 * won't register if they are not greater so
3758 		 * we want to get what info (if any) is available
3759 		 * now.
3760 		 */
3761 		rack_do_goodput_measurement(rack->rc_tp, rack,
3762 					    rack->rc_tp->snd_una, __LINE__,
3763 					    RACK_QUALITY_PROBERTT);
3764 	} else if (rack->rc_tp->t_flags & TF_GPUTINPROG) {
3765 		/*
3766 		 * We don't have enough data to make a measurement.
3767 		 * So lets just stop and start here after exiting
3768 		 * probe-rtt. We probably are not interested in
3769 		 * the results anyway.
3770 		 */
3771 		rack->rc_tp->t_flags &= ~TF_GPUTINPROG;
3772 	}
3773 	/*
3774 	 * Measurements through the current snd_max are going
3775 	 * to be limited by the slower pacing rate.
3776 	 *
3777 	 * We need to mark these as app-limited so we
3778 	 * don't collapse the b/w.
3779 	 */
3780 	rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
3781 	if (rsm && ((rsm->r_flags & RACK_APP_LIMITED) == 0)) {
3782 		if (rack->r_ctl.rc_app_limited_cnt == 0)
3783 			rack->r_ctl.rc_end_appl = rack->r_ctl.rc_first_appl = rsm;
3784 		else {
3785 			/*
3786 			 * Go out to the end app limited and mark
3787 			 * this new one as next and move the end_appl up
3788 			 * to this guy.
3789 			 */
3790 			if (rack->r_ctl.rc_end_appl)
3791 				rack->r_ctl.rc_end_appl->r_nseq_appl = rsm->r_start;
3792 			rack->r_ctl.rc_end_appl = rsm;
3793 		}
3794 		rsm->r_flags |= RACK_APP_LIMITED;
3795 		rack->r_ctl.rc_app_limited_cnt++;
3796 	}
3797 	/*
3798 	 * Now, we need to examine our pacing rate multipliers.
3799 	 * If its under 100%, we need to kick it back up to
3800 	 * 100%. We also don't let it be over our "max" above
3801 	 * the actual rate i.e. 100% + rack_clamp_atexit_prtt.
3802 	 * Note setting clamp_atexit_prtt to 0 has the effect
3803 	 * of setting CA/SS to 100% always at exit (which is
3804 	 * the default behavior).
3805 	 */
3806 	if (rack_probertt_clear_is) {
3807 		rack->rc_gp_incr = 0;
3808 		rack->rc_gp_bwred = 0;
3809 		rack->rc_gp_timely_inc_cnt = 0;
3810 		rack->rc_gp_timely_dec_cnt = 0;
3811 	}
3812 	/* Do we do any clamping at exit? */
3813 	if (rack->rc_highly_buffered && rack_atexit_prtt_hbp) {
3814 		rack->r_ctl.rack_per_of_gp_ca = rack_atexit_prtt_hbp;
3815 		rack->r_ctl.rack_per_of_gp_ss = rack_atexit_prtt_hbp;
3816 	}
3817 	if ((rack->rc_highly_buffered == 0) && rack_atexit_prtt) {
3818 		rack->r_ctl.rack_per_of_gp_ca = rack_atexit_prtt;
3819 		rack->r_ctl.rack_per_of_gp_ss = rack_atexit_prtt;
3820 	}
3821 	/*
3822 	 * Lets set rtt_diff to 0, so that we will get a "boost"
3823 	 * after exiting.
3824 	 */
3825 	rack->r_ctl.rc_rtt_diff = 0;
3826 
3827 	/* Clear all flags so we start fresh */
3828 	rack->rc_tp->t_bytes_acked = 0;
3829 	rack->rc_tp->ccv->flags &= ~CCF_ABC_SENTAWND;
3830 	/*
3831 	 * If configured to, set the cwnd and ssthresh to
3832 	 * our targets.
3833 	 */
3834 	if (rack_probe_rtt_sets_cwnd) {
3835 		uint64_t ebdp;
3836 		uint32_t setto;
3837 
3838 		/* Set ssthresh so we get into CA once we hit our target */
3839 		if (rack_probertt_use_min_rtt_exit == 1) {
3840 			/* Set to min rtt */
3841 			rack_set_prtt_target(rack, segsiz,
3842 					     get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt));
3843 		} else if (rack_probertt_use_min_rtt_exit == 2) {
3844 			/* Set to current gp rtt */
3845 			rack_set_prtt_target(rack, segsiz,
3846 					     rack->r_ctl.rc_gp_srtt);
3847 		} else if (rack_probertt_use_min_rtt_exit == 3) {
3848 			/* Set to entry gp rtt */
3849 			rack_set_prtt_target(rack, segsiz,
3850 					     rack->r_ctl.rc_entry_gp_rtt);
3851 		} else {
3852 			uint64_t sum;
3853 			uint32_t setval;
3854 
3855 			sum = rack->r_ctl.rc_entry_gp_rtt;
3856 			sum *= 10;
3857 			sum /= (uint64_t)(max(1, rack->r_ctl.rc_gp_srtt));
3858 			if (sum >= 20) {
3859 				/*
3860 				 * A highly buffered path needs
3861 				 * cwnd space for timely to work.
3862 				 * Lets set things up as if
3863 				 * we are heading back here again.
3864 				 */
3865 				setval = rack->r_ctl.rc_entry_gp_rtt;
3866 			} else if (sum >= 15) {
3867 				/*
3868 				 * Lets take the smaller of the
3869 				 * two since we are just somewhat
3870 				 * buffered.
3871 				 */
3872 				setval = rack->r_ctl.rc_gp_srtt;
3873 				if (setval > rack->r_ctl.rc_entry_gp_rtt)
3874 					setval = rack->r_ctl.rc_entry_gp_rtt;
3875 			} else {
3876 				/*
3877 				 * Here we are not highly buffered
3878 				 * and should pick the min we can to
3879 				 * keep from causing loss.
3880 				 */
3881 				setval = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
3882 			}
3883 			rack_set_prtt_target(rack, segsiz,
3884 					     setval);
3885 		}
3886 		if (rack_probe_rtt_sets_cwnd > 1) {
3887 			/* There is a percentage here to boost */
3888 			ebdp = rack->r_ctl.rc_target_probertt_flight;
3889 			ebdp *= rack_probe_rtt_sets_cwnd;
3890 			ebdp /= 100;
3891 			setto = rack->r_ctl.rc_target_probertt_flight + ebdp;
3892 		} else
3893 			setto = rack->r_ctl.rc_target_probertt_flight;
3894 		rack->rc_tp->snd_cwnd = roundup(setto, segsiz);
3895 		if (rack->rc_tp->snd_cwnd < (segsiz * rack_timely_min_segs)) {
3896 			/* Enforce a min */
3897 			rack->rc_tp->snd_cwnd = segsiz * rack_timely_min_segs;
3898 		}
3899 		/* If we set in the cwnd also set the ssthresh point so we are in CA */
3900 		rack->rc_tp->snd_ssthresh = (rack->rc_tp->snd_cwnd - 1);
3901 	}
3902 	rack_log_rtt_shrinks(rack,  us_cts,
3903 			     get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3904 			     __LINE__, RACK_RTTS_EXITPROBE);
3905 	/* Clear times last so log has all the info */
3906 	rack->r_ctl.rc_probertt_sndmax_atexit = rack->rc_tp->snd_max;
3907 	rack->r_ctl.rc_time_probertt_entered = us_cts;
3908 	rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
3909 	rack->r_ctl.rc_time_of_last_probertt = us_cts;
3910 }
3911 
3912 static void
3913 rack_check_probe_rtt(struct tcp_rack *rack, uint32_t us_cts)
3914 {
3915 	/* Check in on probe-rtt */
3916 	if (rack->rc_gp_filled == 0) {
3917 		/* We do not do p-rtt unless we have gp measurements */
3918 		return;
3919 	}
3920 	if (rack->in_probe_rtt) {
3921 		uint64_t no_overflow;
3922 		uint32_t endtime, must_stay;
3923 
3924 		if (rack->r_ctl.rc_went_idle_time &&
3925 		    ((us_cts - rack->r_ctl.rc_went_idle_time) > rack_min_probertt_hold)) {
3926 			/*
3927 			 * We went idle during prtt, just exit now.
3928 			 */
3929 			rack_exit_probertt(rack, us_cts);
3930 		} else if (rack_probe_rtt_safety_val &&
3931 		    TSTMP_GT(us_cts, rack->r_ctl.rc_time_probertt_entered) &&
3932 		    ((us_cts - rack->r_ctl.rc_time_probertt_entered) > rack_probe_rtt_safety_val)) {
3933 			/*
3934 			 * Probe RTT safety value triggered!
3935 			 */
3936 			rack_log_rtt_shrinks(rack,  us_cts,
3937 					     get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3938 					     __LINE__, RACK_RTTS_SAFETY);
3939 			rack_exit_probertt(rack, us_cts);
3940 		}
3941 		/* Calculate the max we will wait */
3942 		endtime = rack->r_ctl.rc_time_probertt_entered + (rack->r_ctl.rc_gp_srtt * rack_max_drain_wait);
3943 		if (rack->rc_highly_buffered)
3944 			endtime += (rack->r_ctl.rc_gp_srtt * rack_max_drain_hbp);
3945 		/* Calculate the min we must wait */
3946 		must_stay = rack->r_ctl.rc_time_probertt_entered + (rack->r_ctl.rc_gp_srtt * rack_must_drain);
3947 		if ((ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) > rack->r_ctl.rc_target_probertt_flight) &&
3948 		    TSTMP_LT(us_cts, endtime)) {
3949 			uint32_t calc;
3950 			/* Do we lower more? */
3951 no_exit:
3952 			if (TSTMP_GT(us_cts, rack->r_ctl.rc_time_probertt_entered))
3953 				calc = us_cts - rack->r_ctl.rc_time_probertt_entered;
3954 			else
3955 				calc = 0;
3956 			calc /= max(rack->r_ctl.rc_gp_srtt, 1);
3957 			if (calc) {
3958 				/* Maybe */
3959 				calc *= rack_per_of_gp_probertt_reduce;
3960 				rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt - calc;
3961 				/* Limit it too */
3962 				if (rack->r_ctl.rack_per_of_gp_probertt < rack_per_of_gp_lowthresh)
3963 					rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_lowthresh;
3964 			}
3965 			/* We must reach target or the time set */
3966 			return;
3967 		}
3968 		if (rack->r_ctl.rc_time_probertt_starts == 0) {
3969 			if ((TSTMP_LT(us_cts, must_stay) &&
3970 			     rack->rc_highly_buffered) ||
3971 			     (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) >
3972 			      rack->r_ctl.rc_target_probertt_flight)) {
3973 				/* We are not past the must_stay time */
3974 				goto no_exit;
3975 			}
3976 			rack_log_rtt_shrinks(rack,  us_cts,
3977 					     get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
3978 					     __LINE__, RACK_RTTS_REACHTARGET);
3979 			rack->r_ctl.rc_time_probertt_starts = us_cts;
3980 			if (rack->r_ctl.rc_time_probertt_starts == 0)
3981 				rack->r_ctl.rc_time_probertt_starts = 1;
3982 			/* Restore back to our rate we want to pace at in prtt */
3983 			rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
3984 		}
3985 		/*
3986 		 * Setup our end time, some number of gp_srtts plus 200ms.
3987 		 */
3988 		no_overflow = ((uint64_t)rack->r_ctl.rc_gp_srtt *
3989 			       (uint64_t)rack_probertt_gpsrtt_cnt_mul);
3990 		if (rack_probertt_gpsrtt_cnt_div)
3991 			endtime = (uint32_t)(no_overflow / (uint64_t)rack_probertt_gpsrtt_cnt_div);
3992 		else
3993 			endtime = 0;
3994 		endtime += rack_min_probertt_hold;
3995 		endtime += rack->r_ctl.rc_time_probertt_starts;
3996 		if (TSTMP_GEQ(us_cts,  endtime)) {
3997 			/* yes, exit probertt */
3998 			rack_exit_probertt(rack, us_cts);
3999 		}
4000 
4001 	} else if ((us_cts - rack->r_ctl.rc_lower_rtt_us_cts) >= rack_time_between_probertt) {
4002 		/* Go into probertt, its been too long since we went lower */
4003 		rack_enter_probertt(rack, us_cts);
4004 	}
4005 }
4006 
4007 static void
4008 rack_update_multiplier(struct tcp_rack *rack, int32_t timely_says, uint64_t last_bw_est,
4009 		       uint32_t rtt, int32_t rtt_diff)
4010 {
4011 	uint64_t cur_bw, up_bnd, low_bnd, subfr;
4012 	uint32_t losses;
4013 
4014 	if ((rack->rc_gp_dyn_mul == 0) ||
4015 	    (rack->use_fixed_rate) ||
4016 	    (rack->in_probe_rtt) ||
4017 	    (rack->rc_always_pace == 0)) {
4018 		/* No dynamic GP multipler in play */
4019 		return;
4020 	}
4021 	losses = rack->r_ctl.rc_loss_count - rack->r_ctl.rc_loss_at_start;
4022 	cur_bw = rack_get_bw(rack);
4023 	/* Calculate our up and down range */
4024 	up_bnd = rack->r_ctl.last_gp_comp_bw * (uint64_t)rack_gp_per_bw_mul_up;
4025 	up_bnd /= 100;
4026 	up_bnd += rack->r_ctl.last_gp_comp_bw;
4027 
4028 	subfr = (uint64_t)rack->r_ctl.last_gp_comp_bw * (uint64_t)rack_gp_per_bw_mul_down;
4029 	subfr /= 100;
4030 	low_bnd = rack->r_ctl.last_gp_comp_bw - subfr;
4031 	if ((timely_says == 2) && (rack->r_ctl.rc_no_push_at_mrtt)) {
4032 		/*
4033 		 * This is the case where our RTT is above
4034 		 * the max target and we have been configured
4035 		 * to just do timely no bonus up stuff in that case.
4036 		 *
4037 		 * There are two configurations, set to 1, and we
4038 		 * just do timely if we are over our max. If its
4039 		 * set above 1 then we slam the multipliers down
4040 		 * to 100 and then decrement per timely.
4041 		 */
4042 		rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4043 				__LINE__, 3);
4044 		if (rack->r_ctl.rc_no_push_at_mrtt > 1)
4045 			rack_validate_multipliers_at_or_below_100(rack);
4046 		rack_decrease_bw_mul(rack, timely_says, rtt, rtt_diff);
4047 	} else if ((last_bw_est < low_bnd) && !losses) {
4048 		/*
4049 		 * We are decreasing this is a bit complicated this
4050 		 * means we are loosing ground. This could be
4051 		 * because another flow entered and we are competing
4052 		 * for b/w with it. This will push the RTT up which
4053 		 * makes timely unusable unless we want to get shoved
4054 		 * into a corner and just be backed off (the age
4055 		 * old problem with delay based CC).
4056 		 *
4057 		 * On the other hand if it was a route change we
4058 		 * would like to stay somewhat contained and not
4059 		 * blow out the buffers.
4060 		 */
4061 		rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4062 				__LINE__, 3);
4063 		rack->r_ctl.last_gp_comp_bw = cur_bw;
4064 		if (rack->rc_gp_bwred == 0) {
4065 			/* Go into reduction counting */
4066 			rack->rc_gp_bwred = 1;
4067 			rack->rc_gp_timely_dec_cnt = 0;
4068 		}
4069 		if ((rack->rc_gp_timely_dec_cnt < rack_timely_max_push_drop) ||
4070 		    (timely_says == 0)) {
4071 			/*
4072 			 * Push another time with a faster pacing
4073 			 * to try to gain back (we include override to
4074 			 * get a full raise factor).
4075 			 */
4076 			if ((rack->rc_gp_saw_ca && rack->r_ctl.rack_per_of_gp_ca <= rack_down_raise_thresh) ||
4077 			    (rack->rc_gp_saw_ss && rack->r_ctl.rack_per_of_gp_ss <= rack_down_raise_thresh) ||
4078 			    (timely_says == 0) ||
4079 			    (rack_down_raise_thresh == 0)) {
4080 				/*
4081 				 * Do an override up in b/w if we were
4082 				 * below the threshold or if the threshold
4083 				 * is zero we always do the raise.
4084 				 */
4085 				rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 1);
4086 			} else {
4087 				/* Log it stays the same */
4088 				rack_log_timely(rack,  0, last_bw_est, low_bnd, 0,
4089 						__LINE__, 11);
4090 			}
4091 			rack->rc_gp_timely_dec_cnt++;
4092 			/* We are not incrementing really no-count */
4093 			rack->rc_gp_incr = 0;
4094 			rack->rc_gp_timely_inc_cnt = 0;
4095 		} else {
4096 			/*
4097 			 * Lets just use the RTT
4098 			 * information and give up
4099 			 * pushing.
4100 			 */
4101 			goto use_timely;
4102 		}
4103 	} else if ((timely_says != 2) &&
4104 		    !losses &&
4105 		    (last_bw_est > up_bnd)) {
4106 		/*
4107 		 * We are increasing b/w lets keep going, updating
4108 		 * our b/w and ignoring any timely input, unless
4109 		 * of course we are at our max raise (if there is one).
4110 		 */
4111 
4112 		rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4113 				__LINE__, 3);
4114 		rack->r_ctl.last_gp_comp_bw = cur_bw;
4115 		if (rack->rc_gp_saw_ss &&
4116 		    rack_per_upper_bound_ss &&
4117 		     (rack->r_ctl.rack_per_of_gp_ss == rack_per_upper_bound_ss)) {
4118 			    /*
4119 			     * In cases where we can't go higher
4120 			     * we should just use timely.
4121 			     */
4122 			    goto use_timely;
4123 		}
4124 		if (rack->rc_gp_saw_ca &&
4125 		    rack_per_upper_bound_ca &&
4126 		    (rack->r_ctl.rack_per_of_gp_ca == rack_per_upper_bound_ca)) {
4127 			    /*
4128 			     * In cases where we can't go higher
4129 			     * we should just use timely.
4130 			     */
4131 			    goto use_timely;
4132 		}
4133 		rack->rc_gp_bwred = 0;
4134 		rack->rc_gp_timely_dec_cnt = 0;
4135 		/* You get a set number of pushes if timely is trying to reduce */
4136 		if ((rack->rc_gp_incr < rack_timely_max_push_rise) || (timely_says == 0)) {
4137 			rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4138 		} else {
4139 			/* Log it stays the same */
4140 			rack_log_timely(rack,  0, last_bw_est, up_bnd, 0,
4141 			    __LINE__, 12);
4142 		}
4143 		return;
4144 	} else {
4145 		/*
4146 		 * We are staying between the lower and upper range bounds
4147 		 * so use timely to decide.
4148 		 */
4149 		rack_log_timely(rack,  timely_says, cur_bw, low_bnd, up_bnd,
4150 				__LINE__, 3);
4151 use_timely:
4152 		if (timely_says) {
4153 			rack->rc_gp_incr = 0;
4154 			rack->rc_gp_timely_inc_cnt = 0;
4155 			if ((rack->rc_gp_timely_dec_cnt < rack_timely_max_push_drop) &&
4156 			    !losses &&
4157 			    (last_bw_est < low_bnd)) {
4158 				/* We are loosing ground */
4159 				rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4160 				rack->rc_gp_timely_dec_cnt++;
4161 				/* We are not incrementing really no-count */
4162 				rack->rc_gp_incr = 0;
4163 				rack->rc_gp_timely_inc_cnt = 0;
4164 			} else
4165 				rack_decrease_bw_mul(rack, timely_says, rtt, rtt_diff);
4166 		} else {
4167 			rack->rc_gp_bwred = 0;
4168 			rack->rc_gp_timely_dec_cnt = 0;
4169 			rack_increase_bw_mul(rack, timely_says, cur_bw, last_bw_est, 0);
4170 		}
4171 	}
4172 }
4173 
4174 static int32_t
4175 rack_make_timely_judgement(struct tcp_rack *rack, uint32_t rtt, int32_t rtt_diff, uint32_t prev_rtt)
4176 {
4177 	int32_t timely_says;
4178 	uint64_t log_mult, log_rtt_a_diff;
4179 
4180 	log_rtt_a_diff = rtt;
4181 	log_rtt_a_diff <<= 32;
4182 	log_rtt_a_diff |= (uint32_t)rtt_diff;
4183 	if (rtt >= (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) *
4184 		    rack_gp_rtt_maxmul)) {
4185 		/* Reduce the b/w multipler */
4186 		timely_says = 2;
4187 		log_mult = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_maxmul;
4188 		log_mult <<= 32;
4189 		log_mult |= prev_rtt;
4190 		rack_log_timely(rack,  timely_says, log_mult,
4191 				get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
4192 				log_rtt_a_diff, __LINE__, 4);
4193 	} else if (rtt <= (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) +
4194 			   ((get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_minmul) /
4195 			    max(rack_gp_rtt_mindiv , 1)))) {
4196 		/* Increase the b/w multipler */
4197 		log_mult = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) +
4198 			((get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack_gp_rtt_minmul) /
4199 			 max(rack_gp_rtt_mindiv , 1));
4200 		log_mult <<= 32;
4201 		log_mult |= prev_rtt;
4202 		timely_says = 0;
4203 		rack_log_timely(rack,  timely_says, log_mult ,
4204 				get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt),
4205 				log_rtt_a_diff, __LINE__, 5);
4206 	} else {
4207 		/*
4208 		 * Use a gradient to find it the timely gradient
4209 		 * is:
4210 		 * grad = rc_rtt_diff / min_rtt;
4211 		 *
4212 		 * anything below or equal to 0 will be
4213 		 * a increase indication. Anything above
4214 		 * zero is a decrease. Note we take care
4215 		 * of the actual gradient calculation
4216 		 * in the reduction (its not needed for
4217 		 * increase).
4218 		 */
4219 		log_mult = prev_rtt;
4220 		if (rtt_diff <= 0) {
4221 			/*
4222 			 * Rttdiff is less than zero, increase the
4223 			 * b/w multipler (its 0 or negative)
4224 			 */
4225 			timely_says = 0;
4226 			rack_log_timely(rack,  timely_says, log_mult,
4227 					get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt), log_rtt_a_diff, __LINE__, 6);
4228 		} else {
4229 			/* Reduce the b/w multipler */
4230 			timely_says = 1;
4231 			rack_log_timely(rack,  timely_says, log_mult,
4232 					get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt), log_rtt_a_diff, __LINE__, 7);
4233 		}
4234 	}
4235 	return (timely_says);
4236 }
4237 
4238 static void
4239 rack_do_goodput_measurement(struct tcpcb *tp, struct tcp_rack *rack,
4240 			    tcp_seq th_ack, int line, uint8_t quality)
4241 {
4242 	uint64_t tim, bytes_ps, ltim, stim, utim;
4243 	uint32_t segsiz, bytes, reqbytes, us_cts;
4244 	int32_t gput, new_rtt_diff, timely_says;
4245 	uint64_t  resid_bw, subpart = 0, addpart = 0, srtt;
4246 	int did_add = 0;
4247 
4248 	us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
4249 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
4250 	if (TSTMP_GEQ(us_cts, tp->gput_ts))
4251 		tim = us_cts - tp->gput_ts;
4252 	else
4253 		tim = 0;
4254 	if (rack->r_ctl.rc_gp_cumack_ts > rack->r_ctl.rc_gp_output_ts)
4255 		stim = rack->r_ctl.rc_gp_cumack_ts - rack->r_ctl.rc_gp_output_ts;
4256 	else
4257 		stim = 0;
4258 	/*
4259 	 * Use the larger of the send time or ack time. This prevents us
4260 	 * from being influenced by ack artifacts to come up with too
4261 	 * high of measurement. Note that since we are spanning over many more
4262 	 * bytes in most of our measurements hopefully that is less likely to
4263 	 * occur.
4264 	 */
4265 	if (tim > stim)
4266 		utim = max(tim, 1);
4267 	else
4268 		utim = max(stim, 1);
4269 	/* Lets get a msec time ltim too for the old stuff */
4270 	ltim = max(1, (utim / HPTS_USEC_IN_MSEC));
4271 	gput = (((uint64_t) (th_ack - tp->gput_seq)) << 3) / ltim;
4272 	reqbytes = min(rc_init_window(rack), (MIN_GP_WIN * segsiz));
4273 	if ((tim == 0) && (stim == 0)) {
4274 		/*
4275 		 * Invalid measurement time, maybe
4276 		 * all on one ack/one send?
4277 		 */
4278 		bytes = 0;
4279 		bytes_ps = 0;
4280 		rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4281 					   0, 0, 0, 10, __LINE__, NULL, quality);
4282 		goto skip_measurement;
4283 	}
4284 	if (rack->r_ctl.rc_gp_lowrtt == 0xffffffff) {
4285 		/* We never made a us_rtt measurement? */
4286 		bytes = 0;
4287 		bytes_ps = 0;
4288 		rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4289 					   0, 0, 0, 10, __LINE__, NULL, quality);
4290 		goto skip_measurement;
4291 	}
4292 	/*
4293 	 * Calculate the maximum possible b/w this connection
4294 	 * could have. We base our calculation on the lowest
4295 	 * rtt we have seen during the measurement and the
4296 	 * largest rwnd the client has given us in that time. This
4297 	 * forms a BDP that is the maximum that we could ever
4298 	 * get to the client. Anything larger is not valid.
4299 	 *
4300 	 * I originally had code here that rejected measurements
4301 	 * where the time was less than 1/2 the latest us_rtt.
4302 	 * But after thinking on that I realized its wrong since
4303 	 * say you had a 150Mbps or even 1Gbps link, and you
4304 	 * were a long way away.. example I am in Europe (100ms rtt)
4305 	 * talking to my 1Gbps link in S.C. Now measuring say 150,000
4306 	 * bytes my time would be 1.2ms, and yet my rtt would say
4307 	 * the measurement was invalid the time was < 50ms. The
4308 	 * same thing is true for 150Mb (8ms of time).
4309 	 *
4310 	 * A better way I realized is to look at what the maximum
4311 	 * the connection could possibly do. This is gated on
4312 	 * the lowest RTT we have seen and the highest rwnd.
4313 	 * We should in theory never exceed that, if we are
4314 	 * then something on the path is storing up packets
4315 	 * and then feeding them all at once to our endpoint
4316 	 * messing up our measurement.
4317 	 */
4318 	rack->r_ctl.last_max_bw = rack->r_ctl.rc_gp_high_rwnd;
4319 	rack->r_ctl.last_max_bw *= HPTS_USEC_IN_SEC;
4320 	rack->r_ctl.last_max_bw /= rack->r_ctl.rc_gp_lowrtt;
4321 	if (SEQ_LT(th_ack, tp->gput_seq)) {
4322 		/* No measurement can be made */
4323 		bytes = 0;
4324 		bytes_ps = 0;
4325 		rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4326 					   0, 0, 0, 10, __LINE__, NULL, quality);
4327 		goto skip_measurement;
4328 	} else
4329 		bytes = (th_ack - tp->gput_seq);
4330 	bytes_ps = (uint64_t)bytes;
4331 	/*
4332 	 * Don't measure a b/w for pacing unless we have gotten at least
4333 	 * an initial windows worth of data in this measurement interval.
4334 	 *
4335 	 * Small numbers of bytes get badly influenced by delayed ack and
4336 	 * other artifacts. Note we take the initial window or our
4337 	 * defined minimum GP (defaulting to 10 which hopefully is the
4338 	 * IW).
4339 	 */
4340 	if (rack->rc_gp_filled == 0) {
4341 		/*
4342 		 * The initial estimate is special. We
4343 		 * have blasted out an IW worth of packets
4344 		 * without a real valid ack ts results. We
4345 		 * then setup the app_limited_needs_set flag,
4346 		 * this should get the first ack in (probably 2
4347 		 * MSS worth) to be recorded as the timestamp.
4348 		 * We thus allow a smaller number of bytes i.e.
4349 		 * IW - 2MSS.
4350 		 */
4351 		reqbytes -= (2 * segsiz);
4352 		/* Also lets fill previous for our first measurement to be neutral */
4353 		rack->r_ctl.rc_prev_gp_srtt = rack->r_ctl.rc_gp_srtt;
4354 	}
4355 	if ((bytes_ps < reqbytes) || rack->app_limited_needs_set) {
4356 		rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4357 					   rack->r_ctl.rc_app_limited_cnt,
4358 					   0, 0, 10, __LINE__, NULL, quality);
4359 		goto skip_measurement;
4360 	}
4361 	/*
4362 	 * We now need to calculate the Timely like status so
4363 	 * we can update (possibly) the b/w multipliers.
4364 	 */
4365 	new_rtt_diff = (int32_t)rack->r_ctl.rc_gp_srtt - (int32_t)rack->r_ctl.rc_prev_gp_srtt;
4366 	if (rack->rc_gp_filled == 0) {
4367 		/* No previous reading */
4368 		rack->r_ctl.rc_rtt_diff = new_rtt_diff;
4369 	} else {
4370 		if (rack->measure_saw_probe_rtt == 0) {
4371 			/*
4372 			 * We don't want a probertt to be counted
4373 			 * since it will be negative incorrectly. We
4374 			 * expect to be reducing the RTT when we
4375 			 * pace at a slower rate.
4376 			 */
4377 			rack->r_ctl.rc_rtt_diff -= (rack->r_ctl.rc_rtt_diff / 8);
4378 			rack->r_ctl.rc_rtt_diff += (new_rtt_diff / 8);
4379 		}
4380 	}
4381 	timely_says = rack_make_timely_judgement(rack,
4382 		rack->r_ctl.rc_gp_srtt,
4383 		rack->r_ctl.rc_rtt_diff,
4384 	        rack->r_ctl.rc_prev_gp_srtt
4385 		);
4386 	bytes_ps *= HPTS_USEC_IN_SEC;
4387 	bytes_ps /= utim;
4388 	if (bytes_ps > rack->r_ctl.last_max_bw) {
4389 		/*
4390 		 * Something is on path playing
4391 		 * since this b/w is not possible based
4392 		 * on our BDP (highest rwnd and lowest rtt
4393 		 * we saw in the measurement window).
4394 		 *
4395 		 * Another option here would be to
4396 		 * instead skip the measurement.
4397 		 */
4398 		rack_log_pacing_delay_calc(rack, bytes, reqbytes,
4399 					   bytes_ps, rack->r_ctl.last_max_bw, 0,
4400 					   11, __LINE__, NULL, quality);
4401 		bytes_ps = rack->r_ctl.last_max_bw;
4402 	}
4403 	/* We store gp for b/w in bytes per second */
4404 	if (rack->rc_gp_filled == 0) {
4405 		/* Initial measurment */
4406 		if (bytes_ps) {
4407 			rack->r_ctl.gp_bw = bytes_ps;
4408 			rack->rc_gp_filled = 1;
4409 			rack->r_ctl.num_measurements = 1;
4410 			rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
4411 		} else {
4412 			rack_log_pacing_delay_calc(rack, bytes_ps, reqbytes,
4413 						   rack->r_ctl.rc_app_limited_cnt,
4414 						   0, 0, 10, __LINE__, NULL, quality);
4415 		}
4416 		if (rack->rc_inp->inp_in_hpts &&
4417 		    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
4418 			/*
4419 			 * Ok we can't trust the pacer in this case
4420 			 * where we transition from un-paced to paced.
4421 			 * Or for that matter when the burst mitigation
4422 			 * was making a wild guess and got it wrong.
4423 			 * Stop the pacer and clear up all the aggregate
4424 			 * delays etc.
4425 			 */
4426 			tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
4427 			rack->r_ctl.rc_hpts_flags = 0;
4428 			rack->r_ctl.rc_last_output_to = 0;
4429 		}
4430 		did_add = 2;
4431 	} else if (rack->r_ctl.num_measurements < RACK_REQ_AVG) {
4432 		/* Still a small number run an average */
4433 		rack->r_ctl.gp_bw += bytes_ps;
4434 		addpart = rack->r_ctl.num_measurements;
4435 		rack->r_ctl.num_measurements++;
4436 		if (rack->r_ctl.num_measurements >= RACK_REQ_AVG) {
4437 			/* We have collected enought to move forward */
4438 			rack->r_ctl.gp_bw /= (uint64_t)rack->r_ctl.num_measurements;
4439 		}
4440 		did_add = 3;
4441 	} else {
4442 		/*
4443 		 * We want to take 1/wma of the goodput and add in to 7/8th
4444 		 * of the old value weighted by the srtt. So if your measurement
4445 		 * period is say 2 SRTT's long you would get 1/4 as the
4446 		 * value, if it was like 1/2 SRTT then you would get 1/16th.
4447 		 *
4448 		 * But we must be careful not to take too much i.e. if the
4449 		 * srtt is say 20ms and the measurement is taken over
4450 		 * 400ms our weight would be 400/20 i.e. 20. On the
4451 		 * other hand if we get a measurement over 1ms with a
4452 		 * 10ms rtt we only want to take a much smaller portion.
4453 		 */
4454 		if (rack->r_ctl.num_measurements < 0xff) {
4455 			rack->r_ctl.num_measurements++;
4456 		}
4457 		srtt = (uint64_t)tp->t_srtt;
4458 		if (srtt == 0) {
4459 			/*
4460 			 * Strange why did t_srtt go back to zero?
4461 			 */
4462 			if (rack->r_ctl.rc_rack_min_rtt)
4463 				srtt = rack->r_ctl.rc_rack_min_rtt;
4464 			else
4465 				srtt = HPTS_USEC_IN_MSEC;
4466 		}
4467 		/*
4468 		 * XXXrrs: Note for reviewers, in playing with
4469 		 * dynamic pacing I discovered this GP calculation
4470 		 * as done originally leads to some undesired results.
4471 		 * Basically you can get longer measurements contributing
4472 		 * too much to the WMA. Thus I changed it if you are doing
4473 		 * dynamic adjustments to only do the aportioned adjustment
4474 		 * if we have a very small (time wise) measurement. Longer
4475 		 * measurements just get there weight (defaulting to 1/8)
4476 		 * add to the WMA. We may want to think about changing
4477 		 * this to always do that for both sides i.e. dynamic
4478 		 * and non-dynamic... but considering lots of folks
4479 		 * were playing with this I did not want to change the
4480 		 * calculation per.se. without your thoughts.. Lawerence?
4481 		 * Peter??
4482 		 */
4483 		if (rack->rc_gp_dyn_mul == 0) {
4484 			subpart = rack->r_ctl.gp_bw * utim;
4485 			subpart /= (srtt * 8);
4486 			if (subpart < (rack->r_ctl.gp_bw / 2)) {
4487 				/*
4488 				 * The b/w update takes no more
4489 				 * away then 1/2 our running total
4490 				 * so factor it in.
4491 				 */
4492 				addpart = bytes_ps * utim;
4493 				addpart /= (srtt * 8);
4494 			} else {
4495 				/*
4496 				 * Don't allow a single measurement
4497 				 * to account for more than 1/2 of the
4498 				 * WMA. This could happen on a retransmission
4499 				 * where utim becomes huge compared to
4500 				 * srtt (multiple retransmissions when using
4501 				 * the sending rate which factors in all the
4502 				 * transmissions from the first one).
4503 				 */
4504 				subpart = rack->r_ctl.gp_bw / 2;
4505 				addpart = bytes_ps / 2;
4506 			}
4507 			resid_bw = rack->r_ctl.gp_bw - subpart;
4508 			rack->r_ctl.gp_bw = resid_bw + addpart;
4509 			did_add = 1;
4510 		} else {
4511 			if ((utim / srtt) <= 1) {
4512 				/*
4513 				 * The b/w update was over a small period
4514 				 * of time. The idea here is to prevent a small
4515 				 * measurement time period from counting
4516 				 * too much. So we scale it based on the
4517 				 * time so it attributes less than 1/rack_wma_divisor
4518 				 * of its measurement.
4519 				 */
4520 				subpart = rack->r_ctl.gp_bw * utim;
4521 				subpart /= (srtt * rack_wma_divisor);
4522 				addpart = bytes_ps * utim;
4523 				addpart /= (srtt * rack_wma_divisor);
4524 			} else {
4525 				/*
4526 				 * The scaled measurement was long
4527 				 * enough so lets just add in the
4528 				 * portion of the measurment i.e. 1/rack_wma_divisor
4529 				 */
4530 				subpart = rack->r_ctl.gp_bw / rack_wma_divisor;
4531 				addpart = bytes_ps / rack_wma_divisor;
4532 			}
4533 			if ((rack->measure_saw_probe_rtt == 0) ||
4534 		            (bytes_ps > rack->r_ctl.gp_bw)) {
4535 				/*
4536 				 * For probe-rtt we only add it in
4537 				 * if its larger, all others we just
4538 				 * add in.
4539 				 */
4540 				did_add = 1;
4541 				resid_bw = rack->r_ctl.gp_bw - subpart;
4542 				rack->r_ctl.gp_bw = resid_bw + addpart;
4543 			}
4544 		}
4545 	}
4546 	if ((rack->gp_ready == 0) &&
4547 	    (rack->r_ctl.num_measurements >= rack->r_ctl.req_measurements)) {
4548 		/* We have enough measurements now */
4549 		rack->gp_ready = 1;
4550 		rack_set_cc_pacing(rack);
4551 		if (rack->defer_options)
4552 			rack_apply_deferred_options(rack);
4553 	}
4554 	rack_log_pacing_delay_calc(rack, subpart, addpart, bytes_ps, stim,
4555 				   rack_get_bw(rack), 22, did_add, NULL, quality);
4556 	/* We do not update any multipliers if we are in or have seen a probe-rtt */
4557 	if ((rack->measure_saw_probe_rtt == 0) && rack->rc_gp_rtt_set)
4558 		rack_update_multiplier(rack, timely_says, bytes_ps,
4559 				       rack->r_ctl.rc_gp_srtt,
4560 				       rack->r_ctl.rc_rtt_diff);
4561 	rack_log_pacing_delay_calc(rack, bytes, tim, bytes_ps, stim,
4562 				   rack_get_bw(rack), 3, line, NULL, quality);
4563 	/* reset the gp srtt and setup the new prev */
4564 	rack->r_ctl.rc_prev_gp_srtt = rack->r_ctl.rc_gp_srtt;
4565 	/* Record the lost count for the next measurement */
4566 	rack->r_ctl.rc_loss_at_start = rack->r_ctl.rc_loss_count;
4567 	/*
4568 	 * We restart our diffs based on the gpsrtt in the
4569 	 * measurement window.
4570 	 */
4571 	rack->rc_gp_rtt_set = 0;
4572 	rack->rc_gp_saw_rec = 0;
4573 	rack->rc_gp_saw_ca = 0;
4574 	rack->rc_gp_saw_ss = 0;
4575 	rack->rc_dragged_bottom = 0;
4576 skip_measurement:
4577 
4578 #ifdef STATS
4579 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
4580 				 gput);
4581 	/*
4582 	 * XXXLAS: This is a temporary hack, and should be
4583 	 * chained off VOI_TCP_GPUT when stats(9) grows an
4584 	 * API to deal with chained VOIs.
4585 	 */
4586 	if (tp->t_stats_gput_prev > 0)
4587 		stats_voi_update_abs_s32(tp->t_stats,
4588 					 VOI_TCP_GPUT_ND,
4589 					 ((gput - tp->t_stats_gput_prev) * 100) /
4590 					 tp->t_stats_gput_prev);
4591 #endif
4592 	tp->t_flags &= ~TF_GPUTINPROG;
4593 	tp->t_stats_gput_prev = gput;
4594 	/*
4595 	 * Now are we app limited now and there is space from where we
4596 	 * were to where we want to go?
4597 	 *
4598 	 * We don't do the other case i.e. non-applimited here since
4599 	 * the next send will trigger us picking up the missing data.
4600 	 */
4601 	if (rack->r_ctl.rc_first_appl &&
4602 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
4603 	    rack->r_ctl.rc_app_limited_cnt &&
4604 	    (SEQ_GT(rack->r_ctl.rc_first_appl->r_start, th_ack)) &&
4605 	    ((rack->r_ctl.rc_first_appl->r_end - th_ack) >
4606 	     max(rc_init_window(rack), (MIN_GP_WIN * segsiz)))) {
4607 		/*
4608 		 * Yep there is enough outstanding to make a measurement here.
4609 		 */
4610 		struct rack_sendmap *rsm, fe;
4611 
4612 		rack->r_ctl.rc_gp_lowrtt = 0xffffffff;
4613 		rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
4614 		tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
4615 		rack->app_limited_needs_set = 0;
4616 		tp->gput_seq = th_ack;
4617 		if (rack->in_probe_rtt)
4618 			rack->measure_saw_probe_rtt = 1;
4619 		else if ((rack->measure_saw_probe_rtt) &&
4620 			 (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
4621 			rack->measure_saw_probe_rtt = 0;
4622 		if ((rack->r_ctl.rc_first_appl->r_end - th_ack) >= rack_get_measure_window(tp, rack)) {
4623 			/* There is a full window to gain info from */
4624 			tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
4625 		} else {
4626 			/* We can only measure up to the applimited point */
4627 			tp->gput_ack = tp->gput_seq + (rack->r_ctl.rc_first_appl->r_end - th_ack);
4628 			if ((tp->gput_ack - tp->gput_seq) < (MIN_GP_WIN * segsiz)) {
4629 				/*
4630 				 * We don't have enough to make a measurement.
4631 				 */
4632 				tp->t_flags &= ~TF_GPUTINPROG;
4633 				rack_log_pacing_delay_calc(rack, tp->gput_ack, tp->gput_seq,
4634 							   0, 0, 0, 6, __LINE__, NULL, quality);
4635 				return;
4636 			}
4637 		}
4638 		if (tp->t_state >= TCPS_FIN_WAIT_1) {
4639 			/*
4640 			 * We will get no more data into the SB
4641 			 * this means we need to have the data available
4642 			 * before we start a measurement.
4643 			 */
4644 			if (sbavail(&tp->t_inpcb->inp_socket->so_snd) < (tp->gput_ack - tp->gput_seq)) {
4645 				/* Nope not enough data. */
4646 				return;
4647 			}
4648 		}
4649 		tp->t_flags |= TF_GPUTINPROG;
4650 		/*
4651 		 * Now we need to find the timestamp of the send at tp->gput_seq
4652 		 * for the send based measurement.
4653 		 */
4654 		fe.r_start = tp->gput_seq;
4655 		rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
4656 		if (rsm) {
4657 			/* Ok send-based limit is set */
4658 			if (SEQ_LT(rsm->r_start, tp->gput_seq)) {
4659 				/*
4660 				 * Move back to include the earlier part
4661 				 * so our ack time lines up right (this may
4662 				 * make an overlapping measurement but thats
4663 				 * ok).
4664 				 */
4665 				tp->gput_seq = rsm->r_start;
4666 			}
4667 			if (rsm->r_flags & RACK_ACKED)
4668 				tp->gput_ts = (uint32_t)rsm->r_ack_arrival;
4669 			else
4670 				rack->app_limited_needs_set = 1;
4671 			rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
4672 		} else {
4673 			/*
4674 			 * If we don't find the rsm due to some
4675 			 * send-limit set the current time, which
4676 			 * basically disables the send-limit.
4677 			 */
4678 			struct timeval tv;
4679 
4680 			microuptime(&tv);
4681 			rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
4682 		}
4683 		rack_log_pacing_delay_calc(rack,
4684 					   tp->gput_seq,
4685 					   tp->gput_ack,
4686 					   (uint64_t)rsm,
4687 					   tp->gput_ts,
4688 					   rack->r_ctl.rc_app_limited_cnt,
4689 					   9,
4690 					   __LINE__, NULL, quality);
4691 	}
4692 }
4693 
4694 /*
4695  * CC wrapper hook functions
4696  */
4697 static void
4698 rack_ack_received(struct tcpcb *tp, struct tcp_rack *rack, uint32_t th_ack, uint16_t nsegs,
4699     uint16_t type, int32_t recovery)
4700 {
4701 	uint32_t prior_cwnd, acked;
4702 	struct tcp_log_buffer *lgb = NULL;
4703 	uint8_t labc_to_use, quality;
4704 
4705 	INP_WLOCK_ASSERT(tp->t_inpcb);
4706 	tp->ccv->nsegs = nsegs;
4707 	acked = tp->ccv->bytes_this_ack = (th_ack - tp->snd_una);
4708 	if ((recovery) && (rack->r_ctl.rc_early_recovery_segs)) {
4709 		uint32_t max;
4710 
4711 		max = rack->r_ctl.rc_early_recovery_segs * ctf_fixed_maxseg(tp);
4712 		if (tp->ccv->bytes_this_ack > max) {
4713 			tp->ccv->bytes_this_ack = max;
4714 		}
4715 	}
4716 #ifdef STATS
4717 	stats_voi_update_abs_s32(tp->t_stats, VOI_TCP_CALCFRWINDIFF,
4718 	    ((int32_t)rack->r_ctl.cwnd_to_use) - tp->snd_wnd);
4719 #endif
4720 	quality = RACK_QUALITY_NONE;
4721 	if ((tp->t_flags & TF_GPUTINPROG) &&
4722 	    rack_enough_for_measurement(tp, rack, th_ack, &quality)) {
4723 		/* Measure the Goodput */
4724 		rack_do_goodput_measurement(tp, rack, th_ack, __LINE__, quality);
4725 #ifdef NETFLIX_PEAKRATE
4726 		if ((type == CC_ACK) &&
4727 		    (tp->t_maxpeakrate)) {
4728 			/*
4729 			 * We update t_peakrate_thr. This gives us roughly
4730 			 * one update per round trip time. Note
4731 			 * it will only be used if pace_always is off i.e
4732 			 * we don't do this for paced flows.
4733 			 */
4734 			rack_update_peakrate_thr(tp);
4735 		}
4736 #endif
4737 	}
4738 	/* Which way our we limited, if not cwnd limited no advance in CA */
4739 	if (tp->snd_cwnd <= tp->snd_wnd)
4740 		tp->ccv->flags |= CCF_CWND_LIMITED;
4741 	else
4742 		tp->ccv->flags &= ~CCF_CWND_LIMITED;
4743 	if (tp->snd_cwnd > tp->snd_ssthresh) {
4744 		tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
4745 			 nsegs * V_tcp_abc_l_var * ctf_fixed_maxseg(tp));
4746 		/* For the setting of a window past use the actual scwnd we are using */
4747 		if (tp->t_bytes_acked >= rack->r_ctl.cwnd_to_use) {
4748 			tp->t_bytes_acked -= rack->r_ctl.cwnd_to_use;
4749 			tp->ccv->flags |= CCF_ABC_SENTAWND;
4750 		}
4751 	} else {
4752 		tp->ccv->flags &= ~CCF_ABC_SENTAWND;
4753 		tp->t_bytes_acked = 0;
4754 	}
4755 	prior_cwnd = tp->snd_cwnd;
4756 	if ((recovery == 0) || (rack_max_abc_post_recovery == 0) || rack->r_use_labc_for_rec ||
4757 	    (rack_client_low_buf && (rack->client_bufferlvl < rack_client_low_buf)))
4758 		labc_to_use = rack->rc_labc;
4759 	else
4760 		labc_to_use = rack_max_abc_post_recovery;
4761 	if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
4762 		union tcp_log_stackspecific log;
4763 		struct timeval tv;
4764 
4765 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4766 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4767 		log.u_bbr.flex1 = th_ack;
4768 		log.u_bbr.flex2 = tp->ccv->flags;
4769 		log.u_bbr.flex3 = tp->ccv->bytes_this_ack;
4770 		log.u_bbr.flex4 = tp->ccv->nsegs;
4771 		log.u_bbr.flex5 = labc_to_use;
4772 		log.u_bbr.flex6 = prior_cwnd;
4773 		log.u_bbr.flex7 = V_tcp_do_newsack;
4774 		log.u_bbr.flex8 = 1;
4775 		lgb = tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
4776 				     0, &log, false, NULL, NULL, 0, &tv);
4777 	}
4778 	if (CC_ALGO(tp)->ack_received != NULL) {
4779 		/* XXXLAS: Find a way to live without this */
4780 		tp->ccv->curack = th_ack;
4781 		tp->ccv->labc = labc_to_use;
4782 		tp->ccv->flags |= CCF_USE_LOCAL_ABC;
4783 		CC_ALGO(tp)->ack_received(tp->ccv, type);
4784 	}
4785 	if (lgb) {
4786 		lgb->tlb_stackinfo.u_bbr.flex6 = tp->snd_cwnd;
4787 	}
4788 	if (rack->r_must_retran) {
4789 		if (SEQ_GEQ(th_ack, rack->r_ctl.rc_snd_max_at_rto)) {
4790 			/*
4791 			 * We now are beyond the rxt point so lets disable
4792 			 * the flag.
4793 			 */
4794 			rack->r_ctl.rc_out_at_rto = 0;
4795 			rack->r_must_retran = 0;
4796 		} else if ((prior_cwnd + ctf_fixed_maxseg(tp)) <= tp->snd_cwnd) {
4797 			/*
4798 			 * Only decrement the rc_out_at_rto if the cwnd advances
4799 			 * at least a whole segment. Otherwise next time the peer
4800 			 * acks, we won't be able to send this generaly happens
4801 			 * when we are in Congestion Avoidance.
4802 			 */
4803 			if (acked <= rack->r_ctl.rc_out_at_rto){
4804 				rack->r_ctl.rc_out_at_rto -= acked;
4805 			} else {
4806 				rack->r_ctl.rc_out_at_rto = 0;
4807 			}
4808 		}
4809 	}
4810 #ifdef STATS
4811 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_LCWIN, rack->r_ctl.cwnd_to_use);
4812 #endif
4813 	if (rack->r_ctl.rc_rack_largest_cwnd < rack->r_ctl.cwnd_to_use) {
4814 		rack->r_ctl.rc_rack_largest_cwnd = rack->r_ctl.cwnd_to_use;
4815 	}
4816 #ifdef NETFLIX_PEAKRATE
4817 	/* we enforce max peak rate if it is set and we are not pacing */
4818 	if ((rack->rc_always_pace == 0) &&
4819 	    tp->t_peakrate_thr &&
4820 	    (tp->snd_cwnd > tp->t_peakrate_thr)) {
4821 		tp->snd_cwnd = tp->t_peakrate_thr;
4822 	}
4823 #endif
4824 }
4825 
4826 static void
4827 tcp_rack_partialack(struct tcpcb *tp)
4828 {
4829 	struct tcp_rack *rack;
4830 
4831 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4832 	INP_WLOCK_ASSERT(tp->t_inpcb);
4833 	/*
4834 	 * If we are doing PRR and have enough
4835 	 * room to send <or> we are pacing and prr
4836 	 * is disabled we will want to see if we
4837 	 * can send data (by setting r_wanted_output to
4838 	 * true).
4839 	 */
4840 	if ((rack->r_ctl.rc_prr_sndcnt > 0) ||
4841 	    rack->rack_no_prr)
4842 		rack->r_wanted_output = 1;
4843 }
4844 
4845 static void
4846 rack_post_recovery(struct tcpcb *tp, uint32_t th_ack)
4847 {
4848 	struct tcp_rack *rack;
4849 	uint32_t orig_cwnd;
4850 
4851 	orig_cwnd = tp->snd_cwnd;
4852 	INP_WLOCK_ASSERT(tp->t_inpcb);
4853 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4854 	/* only alert CC if we alerted when we entered */
4855 	if (CC_ALGO(tp)->post_recovery != NULL) {
4856 		tp->ccv->curack = th_ack;
4857 		CC_ALGO(tp)->post_recovery(tp->ccv);
4858 		if (tp->snd_cwnd < tp->snd_ssthresh) {
4859 			/*
4860 			 * Rack has burst control and pacing
4861 			 * so lets not set this any lower than
4862 			 * snd_ssthresh per RFC-6582 (option 2).
4863 			 */
4864 			tp->snd_cwnd = tp->snd_ssthresh;
4865 		}
4866 	}
4867 	if (rack_verbose_logging && (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
4868 		union tcp_log_stackspecific log;
4869 		struct timeval tv;
4870 
4871 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
4872 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
4873 		log.u_bbr.flex1 = th_ack;
4874 		log.u_bbr.flex2 = tp->ccv->flags;
4875 		log.u_bbr.flex3 = tp->ccv->bytes_this_ack;
4876 		log.u_bbr.flex4 = tp->ccv->nsegs;
4877 		log.u_bbr.flex5 = V_tcp_abc_l_var;
4878 		log.u_bbr.flex6 = orig_cwnd;
4879 		log.u_bbr.flex7 = V_tcp_do_newsack;
4880 		log.u_bbr.pkts_out = rack->r_ctl.rc_prr_sndcnt;
4881 		log.u_bbr.flex8 = 2;
4882 		tcp_log_event_(tp, NULL, NULL, NULL, BBR_LOG_CWND, 0,
4883 			       0, &log, false, NULL, NULL, 0, &tv);
4884 	}
4885 	if ((rack->rack_no_prr == 0) &&
4886 	    (rack->no_prr_addback == 0) &&
4887 	    (rack->r_ctl.rc_prr_sndcnt > 0)) {
4888 		/*
4889 		 * Suck the next prr cnt back into cwnd, but
4890 		 * only do that if we are not application limited.
4891 		 */
4892 		if (ctf_outstanding(tp) <= sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
4893 			/*
4894 			 * We are allowed to add back to the cwnd the amount we did
4895 			 * not get out if:
4896 			 * a) no_prr_addback is off.
4897 			 * b) we are not app limited
4898 			 * c) we are doing prr
4899 			 * <and>
4900 			 * d) it is bounded by rack_prr_addbackmax (if addback is 0, then none).
4901 			 */
4902 			tp->snd_cwnd += min((ctf_fixed_maxseg(tp) * rack_prr_addbackmax),
4903 					    rack->r_ctl.rc_prr_sndcnt);
4904 		}
4905 		rack->r_ctl.rc_prr_sndcnt = 0;
4906 		rack_log_to_prr(rack, 1, 0);
4907 	}
4908 	rack_log_to_prr(rack, 14, orig_cwnd);
4909 	tp->snd_recover = tp->snd_una;
4910 	if (rack->r_ctl.dsack_persist) {
4911 		rack->r_ctl.dsack_persist--;
4912 		if (rack->r_ctl.num_dsack && (rack->r_ctl.dsack_persist == 0)) {
4913 			rack->r_ctl.num_dsack = 0;
4914 		}
4915 		rack_log_dsack_event(rack, 1, __LINE__, 0, 0);
4916 	}
4917 	EXIT_RECOVERY(tp->t_flags);
4918 }
4919 
4920 static void
4921 rack_cong_signal(struct tcpcb *tp, uint32_t type, uint32_t ack)
4922 {
4923 	struct tcp_rack *rack;
4924 	uint32_t ssthresh_enter, cwnd_enter, in_rec_at_entry, orig_cwnd;
4925 
4926 	INP_WLOCK_ASSERT(tp->t_inpcb);
4927 #ifdef STATS
4928 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
4929 #endif
4930 	if (IN_RECOVERY(tp->t_flags) == 0) {
4931 		in_rec_at_entry = 0;
4932 		ssthresh_enter = tp->snd_ssthresh;
4933 		cwnd_enter = tp->snd_cwnd;
4934 	} else
4935 		in_rec_at_entry = 1;
4936 	rack = (struct tcp_rack *)tp->t_fb_ptr;
4937 	switch (type) {
4938 	case CC_NDUPACK:
4939 		tp->t_flags &= ~TF_WASFRECOVERY;
4940 		tp->t_flags &= ~TF_WASCRECOVERY;
4941 		if (!IN_FASTRECOVERY(tp->t_flags)) {
4942 			rack->r_ctl.rc_prr_delivered = 0;
4943 			rack->r_ctl.rc_prr_out = 0;
4944 			if (rack->rack_no_prr == 0) {
4945 				rack->r_ctl.rc_prr_sndcnt = ctf_fixed_maxseg(tp);
4946 				rack_log_to_prr(rack, 2, in_rec_at_entry);
4947 			}
4948 			rack->r_ctl.rc_prr_recovery_fs = tp->snd_max - tp->snd_una;
4949 			tp->snd_recover = tp->snd_max;
4950 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4951 				tp->t_flags2 |= TF2_ECN_SND_CWR;
4952 		}
4953 		break;
4954 	case CC_ECN:
4955 		if (!IN_CONGRECOVERY(tp->t_flags) ||
4956 		    /*
4957 		     * Allow ECN reaction on ACK to CWR, if
4958 		     * that data segment was also CE marked.
4959 		     */
4960 		    SEQ_GEQ(ack, tp->snd_recover)) {
4961 			EXIT_CONGRECOVERY(tp->t_flags);
4962 			KMOD_TCPSTAT_INC(tcps_ecn_rcwnd);
4963 			tp->snd_recover = tp->snd_max + 1;
4964 			if (tp->t_flags2 & TF2_ECN_PERMIT)
4965 				tp->t_flags2 |= TF2_ECN_SND_CWR;
4966 		}
4967 		break;
4968 	case CC_RTO:
4969 		tp->t_dupacks = 0;
4970 		tp->t_bytes_acked = 0;
4971 		EXIT_RECOVERY(tp->t_flags);
4972 		tp->snd_ssthresh = max(2, min(tp->snd_wnd, rack->r_ctl.cwnd_to_use) / 2 /
4973 		    ctf_fixed_maxseg(tp)) * ctf_fixed_maxseg(tp);
4974 		orig_cwnd = tp->snd_cwnd;
4975 		tp->snd_cwnd = ctf_fixed_maxseg(tp);
4976 		rack_log_to_prr(rack, 16, orig_cwnd);
4977 		if (tp->t_flags2 & TF2_ECN_PERMIT)
4978 			tp->t_flags2 |= TF2_ECN_SND_CWR;
4979 		break;
4980 	case CC_RTO_ERR:
4981 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4982 		/* RTO was unnecessary, so reset everything. */
4983 		tp->snd_cwnd = tp->snd_cwnd_prev;
4984 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
4985 		tp->snd_recover = tp->snd_recover_prev;
4986 		if (tp->t_flags & TF_WASFRECOVERY) {
4987 			ENTER_FASTRECOVERY(tp->t_flags);
4988 			tp->t_flags &= ~TF_WASFRECOVERY;
4989 		}
4990 		if (tp->t_flags & TF_WASCRECOVERY) {
4991 			ENTER_CONGRECOVERY(tp->t_flags);
4992 			tp->t_flags &= ~TF_WASCRECOVERY;
4993 		}
4994 		tp->snd_nxt = tp->snd_max;
4995 		tp->t_badrxtwin = 0;
4996 		break;
4997 	}
4998 	if ((CC_ALGO(tp)->cong_signal != NULL)  &&
4999 	    (type != CC_RTO)){
5000 		tp->ccv->curack = ack;
5001 		CC_ALGO(tp)->cong_signal(tp->ccv, type);
5002 	}
5003 	if ((in_rec_at_entry == 0) && IN_RECOVERY(tp->t_flags)) {
5004 		rack_log_to_prr(rack, 15, cwnd_enter);
5005 		rack->r_ctl.dsack_byte_cnt = 0;
5006 		rack->r_ctl.retran_during_recovery = 0;
5007 		rack->r_ctl.rc_cwnd_at_erec = cwnd_enter;
5008 		rack->r_ctl.rc_ssthresh_at_erec = ssthresh_enter;
5009 		rack->r_ent_rec_ns = 1;
5010 	}
5011 }
5012 
5013 static inline void
5014 rack_cc_after_idle(struct tcp_rack *rack, struct tcpcb *tp)
5015 {
5016 	uint32_t i_cwnd;
5017 
5018 	INP_WLOCK_ASSERT(tp->t_inpcb);
5019 
5020 #ifdef NETFLIX_STATS
5021 	KMOD_TCPSTAT_INC(tcps_idle_restarts);
5022 	if (tp->t_state == TCPS_ESTABLISHED)
5023 		KMOD_TCPSTAT_INC(tcps_idle_estrestarts);
5024 #endif
5025 	if (CC_ALGO(tp)->after_idle != NULL)
5026 		CC_ALGO(tp)->after_idle(tp->ccv);
5027 
5028 	if (tp->snd_cwnd == 1)
5029 		i_cwnd = tp->t_maxseg;		/* SYN(-ACK) lost */
5030 	else
5031 		i_cwnd = rc_init_window(rack);
5032 
5033 	/*
5034 	 * Being idle is no differnt than the initial window. If the cc
5035 	 * clamps it down below the initial window raise it to the initial
5036 	 * window.
5037 	 */
5038 	if (tp->snd_cwnd < i_cwnd) {
5039 		tp->snd_cwnd = i_cwnd;
5040 	}
5041 }
5042 
5043 /*
5044  * Indicate whether this ack should be delayed.  We can delay the ack if
5045  * following conditions are met:
5046  *	- There is no delayed ack timer in progress.
5047  *	- Our last ack wasn't a 0-sized window. We never want to delay
5048  *	  the ack that opens up a 0-sized window.
5049  *	- LRO wasn't used for this segment. We make sure by checking that the
5050  *	  segment size is not larger than the MSS.
5051  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
5052  *	  connection.
5053  */
5054 #define DELAY_ACK(tp, tlen)			 \
5055 	(((tp->t_flags & TF_RXWIN0SENT) == 0) && \
5056 	((tp->t_flags & TF_DELACK) == 0) &&	 \
5057 	(tlen <= tp->t_maxseg) &&		 \
5058 	(tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
5059 
5060 static struct rack_sendmap *
5061 rack_find_lowest_rsm(struct tcp_rack *rack)
5062 {
5063 	struct rack_sendmap *rsm;
5064 
5065 	/*
5066 	 * Walk the time-order transmitted list looking for an rsm that is
5067 	 * not acked. This will be the one that was sent the longest time
5068 	 * ago that is still outstanding.
5069 	 */
5070 	TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
5071 		if (rsm->r_flags & RACK_ACKED) {
5072 			continue;
5073 		}
5074 		goto finish;
5075 	}
5076 finish:
5077 	return (rsm);
5078 }
5079 
5080 static struct rack_sendmap *
5081 rack_find_high_nonack(struct tcp_rack *rack, struct rack_sendmap *rsm)
5082 {
5083 	struct rack_sendmap *prsm;
5084 
5085 	/*
5086 	 * Walk the sequence order list backward until we hit and arrive at
5087 	 * the highest seq not acked. In theory when this is called it
5088 	 * should be the last segment (which it was not).
5089 	 */
5090 	counter_u64_add(rack_find_high, 1);
5091 	prsm = rsm;
5092 	RB_FOREACH_REVERSE_FROM(prsm, rack_rb_tree_head, rsm) {
5093 		if (prsm->r_flags & (RACK_ACKED | RACK_HAS_FIN)) {
5094 			continue;
5095 		}
5096 		return (prsm);
5097 	}
5098 	return (NULL);
5099 }
5100 
5101 static uint32_t
5102 rack_calc_thresh_rack(struct tcp_rack *rack, uint32_t srtt, uint32_t cts)
5103 {
5104 	int32_t lro;
5105 	uint32_t thresh;
5106 
5107 	/*
5108 	 * lro is the flag we use to determine if we have seen reordering.
5109 	 * If it gets set we have seen reordering. The reorder logic either
5110 	 * works in one of two ways:
5111 	 *
5112 	 * If reorder-fade is configured, then we track the last time we saw
5113 	 * re-ordering occur. If we reach the point where enough time as
5114 	 * passed we no longer consider reordering has occuring.
5115 	 *
5116 	 * Or if reorder-face is 0, then once we see reordering we consider
5117 	 * the connection to alway be subject to reordering and just set lro
5118 	 * to 1.
5119 	 *
5120 	 * In the end if lro is non-zero we add the extra time for
5121 	 * reordering in.
5122 	 */
5123 	if (srtt == 0)
5124 		srtt = 1;
5125 	if (rack->r_ctl.rc_reorder_ts) {
5126 		if (rack->r_ctl.rc_reorder_fade) {
5127 			if (SEQ_GEQ(cts, rack->r_ctl.rc_reorder_ts)) {
5128 				lro = cts - rack->r_ctl.rc_reorder_ts;
5129 				if (lro == 0) {
5130 					/*
5131 					 * No time as passed since the last
5132 					 * reorder, mark it as reordering.
5133 					 */
5134 					lro = 1;
5135 				}
5136 			} else {
5137 				/* Negative time? */
5138 				lro = 0;
5139 			}
5140 			if (lro > rack->r_ctl.rc_reorder_fade) {
5141 				/* Turn off reordering seen too */
5142 				rack->r_ctl.rc_reorder_ts = 0;
5143 				lro = 0;
5144 			}
5145 		} else {
5146 			/* Reodering does not fade */
5147 			lro = 1;
5148 		}
5149 	} else {
5150 		lro = 0;
5151 	}
5152 	if (rack->rc_rack_tmr_std_based == 0) {
5153 		thresh = srtt + rack->r_ctl.rc_pkt_delay;
5154 	} else {
5155 		/* Standards based pkt-delay is 1/4 srtt */
5156 		thresh = srtt +  (srtt >> 2);
5157 	}
5158 	if (lro && (rack->rc_rack_tmr_std_based == 0)) {
5159 		/* It must be set, if not you get 1/4 rtt */
5160 		if (rack->r_ctl.rc_reorder_shift)
5161 			thresh += (srtt >> rack->r_ctl.rc_reorder_shift);
5162 		else
5163 			thresh += (srtt >> 2);
5164 	}
5165 	if (rack->rc_rack_use_dsack &&
5166 	    lro &&
5167 	    (rack->r_ctl.num_dsack > 0)) {
5168 		/*
5169 		 * We only increase the reordering window if we
5170 		 * have seen reordering <and> we have a DSACK count.
5171 		 */
5172 		thresh += rack->r_ctl.num_dsack * (srtt >> 2);
5173 		rack_log_dsack_event(rack, 4, __LINE__, srtt, thresh);
5174 	}
5175 	/* SRTT * 2 is the ceiling */
5176 	if (thresh > (srtt * 2)) {
5177 		thresh = srtt * 2;
5178 	}
5179 	/* And we don't want it above the RTO max either */
5180 	if (thresh > rack_rto_max) {
5181 		thresh = rack_rto_max;
5182 	}
5183 	rack_log_dsack_event(rack, 6, __LINE__, srtt, thresh);
5184 	return (thresh);
5185 }
5186 
5187 static uint32_t
5188 rack_calc_thresh_tlp(struct tcpcb *tp, struct tcp_rack *rack,
5189 		     struct rack_sendmap *rsm, uint32_t srtt)
5190 {
5191 	struct rack_sendmap *prsm;
5192 	uint32_t thresh, len;
5193 	int segsiz;
5194 
5195 	if (srtt == 0)
5196 		srtt = 1;
5197 	if (rack->r_ctl.rc_tlp_threshold)
5198 		thresh = srtt + (srtt / rack->r_ctl.rc_tlp_threshold);
5199 	else
5200 		thresh = (srtt * 2);
5201 
5202 	/* Get the previous sent packet, if any */
5203 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
5204 	counter_u64_add(rack_enter_tlp_calc, 1);
5205 	len = rsm->r_end - rsm->r_start;
5206 	if (rack->rack_tlp_threshold_use == TLP_USE_ID) {
5207 		/* Exactly like the ID */
5208 		if (((tp->snd_max - tp->snd_una) - rack->r_ctl.rc_sacked + rack->r_ctl.rc_holes_rxt) <= segsiz) {
5209 			uint32_t alt_thresh;
5210 			/*
5211 			 * Compensate for delayed-ack with the d-ack time.
5212 			 */
5213 			counter_u64_add(rack_used_tlpmethod, 1);
5214 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5215 			if (alt_thresh > thresh)
5216 				thresh = alt_thresh;
5217 		}
5218 	} else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_ONE) {
5219 		/* 2.1 behavior */
5220 		prsm = TAILQ_PREV(rsm, rack_head, r_tnext);
5221 		if (prsm && (len <= segsiz)) {
5222 			/*
5223 			 * Two packets outstanding, thresh should be (2*srtt) +
5224 			 * possible inter-packet delay (if any).
5225 			 */
5226 			uint32_t inter_gap = 0;
5227 			int idx, nidx;
5228 
5229 			counter_u64_add(rack_used_tlpmethod, 1);
5230 			idx = rsm->r_rtr_cnt - 1;
5231 			nidx = prsm->r_rtr_cnt - 1;
5232 			if (rsm->r_tim_lastsent[nidx] >= prsm->r_tim_lastsent[idx]) {
5233 				/* Yes it was sent later (or at the same time) */
5234 				inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
5235 			}
5236 			thresh += inter_gap;
5237 		} else if (len <= segsiz) {
5238 			/*
5239 			 * Possibly compensate for delayed-ack.
5240 			 */
5241 			uint32_t alt_thresh;
5242 
5243 			counter_u64_add(rack_used_tlpmethod2, 1);
5244 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5245 			if (alt_thresh > thresh)
5246 				thresh = alt_thresh;
5247 		}
5248 	} else if (rack->rack_tlp_threshold_use == TLP_USE_TWO_TWO) {
5249 		/* 2.2 behavior */
5250 		if (len <= segsiz) {
5251 			uint32_t alt_thresh;
5252 			/*
5253 			 * Compensate for delayed-ack with the d-ack time.
5254 			 */
5255 			counter_u64_add(rack_used_tlpmethod, 1);
5256 			alt_thresh = srtt + (srtt / 2) + rack_delayed_ack_time;
5257 			if (alt_thresh > thresh)
5258 				thresh = alt_thresh;
5259 		}
5260 	}
5261 	/* Not above an RTO */
5262 	if (thresh > tp->t_rxtcur) {
5263 		thresh = tp->t_rxtcur;
5264 	}
5265 	/* Not above a RTO max */
5266 	if (thresh > rack_rto_max) {
5267 		thresh = rack_rto_max;
5268 	}
5269 	/* Apply user supplied min TLP */
5270 	if (thresh < rack_tlp_min) {
5271 		thresh = rack_tlp_min;
5272 	}
5273 	return (thresh);
5274 }
5275 
5276 static uint32_t
5277 rack_grab_rtt(struct tcpcb *tp, struct tcp_rack *rack)
5278 {
5279 	/*
5280 	 * We want the rack_rtt which is the
5281 	 * last rtt we measured. However if that
5282 	 * does not exist we fallback to the srtt (which
5283 	 * we probably will never do) and then as a last
5284 	 * resort we use RACK_INITIAL_RTO if no srtt is
5285 	 * yet set.
5286 	 */
5287 	if (rack->rc_rack_rtt)
5288 		return (rack->rc_rack_rtt);
5289 	else if (tp->t_srtt == 0)
5290 		return (RACK_INITIAL_RTO);
5291 	return (tp->t_srtt);
5292 }
5293 
5294 static struct rack_sendmap *
5295 rack_check_recovery_mode(struct tcpcb *tp, uint32_t tsused)
5296 {
5297 	/*
5298 	 * Check to see that we don't need to fall into recovery. We will
5299 	 * need to do so if our oldest transmit is past the time we should
5300 	 * have had an ack.
5301 	 */
5302 	struct tcp_rack *rack;
5303 	struct rack_sendmap *rsm;
5304 	int32_t idx;
5305 	uint32_t srtt, thresh;
5306 
5307 	rack = (struct tcp_rack *)tp->t_fb_ptr;
5308 	if (RB_EMPTY(&rack->r_ctl.rc_mtree)) {
5309 		return (NULL);
5310 	}
5311 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5312 	if (rsm == NULL)
5313 		return (NULL);
5314 
5315 	if (rsm->r_flags & RACK_ACKED) {
5316 		rsm = rack_find_lowest_rsm(rack);
5317 		if (rsm == NULL)
5318 			return (NULL);
5319 	}
5320 	idx = rsm->r_rtr_cnt - 1;
5321 	srtt = rack_grab_rtt(tp, rack);
5322 	thresh = rack_calc_thresh_rack(rack, srtt, tsused);
5323 	if (TSTMP_LT(tsused, ((uint32_t)rsm->r_tim_lastsent[idx]))) {
5324 		return (NULL);
5325 	}
5326 	if ((tsused - ((uint32_t)rsm->r_tim_lastsent[idx])) < thresh) {
5327 		return (NULL);
5328 	}
5329 	/* Ok if we reach here we are over-due and this guy can be sent */
5330 	if (IN_RECOVERY(tp->t_flags) == 0) {
5331 		/*
5332 		 * For the one that enters us into recovery record undo
5333 		 * info.
5334 		 */
5335 		rack->r_ctl.rc_rsm_start = rsm->r_start;
5336 		rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
5337 		rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
5338 	}
5339 	rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
5340 	return (rsm);
5341 }
5342 
5343 static uint32_t
5344 rack_get_persists_timer_val(struct tcpcb *tp, struct tcp_rack *rack)
5345 {
5346 	int32_t t;
5347 	int32_t tt;
5348 	uint32_t ret_val;
5349 
5350 	t = (tp->t_srtt + (tp->t_rttvar << 2));
5351 	RACK_TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
5352  	    rack_persist_min, rack_persist_max, rack->r_ctl.timer_slop);
5353 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
5354 		tp->t_rxtshift++;
5355 	rack->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
5356 	ret_val = (uint32_t)tt;
5357 	return (ret_val);
5358 }
5359 
5360 static uint32_t
5361 rack_timer_start(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int sup_rack)
5362 {
5363 	/*
5364 	 * Start the FR timer, we do this based on getting the first one in
5365 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
5366 	 * events we need to stop the running timer (if its running) before
5367 	 * starting the new one.
5368 	 */
5369 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
5370 	uint32_t srtt_cur;
5371 	int32_t idx;
5372 	int32_t is_tlp_timer = 0;
5373 	struct rack_sendmap *rsm;
5374 
5375 	if (rack->t_timers_stopped) {
5376 		/* All timers have been stopped none are to run */
5377 		return (0);
5378 	}
5379 	if (rack->rc_in_persist) {
5380 		/* We can't start any timer in persists */
5381 		return (rack_get_persists_timer_val(tp, rack));
5382 	}
5383 	rack->rc_on_min_to = 0;
5384 	if ((tp->t_state < TCPS_ESTABLISHED) ||
5385 	    ((tp->t_flags & TF_SACK_PERMIT) == 0)) {
5386 		goto activate_rxt;
5387 	}
5388 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5389 	if ((rsm == NULL) || sup_rack) {
5390 		/* Nothing on the send map or no rack */
5391 activate_rxt:
5392 		time_since_sent = 0;
5393 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
5394 		if (rsm) {
5395 			/*
5396 			 * Should we discount the RTX timer any?
5397 			 *
5398 			 * We want to discount it the smallest amount.
5399 			 * If a timer (Rack/TLP or RXT) has gone off more
5400 			 * recently thats the discount we want to use (now - timer time).
5401 			 * If the retransmit of the oldest packet was more recent then
5402 			 * we want to use that (now - oldest-packet-last_transmit_time).
5403 			 *
5404 			 */
5405 			idx = rsm->r_rtr_cnt - 1;
5406 			if (TSTMP_GEQ(rack->r_ctl.rc_tlp_rxt_last_time, ((uint32_t)rsm->r_tim_lastsent[idx])))
5407 				tstmp_touse = (uint32_t)rack->r_ctl.rc_tlp_rxt_last_time;
5408 			else
5409 				tstmp_touse = (uint32_t)rsm->r_tim_lastsent[idx];
5410 			if (TSTMP_GT(cts, tstmp_touse))
5411 			    time_since_sent = cts - tstmp_touse;
5412 		}
5413 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
5414 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
5415 			to = tp->t_rxtcur;
5416 			if (to > time_since_sent)
5417 				to -= time_since_sent;
5418 			else
5419 				to = rack->r_ctl.rc_min_to;
5420 			if (to == 0)
5421 				to = 1;
5422 			/* Special case for KEEPINIT */
5423 			if ((TCPS_HAVEESTABLISHED(tp->t_state) == 0) &&
5424 			    (TP_KEEPINIT(tp) != 0) &&
5425 			    rsm) {
5426 				/*
5427 				 * We have to put a ceiling on the rxt timer
5428 				 * of the keep-init timeout.
5429 				 */
5430 				uint32_t max_time, red;
5431 
5432 				max_time = TICKS_2_USEC(TP_KEEPINIT(tp));
5433 				if (TSTMP_GT(cts, (uint32_t)rsm->r_tim_lastsent[0])) {
5434 					red = (cts - (uint32_t)rsm->r_tim_lastsent[0]);
5435 					if (red < max_time)
5436 						max_time -= red;
5437 					else
5438 						max_time = 1;
5439 				}
5440 				/* Reduce timeout to the keep value if needed */
5441 				if (max_time < to)
5442 					to = max_time;
5443 			}
5444 			return (to);
5445 		}
5446 		return (0);
5447 	}
5448 	if (rsm->r_flags & RACK_ACKED) {
5449 		rsm = rack_find_lowest_rsm(rack);
5450 		if (rsm == NULL) {
5451 			/* No lowest? */
5452 			goto activate_rxt;
5453 		}
5454 	}
5455 	if (rack->sack_attack_disable) {
5456 		/*
5457 		 * We don't want to do
5458 		 * any TLP's if you are an attacker.
5459 		 * Though if you are doing what
5460 		 * is expected you may still have
5461 		 * SACK-PASSED marks.
5462 		 */
5463 		goto activate_rxt;
5464 	}
5465 	/* Convert from ms to usecs */
5466 	if ((rsm->r_flags & RACK_SACK_PASSED) || (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
5467 		if ((tp->t_flags & TF_SENTFIN) &&
5468 		    ((tp->snd_max - tp->snd_una) == 1) &&
5469 		    (rsm->r_flags & RACK_HAS_FIN)) {
5470 			/*
5471 			 * We don't start a rack timer if all we have is a
5472 			 * FIN outstanding.
5473 			 */
5474 			goto activate_rxt;
5475 		}
5476 		if ((rack->use_rack_rr == 0) &&
5477 		    (IN_FASTRECOVERY(tp->t_flags)) &&
5478 		    (rack->rack_no_prr == 0) &&
5479 		     (rack->r_ctl.rc_prr_sndcnt  < ctf_fixed_maxseg(tp))) {
5480 			/*
5481 			 * We are not cheating, in recovery  and
5482 			 * not enough ack's to yet get our next
5483 			 * retransmission out.
5484 			 *
5485 			 * Note that classified attackers do not
5486 			 * get to use the rack-cheat.
5487 			 */
5488 			goto activate_tlp;
5489 		}
5490 		srtt = rack_grab_rtt(tp, rack);
5491 		thresh = rack_calc_thresh_rack(rack, srtt, cts);
5492 		idx = rsm->r_rtr_cnt - 1;
5493 		exp = ((uint32_t)rsm->r_tim_lastsent[idx]) + thresh;
5494 		if (SEQ_GEQ(exp, cts)) {
5495 			to = exp - cts;
5496 			if (to < rack->r_ctl.rc_min_to) {
5497 				to = rack->r_ctl.rc_min_to;
5498 				if (rack->r_rr_config == 3)
5499 					rack->rc_on_min_to = 1;
5500 			}
5501 		} else {
5502 			to = rack->r_ctl.rc_min_to;
5503 			if (rack->r_rr_config == 3)
5504 				rack->rc_on_min_to = 1;
5505 		}
5506 	} else {
5507 		/* Ok we need to do a TLP not RACK */
5508 activate_tlp:
5509 		if ((rack->rc_tlp_in_progress != 0) &&
5510 		    (rack->r_ctl.rc_tlp_cnt_out >= rack_tlp_limit)) {
5511 			/*
5512 			 * The previous send was a TLP and we have sent
5513 			 * N TLP's without sending new data.
5514 			 */
5515 			goto activate_rxt;
5516 		}
5517 		rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
5518 		if (rsm == NULL) {
5519 			/* We found no rsm to TLP with. */
5520 			goto activate_rxt;
5521 		}
5522 		if (rsm->r_flags & RACK_HAS_FIN) {
5523 			/* If its a FIN we dont do TLP */
5524 			rsm = NULL;
5525 			goto activate_rxt;
5526 		}
5527 		idx = rsm->r_rtr_cnt - 1;
5528 		time_since_sent = 0;
5529 		if (TSTMP_GEQ(((uint32_t)rsm->r_tim_lastsent[idx]), rack->r_ctl.rc_tlp_rxt_last_time))
5530 			tstmp_touse = (uint32_t)rsm->r_tim_lastsent[idx];
5531 		else
5532 			tstmp_touse = (uint32_t)rack->r_ctl.rc_tlp_rxt_last_time;
5533 		if (TSTMP_GT(cts, tstmp_touse))
5534 		    time_since_sent = cts - tstmp_touse;
5535 		is_tlp_timer = 1;
5536 		if (tp->t_srtt) {
5537 			if ((rack->rc_srtt_measure_made == 0) &&
5538 			    (tp->t_srtt == 1)) {
5539 				/*
5540 				 * If another stack as run and set srtt to 1,
5541 				 * then the srtt was 0, so lets use the initial.
5542 				 */
5543 				srtt = RACK_INITIAL_RTO;
5544 			} else {
5545 				srtt_cur = tp->t_srtt;
5546 				srtt = srtt_cur;
5547 			}
5548 		} else
5549 			srtt = RACK_INITIAL_RTO;
5550 		/*
5551 		 * If the SRTT is not keeping up and the
5552 		 * rack RTT has spiked we want to use
5553 		 * the last RTT not the smoothed one.
5554 		 */
5555 		if (rack_tlp_use_greater &&
5556 		    tp->t_srtt &&
5557 		    (srtt < rack_grab_rtt(tp, rack))) {
5558 			srtt = rack_grab_rtt(tp, rack);
5559 		}
5560 		thresh = rack_calc_thresh_tlp(tp, rack, rsm, srtt);
5561 		if (thresh > time_since_sent) {
5562 			to = thresh - time_since_sent;
5563 		} else {
5564 			to = rack->r_ctl.rc_min_to;
5565 			rack_log_alt_to_to_cancel(rack,
5566 						  thresh,		/* flex1 */
5567 						  time_since_sent,	/* flex2 */
5568 						  tstmp_touse,		/* flex3 */
5569 						  rack->r_ctl.rc_tlp_rxt_last_time, /* flex4 */
5570 						  (uint32_t)rsm->r_tim_lastsent[idx],
5571 						  srtt,
5572 						  idx, 99);
5573 		}
5574 		if (to < rack_tlp_min) {
5575 			to = rack_tlp_min;
5576 		}
5577 		if (to > TICKS_2_USEC(TCPTV_REXMTMAX)) {
5578 			/*
5579 			 * If the TLP time works out to larger than the max
5580 			 * RTO lets not do TLP.. just RTO.
5581 			 */
5582 			goto activate_rxt;
5583 		}
5584 	}
5585 	if (is_tlp_timer == 0) {
5586 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
5587 	} else {
5588 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
5589 	}
5590 	if (to == 0)
5591 		to = 1;
5592 	return (to);
5593 }
5594 
5595 static void
5596 rack_enter_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5597 {
5598 	if (rack->rc_in_persist == 0) {
5599 		if (tp->t_flags & TF_GPUTINPROG) {
5600 			/*
5601 			 * Stop the goodput now, the calling of the
5602 			 * measurement function clears the flag.
5603 			 */
5604 			rack_do_goodput_measurement(tp, rack, tp->snd_una, __LINE__,
5605 						    RACK_QUALITY_PERSIST);
5606 		}
5607 #ifdef NETFLIX_SHARED_CWND
5608 		if (rack->r_ctl.rc_scw) {
5609 			tcp_shared_cwnd_idle(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
5610 			rack->rack_scwnd_is_idle = 1;
5611 		}
5612 #endif
5613 		rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
5614 		if (rack->r_ctl.rc_went_idle_time == 0)
5615 			rack->r_ctl.rc_went_idle_time = 1;
5616 		rack_timer_cancel(tp, rack, cts, __LINE__);
5617 		tp->t_rxtshift = 0;
5618 		RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
5619 			      rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
5620 		rack->rc_in_persist = 1;
5621 	}
5622 }
5623 
5624 static void
5625 rack_exit_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
5626 {
5627 	if (rack->rc_inp->inp_in_hpts) {
5628 		tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
5629 		rack->r_ctl.rc_hpts_flags = 0;
5630 	}
5631 #ifdef NETFLIX_SHARED_CWND
5632 	if (rack->r_ctl.rc_scw) {
5633 		tcp_shared_cwnd_active(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
5634 		rack->rack_scwnd_is_idle = 0;
5635 	}
5636 #endif
5637 	if (rack->rc_gp_dyn_mul &&
5638 	    (rack->use_fixed_rate == 0) &&
5639 	    (rack->rc_always_pace)) {
5640 		/*
5641 		 * Do we count this as if a probe-rtt just
5642 		 * finished?
5643 		 */
5644 		uint32_t time_idle, idle_min;
5645 
5646 		time_idle = tcp_get_usecs(NULL) - rack->r_ctl.rc_went_idle_time;
5647 		idle_min = rack_min_probertt_hold;
5648 		if (rack_probertt_gpsrtt_cnt_div) {
5649 			uint64_t extra;
5650 			extra = (uint64_t)rack->r_ctl.rc_gp_srtt *
5651 				(uint64_t)rack_probertt_gpsrtt_cnt_mul;
5652 			extra /= (uint64_t)rack_probertt_gpsrtt_cnt_div;
5653 			idle_min += (uint32_t)extra;
5654 		}
5655 		if (time_idle >= idle_min) {
5656 			/* Yes, we count it as a probe-rtt. */
5657 			uint32_t us_cts;
5658 
5659 			us_cts = tcp_get_usecs(NULL);
5660 			if (rack->in_probe_rtt == 0) {
5661 				rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
5662 				rack->r_ctl.rc_time_probertt_entered = rack->r_ctl.rc_lower_rtt_us_cts;
5663 				rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts;
5664 				rack->r_ctl.rc_time_of_last_probertt = rack->r_ctl.rc_lower_rtt_us_cts;
5665 			} else {
5666 				rack_exit_probertt(rack, us_cts);
5667 			}
5668 		}
5669 	}
5670 	rack->rc_in_persist = 0;
5671 	rack->r_ctl.rc_went_idle_time = 0;
5672 	tp->t_rxtshift = 0;
5673 	RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
5674 	   rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
5675 	rack->r_ctl.rc_agg_delayed = 0;
5676 	rack->r_early = 0;
5677 	rack->r_late = 0;
5678 	rack->r_ctl.rc_agg_early = 0;
5679 }
5680 
5681 static void
5682 rack_log_hpts_diag(struct tcp_rack *rack, uint32_t cts,
5683 		   struct hpts_diag *diag, struct timeval *tv)
5684 {
5685 	if (rack_verbose_logging && rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
5686 		union tcp_log_stackspecific log;
5687 
5688 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
5689 		log.u_bbr.flex1 = diag->p_nxt_slot;
5690 		log.u_bbr.flex2 = diag->p_cur_slot;
5691 		log.u_bbr.flex3 = diag->slot_req;
5692 		log.u_bbr.flex4 = diag->inp_hptsslot;
5693 		log.u_bbr.flex5 = diag->slot_remaining;
5694 		log.u_bbr.flex6 = diag->need_new_to;
5695 		log.u_bbr.flex7 = diag->p_hpts_active;
5696 		log.u_bbr.flex8 = diag->p_on_min_sleep;
5697 		/* Hijack other fields as needed */
5698 		log.u_bbr.epoch = diag->have_slept;
5699 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
5700 		log.u_bbr.pkts_out = diag->co_ret;
5701 		log.u_bbr.applimited = diag->hpts_sleep_time;
5702 		log.u_bbr.delivered = diag->p_prev_slot;
5703 		log.u_bbr.inflight = diag->p_runningslot;
5704 		log.u_bbr.bw_inuse = diag->wheel_slot;
5705 		log.u_bbr.rttProp = diag->wheel_cts;
5706 		log.u_bbr.timeStamp = cts;
5707 		log.u_bbr.delRate = diag->maxslots;
5708 		log.u_bbr.cur_del_rate = diag->p_curtick;
5709 		log.u_bbr.cur_del_rate <<= 32;
5710 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
5711 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
5712 		    &rack->rc_inp->inp_socket->so_rcv,
5713 		    &rack->rc_inp->inp_socket->so_snd,
5714 		    BBR_LOG_HPTSDIAG, 0,
5715 		    0, &log, false, tv);
5716 	}
5717 
5718 }
5719 
5720 static void
5721 rack_log_wakeup(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb, uint32_t len, int type)
5722 {
5723 	if (rack_verbose_logging && rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
5724 		union tcp_log_stackspecific log;
5725 		struct timeval tv;
5726 
5727 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
5728 		log.u_bbr.flex1 = sb->sb_flags;
5729 		log.u_bbr.flex2 = len;
5730 		log.u_bbr.flex3 = sb->sb_state;
5731 		log.u_bbr.flex8 = type;
5732 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
5733 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
5734 		    &rack->rc_inp->inp_socket->so_rcv,
5735 		    &rack->rc_inp->inp_socket->so_snd,
5736 		    TCP_LOG_SB_WAKE, 0,
5737 		    len, &log, false, &tv);
5738 	}
5739 }
5740 
5741 static void
5742 rack_start_hpts_timer(struct tcp_rack *rack, struct tcpcb *tp, uint32_t cts,
5743       int32_t slot, uint32_t tot_len_this_send, int sup_rack)
5744 {
5745 	struct hpts_diag diag;
5746 	struct inpcb *inp;
5747 	struct timeval tv;
5748 	uint32_t delayed_ack = 0;
5749 	uint32_t hpts_timeout;
5750 	uint32_t entry_slot = slot;
5751 	uint8_t stopped;
5752 	uint32_t left = 0;
5753 	uint32_t us_cts;
5754 
5755 	inp = tp->t_inpcb;
5756 	if ((tp->t_state == TCPS_CLOSED) ||
5757 	    (tp->t_state == TCPS_LISTEN)) {
5758 		return;
5759 	}
5760 	if (inp->inp_in_hpts) {
5761 		/* Already on the pacer */
5762 		return;
5763 	}
5764 	stopped = rack->rc_tmr_stopped;
5765 	if (stopped && TSTMP_GT(rack->r_ctl.rc_timer_exp, cts)) {
5766 		left = rack->r_ctl.rc_timer_exp - cts;
5767 	}
5768 	rack->r_ctl.rc_timer_exp = 0;
5769 	rack->r_ctl.rc_hpts_flags = 0;
5770 	us_cts = tcp_get_usecs(&tv);
5771 	/* Now early/late accounting */
5772 	rack_log_pacing_delay_calc(rack, entry_slot, slot, 0, 0, 0, 26, __LINE__, NULL, 0);
5773 	if (rack->r_early && (rack->rc_ack_can_sendout_data == 0)) {
5774 		/*
5775 		 * We have a early carry over set,
5776 		 * we can always add more time so we
5777 		 * can always make this compensation.
5778 		 *
5779 		 * Note if ack's are allowed to wake us do not
5780 		 * penalize the next timer for being awoke
5781 		 * by an ack aka the rc_agg_early (non-paced mode).
5782 		 */
5783 		slot += rack->r_ctl.rc_agg_early;
5784 		rack->r_early = 0;
5785 		rack->r_ctl.rc_agg_early = 0;
5786 	}
5787 	if (rack->r_late) {
5788 		/*
5789 		 * This is harder, we can
5790 		 * compensate some but it
5791 		 * really depends on what
5792 		 * the current pacing time is.
5793 		 */
5794 		if (rack->r_ctl.rc_agg_delayed >= slot) {
5795 			/*
5796 			 * We can't compensate for it all.
5797 			 * And we have to have some time
5798 			 * on the clock. We always have a min
5799 			 * 10 slots (10 x 10 i.e. 100 usecs).
5800 			 */
5801 			if (slot <= HPTS_TICKS_PER_SLOT) {
5802 				/* We gain delay */
5803 				rack->r_ctl.rc_agg_delayed += (HPTS_TICKS_PER_SLOT - slot);
5804 				slot = HPTS_TICKS_PER_SLOT;
5805 			} else {
5806 				/* We take off some */
5807 				rack->r_ctl.rc_agg_delayed -= (slot - HPTS_TICKS_PER_SLOT);
5808 				slot = HPTS_TICKS_PER_SLOT;
5809 			}
5810 		} else {
5811 			slot -= rack->r_ctl.rc_agg_delayed;
5812 			rack->r_ctl.rc_agg_delayed = 0;
5813 			/* Make sure we have 100 useconds at minimum */
5814 			if (slot < HPTS_TICKS_PER_SLOT) {
5815 				rack->r_ctl.rc_agg_delayed = HPTS_TICKS_PER_SLOT - slot;
5816 				slot = HPTS_TICKS_PER_SLOT;
5817 			}
5818 			if (rack->r_ctl.rc_agg_delayed == 0)
5819 				rack->r_late = 0;
5820 		}
5821 	}
5822 	if (slot) {
5823 		/* We are pacing too */
5824 		rack->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
5825 	}
5826 	hpts_timeout = rack_timer_start(tp, rack, cts, sup_rack);
5827 #ifdef NETFLIX_EXP_DETECTION
5828 	if (rack->sack_attack_disable &&
5829 	    (slot < tcp_sad_pacing_interval)) {
5830 		/*
5831 		 * We have a potential attacker on
5832 		 * the line. We have possibly some
5833 		 * (or now) pacing time set. We want to
5834 		 * slow down the processing of sacks by some
5835 		 * amount (if it is an attacker). Set the default
5836 		 * slot for attackers in place (unless the orginal
5837 		 * interval is longer). Its stored in
5838 		 * micro-seconds, so lets convert to msecs.
5839 		 */
5840 		slot = tcp_sad_pacing_interval;
5841 	}
5842 #endif
5843 	if (tp->t_flags & TF_DELACK) {
5844 		delayed_ack = TICKS_2_USEC(tcp_delacktime);
5845 		rack->r_ctl.rc_hpts_flags |= PACE_TMR_DELACK;
5846 	}
5847 	if (delayed_ack && ((hpts_timeout == 0) ||
5848 			    (delayed_ack < hpts_timeout)))
5849 		hpts_timeout = delayed_ack;
5850 	else
5851 		rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
5852 	/*
5853 	 * If no timers are going to run and we will fall off the hptsi
5854 	 * wheel, we resort to a keep-alive timer if its configured.
5855 	 */
5856 	if ((hpts_timeout == 0) &&
5857 	    (slot == 0)) {
5858 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
5859 		    (tp->t_state <= TCPS_CLOSING)) {
5860 			/*
5861 			 * Ok we have no timer (persists, rack, tlp, rxt  or
5862 			 * del-ack), we don't have segments being paced. So
5863 			 * all that is left is the keepalive timer.
5864 			 */
5865 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
5866 				/* Get the established keep-alive time */
5867 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
5868 			} else {
5869 				/*
5870 				 * Get the initial setup keep-alive time,
5871 				 * note that this is probably not going to
5872 				 * happen, since rack will be running a rxt timer
5873 				 * if a SYN of some sort is outstanding. It is
5874 				 * actually handled in rack_timeout_rxt().
5875 				 */
5876 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
5877 			}
5878 			rack->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
5879 			if (rack->in_probe_rtt) {
5880 				/*
5881 				 * We want to instead not wake up a long time from
5882 				 * now but to wake up about the time we would
5883 				 * exit probe-rtt and initiate a keep-alive ack.
5884 				 * This will get us out of probe-rtt and update
5885 				 * our min-rtt.
5886 				 */
5887 				hpts_timeout = rack_min_probertt_hold;
5888 			}
5889 		}
5890 	}
5891 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
5892 	    (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
5893 		/*
5894 		 * RACK, TLP, persists and RXT timers all are restartable
5895 		 * based on actions input .. i.e we received a packet (ack
5896 		 * or sack) and that changes things (rw, or snd_una etc).
5897 		 * Thus we can restart them with a new value. For
5898 		 * keep-alive, delayed_ack we keep track of what was left
5899 		 * and restart the timer with a smaller value.
5900 		 */
5901 		if (left < hpts_timeout)
5902 			hpts_timeout = left;
5903 	}
5904 	if (hpts_timeout) {
5905 		/*
5906 		 * Hack alert for now we can't time-out over 2,147,483
5907 		 * seconds (a bit more than 596 hours), which is probably ok
5908 		 * :).
5909 		 */
5910 		if (hpts_timeout > 0x7ffffffe)
5911 			hpts_timeout = 0x7ffffffe;
5912 		rack->r_ctl.rc_timer_exp = cts + hpts_timeout;
5913 	}
5914 	rack_log_pacing_delay_calc(rack, entry_slot, slot, hpts_timeout, 0, 0, 27, __LINE__, NULL, 0);
5915 	if ((rack->gp_ready == 0) &&
5916 	    (rack->use_fixed_rate == 0) &&
5917 	    (hpts_timeout < slot) &&
5918 	    (rack->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
5919 		/*
5920 		 * We have no good estimate yet for the
5921 		 * old clunky burst mitigation or the
5922 		 * real pacing. And the tlp or rxt is smaller
5923 		 * than the pacing calculation. Lets not
5924 		 * pace that long since we know the calculation
5925 		 * so far is not accurate.
5926 		 */
5927 		slot = hpts_timeout;
5928 	}
5929 	rack->r_ctl.last_pacing_time = slot;
5930 	/**
5931 	 * Turn off all the flags for queuing by default. The
5932 	 * flags have important meanings to what happens when
5933 	 * LRO interacts with the transport. Most likely (by default now)
5934 	 * mbuf_queueing and ack compression are on. So the transport
5935 	 * has a couple of flags that control what happens (if those
5936 	 * are not on then these flags won't have any effect since it
5937 	 * won't go through the queuing LRO path).
5938 	 *
5939 	 * INP_MBUF_QUEUE_READY - This flags says that I am busy
5940 	 *                        pacing output, so don't disturb. But
5941 	 *                        it also means LRO can wake me if there
5942 	 *                        is a SACK arrival.
5943 	 *
5944 	 * INP_DONT_SACK_QUEUE - This flag is used in conjunction
5945 	 *                       with the above flag (QUEUE_READY) and
5946 	 *                       when present it says don't even wake me
5947 	 *                       if a SACK arrives.
5948 	 *
5949 	 * The idea behind these flags is that if we are pacing we
5950 	 * set the MBUF_QUEUE_READY and only get woken up if
5951 	 * a SACK arrives (which could change things) or if
5952 	 * our pacing timer expires. If, however, we have a rack
5953 	 * timer running, then we don't even want a sack to wake
5954 	 * us since the rack timer has to expire before we can send.
5955 	 *
5956 	 * Other cases should usually have none of the flags set
5957 	 * so LRO can call into us.
5958 	 */
5959 	inp->inp_flags2 &= ~(INP_DONT_SACK_QUEUE|INP_MBUF_QUEUE_READY);
5960 	if (slot) {
5961 		rack->r_ctl.rc_last_output_to = us_cts + slot;
5962 		/*
5963 		 * A pacing timer (slot) is being set, in
5964 		 * such a case we cannot send (we are blocked by
5965 		 * the timer). So lets tell LRO that it should not
5966 		 * wake us unless there is a SACK. Note this only
5967 		 * will be effective if mbuf queueing is on or
5968 		 * compressed acks are being processed.
5969 		 */
5970 		inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
5971 		/*
5972 		 * But wait if we have a Rack timer running
5973 		 * even a SACK should not disturb us (with
5974 		 * the exception of r_rr_config 3).
5975 		 */
5976 		if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
5977 		    (rack->r_rr_config != 3))
5978 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
5979 		if (rack->rc_ack_can_sendout_data) {
5980 			/*
5981 			 * Ahh but wait, this is that special case
5982 			 * where the pacing timer can be disturbed
5983 			 * backout the changes (used for non-paced
5984 			 * burst limiting).
5985 			 */
5986 			inp->inp_flags2 &= ~(INP_DONT_SACK_QUEUE|INP_MBUF_QUEUE_READY);
5987 		}
5988 		if ((rack->use_rack_rr) &&
5989 		    (rack->r_rr_config < 2) &&
5990 		    ((hpts_timeout) && (hpts_timeout < slot))) {
5991 			/*
5992 			 * Arrange for the hpts to kick back in after the
5993 			 * t-o if the t-o does not cause a send.
5994 			 */
5995 			(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
5996 						   __LINE__, &diag);
5997 			rack_log_hpts_diag(rack, us_cts, &diag, &tv);
5998 			rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
5999 		} else {
6000 			(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
6001 						   __LINE__, &diag);
6002 			rack_log_hpts_diag(rack, us_cts, &diag, &tv);
6003 			rack_log_to_start(rack, cts, hpts_timeout, slot, 1);
6004 		}
6005 	} else if (hpts_timeout) {
6006 		/*
6007 		 * With respect to inp_flags2 here, lets let any new acks wake
6008 		 * us up here. Since we are not pacing (no pacing timer), output
6009 		 * can happen so we should let it. If its a Rack timer, then any inbound
6010 		 * packet probably won't change the sending (we will be blocked)
6011 		 * but it may change the prr stats so letting it in (the set defaults
6012 		 * at the start of this block) are good enough.
6013 		 */
6014 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
6015 					   __LINE__, &diag);
6016 		rack_log_hpts_diag(rack, us_cts, &diag, &tv);
6017 		rack_log_to_start(rack, cts, hpts_timeout, slot, 0);
6018 	} else {
6019 		/* No timer starting */
6020 #ifdef INVARIANTS
6021 		if (SEQ_GT(tp->snd_max, tp->snd_una)) {
6022 			panic("tp:%p rack:%p tlts:%d cts:%u slot:%u pto:%u -- no timer started?",
6023 			    tp, rack, tot_len_this_send, cts, slot, hpts_timeout);
6024 		}
6025 #endif
6026 	}
6027 	rack->rc_tmr_stopped = 0;
6028 	if (slot)
6029 		rack_log_type_bbrsnd(rack, tot_len_this_send, slot, us_cts, &tv);
6030 }
6031 
6032 /*
6033  * RACK Timer, here we simply do logging and house keeping.
6034  * the normal rack_output() function will call the
6035  * appropriate thing to check if we need to do a RACK retransmit.
6036  * We return 1, saying don't proceed with rack_output only
6037  * when all timers have been stopped (destroyed PCB?).
6038  */
6039 static int
6040 rack_timeout_rack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6041 {
6042 	/*
6043 	 * This timer simply provides an internal trigger to send out data.
6044 	 * The check_recovery_mode call will see if there are needed
6045 	 * retransmissions, if so we will enter fast-recovery. The output
6046 	 * call may or may not do the same thing depending on sysctl
6047 	 * settings.
6048 	 */
6049 	struct rack_sendmap *rsm;
6050 
6051 	if (tp->t_timers->tt_flags & TT_STOPPED) {
6052 		return (1);
6053 	}
6054 	counter_u64_add(rack_to_tot, 1);
6055 	if (rack->r_state && (rack->r_state != tp->t_state))
6056 		rack_set_state(tp, rack);
6057 	rack->rc_on_min_to = 0;
6058 	rsm = rack_check_recovery_mode(tp, cts);
6059 	rack_log_to_event(rack, RACK_TO_FRM_RACK, rsm);
6060 	if (rsm) {
6061 		rack->r_ctl.rc_resend = rsm;
6062 		rack->r_timer_override = 1;
6063 		if (rack->use_rack_rr) {
6064 			/*
6065 			 * Don't accumulate extra pacing delay
6066 			 * we are allowing the rack timer to
6067 			 * over-ride pacing i.e. rrr takes precedence
6068 			 * if the pacing interval is longer than the rrr
6069 			 * time (in other words we get the min pacing
6070 			 * time versus rrr pacing time).
6071 			 */
6072 			rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
6073 		}
6074 	}
6075 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
6076 	if (rsm == NULL) {
6077 		/* restart a timer and return 1 */
6078 		rack_start_hpts_timer(rack, tp, cts,
6079 				      0, 0, 0);
6080 		return (1);
6081 	}
6082 	return (0);
6083 }
6084 
6085 static void
6086 rack_adjust_orig_mlen(struct rack_sendmap *rsm)
6087 {
6088 	if (rsm->m->m_len > rsm->orig_m_len) {
6089 		/*
6090 		 * Mbuf grew, caused by sbcompress, our offset does
6091 		 * not change.
6092 		 */
6093 		rsm->orig_m_len = rsm->m->m_len;
6094 	} else if (rsm->m->m_len < rsm->orig_m_len) {
6095 		/*
6096 		 * Mbuf shrank, trimmed off the top by an ack, our
6097 		 * offset changes.
6098 		 */
6099 		rsm->soff -= (rsm->orig_m_len - rsm->m->m_len);
6100 		rsm->orig_m_len = rsm->m->m_len;
6101 	}
6102 }
6103 
6104 static void
6105 rack_setup_offset_for_rsm(struct rack_sendmap *src_rsm, struct rack_sendmap *rsm)
6106 {
6107 	struct mbuf *m;
6108 	uint32_t soff;
6109 
6110 	if (src_rsm->m && (src_rsm->orig_m_len != src_rsm->m->m_len)) {
6111 		/* Fix up the orig_m_len and possibly the mbuf offset */
6112 		rack_adjust_orig_mlen(src_rsm);
6113 	}
6114 	m = src_rsm->m;
6115 	soff = src_rsm->soff + (src_rsm->r_end - src_rsm->r_start);
6116 	while (soff >= m->m_len) {
6117 		/* Move out past this mbuf */
6118 		soff -= m->m_len;
6119 		m = m->m_next;
6120 		KASSERT((m != NULL),
6121 			("rsm:%p nrsm:%p hit at soff:%u null m",
6122 			 src_rsm, rsm, soff));
6123 	}
6124 	rsm->m = m;
6125 	rsm->soff = soff;
6126 	rsm->orig_m_len = m->m_len;
6127 }
6128 
6129 static __inline void
6130 rack_clone_rsm(struct tcp_rack *rack, struct rack_sendmap *nrsm,
6131 	       struct rack_sendmap *rsm, uint32_t start)
6132 {
6133 	int idx;
6134 
6135 	nrsm->r_start = start;
6136 	nrsm->r_end = rsm->r_end;
6137 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
6138 	nrsm->r_flags = rsm->r_flags;
6139 	nrsm->r_dupack = rsm->r_dupack;
6140 	nrsm->r_no_rtt_allowed = rsm->r_no_rtt_allowed;
6141 	nrsm->r_rtr_bytes = 0;
6142 	rsm->r_end = nrsm->r_start;
6143 	nrsm->r_just_ret = rsm->r_just_ret;
6144 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
6145 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
6146 	}
6147 	/* Now if we have SYN flag we keep it on the left edge */
6148 	if (nrsm->r_flags & RACK_HAS_SYN)
6149 		nrsm->r_flags &= ~RACK_HAS_SYN;
6150 	/* Now if we have a FIN flag we keep it on the right edge */
6151 	if (rsm->r_flags & RACK_HAS_FIN)
6152 		rsm->r_flags &= ~RACK_HAS_FIN;
6153 	/* Push bit must go to the right edge as well */
6154 	if (rsm->r_flags & RACK_HAD_PUSH)
6155 		rsm->r_flags &= ~RACK_HAD_PUSH;
6156 	/* Clone over the state of the hw_tls flag */
6157 	nrsm->r_hw_tls = rsm->r_hw_tls;
6158 	/*
6159 	 * Now we need to find nrsm's new location in the mbuf chain
6160 	 * we basically calculate a new offset, which is soff +
6161 	 * how much is left in original rsm. Then we walk out the mbuf
6162 	 * chain to find the righ postion, it may be the same mbuf
6163 	 * or maybe not.
6164 	 */
6165 	KASSERT(((rsm->m != NULL) ||
6166 		 (rsm->r_flags & (RACK_HAS_SYN|RACK_HAS_FIN))),
6167 		("rsm:%p nrsm:%p rack:%p -- rsm->m is NULL?", rsm, nrsm, rack));
6168 	if (rsm->m)
6169 		rack_setup_offset_for_rsm(rsm, nrsm);
6170 }
6171 
6172 static struct rack_sendmap *
6173 rack_merge_rsm(struct tcp_rack *rack,
6174 	       struct rack_sendmap *l_rsm,
6175 	       struct rack_sendmap *r_rsm)
6176 {
6177 	/*
6178 	 * We are merging two ack'd RSM's,
6179 	 * the l_rsm is on the left (lower seq
6180 	 * values) and the r_rsm is on the right
6181 	 * (higher seq value). The simplest way
6182 	 * to merge these is to move the right
6183 	 * one into the left. I don't think there
6184 	 * is any reason we need to try to find
6185 	 * the oldest (or last oldest retransmitted).
6186 	 */
6187 	struct rack_sendmap *rm;
6188 
6189 	rack_log_map_chg(rack->rc_tp, rack, NULL,
6190 			 l_rsm, r_rsm, MAP_MERGE, r_rsm->r_end, __LINE__);
6191 	l_rsm->r_end = r_rsm->r_end;
6192 	if (l_rsm->r_dupack < r_rsm->r_dupack)
6193 		l_rsm->r_dupack = r_rsm->r_dupack;
6194 	if (r_rsm->r_rtr_bytes)
6195 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
6196 	if (r_rsm->r_in_tmap) {
6197 		/* This really should not happen */
6198 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, r_rsm, r_tnext);
6199 		r_rsm->r_in_tmap = 0;
6200 	}
6201 
6202 	/* Now the flags */
6203 	if (r_rsm->r_flags & RACK_HAS_FIN)
6204 		l_rsm->r_flags |= RACK_HAS_FIN;
6205 	if (r_rsm->r_flags & RACK_TLP)
6206 		l_rsm->r_flags |= RACK_TLP;
6207 	if (r_rsm->r_flags & RACK_RWND_COLLAPSED)
6208 		l_rsm->r_flags |= RACK_RWND_COLLAPSED;
6209 	if ((r_rsm->r_flags & RACK_APP_LIMITED)  &&
6210 	    ((l_rsm->r_flags & RACK_APP_LIMITED) == 0)) {
6211 		/*
6212 		 * If both are app-limited then let the
6213 		 * free lower the count. If right is app
6214 		 * limited and left is not, transfer.
6215 		 */
6216 		l_rsm->r_flags |= RACK_APP_LIMITED;
6217 		r_rsm->r_flags &= ~RACK_APP_LIMITED;
6218 		if (r_rsm == rack->r_ctl.rc_first_appl)
6219 			rack->r_ctl.rc_first_appl = l_rsm;
6220 	}
6221 	rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, r_rsm);
6222 #ifdef INVARIANTS
6223 	if (rm != r_rsm) {
6224 		panic("removing head in rack:%p rsm:%p rm:%p",
6225 		      rack, r_rsm, rm);
6226 	}
6227 #endif
6228 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
6229 		/* Transfer the split limit to the map we free */
6230 		r_rsm->r_limit_type = l_rsm->r_limit_type;
6231 		l_rsm->r_limit_type = 0;
6232 	}
6233 	rack_free(rack, r_rsm);
6234 	return (l_rsm);
6235 }
6236 
6237 /*
6238  * TLP Timer, here we simply setup what segment we want to
6239  * have the TLP expire on, the normal rack_output() will then
6240  * send it out.
6241  *
6242  * We return 1, saying don't proceed with rack_output only
6243  * when all timers have been stopped (destroyed PCB?).
6244  */
6245 static int
6246 rack_timeout_tlp(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t *doing_tlp)
6247 {
6248 	/*
6249 	 * Tail Loss Probe.
6250 	 */
6251 	struct rack_sendmap *rsm = NULL;
6252 	struct rack_sendmap *insret;
6253 	struct socket *so;
6254 	uint32_t amm;
6255 	uint32_t out, avail;
6256 	int collapsed_win = 0;
6257 
6258 	if (tp->t_timers->tt_flags & TT_STOPPED) {
6259 		return (1);
6260 	}
6261 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
6262 		/* Its not time yet */
6263 		return (0);
6264 	}
6265 	if (ctf_progress_timeout_check(tp, true)) {
6266 		rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6267 		tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
6268 		return (1);
6269 	}
6270 	/*
6271 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
6272 	 * need to figure out how to force a full MSS segment out.
6273 	 */
6274 	rack_log_to_event(rack, RACK_TO_FRM_TLP, NULL);
6275 	rack->r_ctl.retran_during_recovery = 0;
6276 	rack->r_ctl.dsack_byte_cnt = 0;
6277 	counter_u64_add(rack_tlp_tot, 1);
6278 	if (rack->r_state && (rack->r_state != tp->t_state))
6279 		rack_set_state(tp, rack);
6280 	so = tp->t_inpcb->inp_socket;
6281 	avail = sbavail(&so->so_snd);
6282 	out = tp->snd_max - tp->snd_una;
6283 	if (out > tp->snd_wnd) {
6284 		/* special case, we need a retransmission */
6285 		collapsed_win = 1;
6286 		goto need_retran;
6287 	}
6288 	if (rack->r_ctl.dsack_persist && (rack->r_ctl.rc_tlp_cnt_out >= 1)) {
6289 		rack->r_ctl.dsack_persist--;
6290 		if (rack->r_ctl.num_dsack && (rack->r_ctl.dsack_persist == 0)) {
6291 			rack->r_ctl.num_dsack = 0;
6292 		}
6293 		rack_log_dsack_event(rack, 1, __LINE__, 0, 0);
6294 	}
6295 	if ((tp->t_flags & TF_GPUTINPROG) &&
6296 	    (rack->r_ctl.rc_tlp_cnt_out == 1)) {
6297 		/*
6298 		 * If this is the second in a row
6299 		 * TLP and we are doing a measurement
6300 		 * its time to abandon the measurement.
6301 		 * Something is likely broken on
6302 		 * the clients network and measuring a
6303 		 * broken network does us no good.
6304 		 */
6305 		tp->t_flags &= ~TF_GPUTINPROG;
6306 		rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
6307 					   rack->r_ctl.rc_gp_srtt /*flex1*/,
6308 					   tp->gput_seq,
6309 					   0, 0, 18, __LINE__, NULL, 0);
6310 	}
6311 	/*
6312 	 * Check our send oldest always settings, and if
6313 	 * there is an oldest to send jump to the need_retran.
6314 	 */
6315 	if (rack_always_send_oldest && (TAILQ_EMPTY(&rack->r_ctl.rc_tmap) == 0))
6316 		goto need_retran;
6317 
6318 	if (avail > out) {
6319 		/* New data is available */
6320 		amm = avail - out;
6321 		if (amm > ctf_fixed_maxseg(tp)) {
6322 			amm = ctf_fixed_maxseg(tp);
6323 			if ((amm + out) > tp->snd_wnd) {
6324 				/* We are rwnd limited */
6325 				goto need_retran;
6326 			}
6327 		} else if (amm < ctf_fixed_maxseg(tp)) {
6328 			/* not enough to fill a MTU */
6329 			goto need_retran;
6330 		}
6331 		if (IN_FASTRECOVERY(tp->t_flags)) {
6332 			/* Unlikely */
6333 			if (rack->rack_no_prr == 0) {
6334 				if (out + amm <= tp->snd_wnd) {
6335 					rack->r_ctl.rc_prr_sndcnt = amm;
6336 					rack->r_ctl.rc_tlp_new_data = amm;
6337 					rack_log_to_prr(rack, 4, 0);
6338 				}
6339 			} else
6340 				goto need_retran;
6341 		} else {
6342 			/* Set the send-new override */
6343 			if (out + amm <= tp->snd_wnd)
6344 				rack->r_ctl.rc_tlp_new_data = amm;
6345 			else
6346 				goto need_retran;
6347 		}
6348 		rack->r_ctl.rc_tlpsend = NULL;
6349 		counter_u64_add(rack_tlp_newdata, 1);
6350 		goto send;
6351 	}
6352 need_retran:
6353 	/*
6354 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
6355 	 * optionally the first un-acked segment.
6356 	 */
6357 	if (collapsed_win == 0) {
6358 		if (rack_always_send_oldest)
6359 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
6360 		else {
6361 			rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6362 			if (rsm && (rsm->r_flags & (RACK_ACKED | RACK_HAS_FIN))) {
6363 				rsm = rack_find_high_nonack(rack, rsm);
6364 			}
6365 		}
6366 		if (rsm == NULL) {
6367 			counter_u64_add(rack_tlp_does_nada, 1);
6368 #ifdef TCP_BLACKBOX
6369 			tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
6370 #endif
6371 			goto out;
6372 		}
6373 	} else {
6374 		/*
6375 		 * We must find the last segment
6376 		 * that was acceptable by the client.
6377 		 */
6378 		RB_FOREACH_REVERSE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
6379 			if ((rsm->r_flags & RACK_RWND_COLLAPSED) == 0) {
6380 				/* Found one */
6381 				break;
6382 			}
6383 		}
6384 		if (rsm == NULL) {
6385 			/* None? if so send the first */
6386 			rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6387 			if (rsm == NULL) {
6388 				counter_u64_add(rack_tlp_does_nada, 1);
6389 #ifdef TCP_BLACKBOX
6390 				tcp_log_dump_tp_logbuf(tp, "nada counter trips", M_NOWAIT, true);
6391 #endif
6392 				goto out;
6393 			}
6394 		}
6395 	}
6396 	if ((rsm->r_end - rsm->r_start) > ctf_fixed_maxseg(tp)) {
6397 		/*
6398 		 * We need to split this the last segment in two.
6399 		 */
6400 		struct rack_sendmap *nrsm;
6401 
6402 		nrsm = rack_alloc_full_limit(rack);
6403 		if (nrsm == NULL) {
6404 			/*
6405 			 * No memory to split, we will just exit and punt
6406 			 * off to the RXT timer.
6407 			 */
6408 			counter_u64_add(rack_tlp_does_nada, 1);
6409 			goto out;
6410 		}
6411 		rack_clone_rsm(rack, nrsm, rsm,
6412 			       (rsm->r_end - ctf_fixed_maxseg(tp)));
6413 		rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
6414 		insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
6415 #ifdef INVARIANTS
6416 		if (insret != NULL) {
6417 			panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
6418 			      nrsm, insret, rack, rsm);
6419 		}
6420 #endif
6421 		if (rsm->r_in_tmap) {
6422 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6423 			nrsm->r_in_tmap = 1;
6424 		}
6425 		rsm = nrsm;
6426 	}
6427 	rack->r_ctl.rc_tlpsend = rsm;
6428 send:
6429 	/* Make sure output path knows we are doing a TLP */
6430 	*doing_tlp = 1;
6431 	rack->r_timer_override = 1;
6432 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
6433 	return (0);
6434 out:
6435 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
6436 	return (0);
6437 }
6438 
6439 /*
6440  * Delayed ack Timer, here we simply need to setup the
6441  * ACK_NOW flag and remove the DELACK flag. From there
6442  * the output routine will send the ack out.
6443  *
6444  * We only return 1, saying don't proceed, if all timers
6445  * are stopped (destroyed PCB?).
6446  */
6447 static int
6448 rack_timeout_delack(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6449 {
6450 	if (tp->t_timers->tt_flags & TT_STOPPED) {
6451 		return (1);
6452 	}
6453 	rack_log_to_event(rack, RACK_TO_FRM_DELACK, NULL);
6454 	tp->t_flags &= ~TF_DELACK;
6455 	tp->t_flags |= TF_ACKNOW;
6456 	KMOD_TCPSTAT_INC(tcps_delack);
6457 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
6458 	return (0);
6459 }
6460 
6461 /*
6462  * Persists timer, here we simply send the
6463  * same thing as a keepalive will.
6464  * the one byte send.
6465  *
6466  * We only return 1, saying don't proceed, if all timers
6467  * are stopped (destroyed PCB?).
6468  */
6469 static int
6470 rack_timeout_persist(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6471 {
6472 	struct tcptemp *t_template;
6473 	struct inpcb *inp;
6474 	int32_t retval = 1;
6475 
6476 	inp = tp->t_inpcb;
6477 
6478 	if (tp->t_timers->tt_flags & TT_STOPPED) {
6479 		return (1);
6480 	}
6481 	if (rack->rc_in_persist == 0)
6482 		return (0);
6483 	if (ctf_progress_timeout_check(tp, false)) {
6484 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6485 		rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6486 		tcp_set_inp_to_drop(inp, ETIMEDOUT);
6487 		return (1);
6488 	}
6489 	KASSERT(inp != NULL, ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
6490 	/*
6491 	 * Persistence timer into zero window. Force a byte to be output, if
6492 	 * possible.
6493 	 */
6494 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
6495 	/*
6496 	 * Hack: if the peer is dead/unreachable, we do not time out if the
6497 	 * window is closed.  After a full backoff, drop the connection if
6498 	 * the idle time (no responses to probes) reaches the maximum
6499 	 * backoff that we would use if retransmitting.
6500 	 */
6501 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
6502 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
6503 	     TICKS_2_USEC(ticks - tp->t_rcvtime) >= RACK_REXMTVAL(tp) * tcp_totbackoff)) {
6504 		KMOD_TCPSTAT_INC(tcps_persistdrop);
6505 		retval = 1;
6506 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6507 		tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
6508 		goto out;
6509 	}
6510 	if ((sbavail(&rack->rc_inp->inp_socket->so_snd) == 0) &&
6511 	    tp->snd_una == tp->snd_max)
6512 		rack_exit_persist(tp, rack, cts);
6513 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
6514 	/*
6515 	 * If the user has closed the socket then drop a persisting
6516 	 * connection after a much reduced timeout.
6517 	 */
6518 	if (tp->t_state > TCPS_CLOSE_WAIT &&
6519 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
6520 		retval = 1;
6521 		KMOD_TCPSTAT_INC(tcps_persistdrop);
6522 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
6523 		tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
6524 		goto out;
6525 	}
6526 	t_template = tcpip_maketemplate(rack->rc_inp);
6527 	if (t_template) {
6528 		/* only set it if we were answered */
6529 		if (rack->forced_ack == 0) {
6530 			rack->forced_ack = 1;
6531 			rack->r_ctl.forced_ack_ts = tcp_get_usecs(NULL);
6532 		}
6533 		tcp_respond(tp, t_template->tt_ipgen,
6534 			    &t_template->tt_t, (struct mbuf *)NULL,
6535 			    tp->rcv_nxt, tp->snd_una - 1, 0);
6536 		/* This sends an ack */
6537 		if (tp->t_flags & TF_DELACK)
6538 			tp->t_flags &= ~TF_DELACK;
6539 		free(t_template, M_TEMP);
6540 	}
6541 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
6542 		tp->t_rxtshift++;
6543 out:
6544 	rack_log_to_event(rack, RACK_TO_FRM_PERSIST, NULL);
6545 	rack_start_hpts_timer(rack, tp, cts,
6546 			      0, 0, 0);
6547 	return (retval);
6548 }
6549 
6550 /*
6551  * If a keepalive goes off, we had no other timers
6552  * happening. We always return 1 here since this
6553  * routine either drops the connection or sends
6554  * out a segment with respond.
6555  */
6556 static int
6557 rack_timeout_keepalive(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6558 {
6559 	struct tcptemp *t_template;
6560 	struct inpcb *inp;
6561 
6562 	if (tp->t_timers->tt_flags & TT_STOPPED) {
6563 		return (1);
6564 	}
6565 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
6566 	inp = tp->t_inpcb;
6567 	rack_log_to_event(rack, RACK_TO_FRM_KEEP, NULL);
6568 	/*
6569 	 * Keep-alive timer went off; send something or drop connection if
6570 	 * idle for too long.
6571 	 */
6572 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
6573 	if (tp->t_state < TCPS_ESTABLISHED)
6574 		goto dropit;
6575 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
6576 	    tp->t_state <= TCPS_CLOSING) {
6577 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
6578 			goto dropit;
6579 		/*
6580 		 * Send a packet designed to force a response if the peer is
6581 		 * up and reachable: either an ACK if the connection is
6582 		 * still alive, or an RST if the peer has closed the
6583 		 * connection due to timeout or reboot. Using sequence
6584 		 * number tp->snd_una-1 causes the transmitted zero-length
6585 		 * segment to lie outside the receive window; by the
6586 		 * protocol spec, this requires the correspondent TCP to
6587 		 * respond.
6588 		 */
6589 		KMOD_TCPSTAT_INC(tcps_keepprobe);
6590 		t_template = tcpip_maketemplate(inp);
6591 		if (t_template) {
6592 			if (rack->forced_ack == 0) {
6593 				rack->forced_ack = 1;
6594 				rack->r_ctl.forced_ack_ts = tcp_get_usecs(NULL);
6595 			}
6596 			tcp_respond(tp, t_template->tt_ipgen,
6597 			    &t_template->tt_t, (struct mbuf *)NULL,
6598 			    tp->rcv_nxt, tp->snd_una - 1, 0);
6599 			free(t_template, M_TEMP);
6600 		}
6601 	}
6602 	rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
6603 	return (1);
6604 dropit:
6605 	KMOD_TCPSTAT_INC(tcps_keepdrops);
6606 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
6607 	tcp_set_inp_to_drop(rack->rc_inp, ETIMEDOUT);
6608 	return (1);
6609 }
6610 
6611 /*
6612  * Retransmit helper function, clear up all the ack
6613  * flags and take care of important book keeping.
6614  */
6615 static void
6616 rack_remxt_tmr(struct tcpcb *tp)
6617 {
6618 	/*
6619 	 * The retransmit timer went off, all sack'd blocks must be
6620 	 * un-acked.
6621 	 */
6622 	struct rack_sendmap *rsm, *trsm = NULL;
6623 	struct tcp_rack *rack;
6624 
6625 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6626 	rack_timer_cancel(tp, rack, tcp_get_usecs(NULL), __LINE__);
6627 	rack_log_to_event(rack, RACK_TO_FRM_TMR, NULL);
6628 	if (rack->r_state && (rack->r_state != tp->t_state))
6629 		rack_set_state(tp, rack);
6630 	/*
6631 	 * Ideally we would like to be able to
6632 	 * mark SACK-PASS on anything not acked here.
6633 	 *
6634 	 * However, if we do that we would burst out
6635 	 * all that data 1ms apart. This would be unwise,
6636 	 * so for now we will just let the normal rxt timer
6637 	 * and tlp timer take care of it.
6638 	 *
6639 	 * Also we really need to stick them back in sequence
6640 	 * order. This way we send in the proper order and any
6641 	 * sacks that come floating in will "re-ack" the data.
6642 	 * To do this we zap the tmap with an INIT and then
6643 	 * walk through and place every rsm in the RB tree
6644 	 * back in its seq ordered place.
6645 	 */
6646 	TAILQ_INIT(&rack->r_ctl.rc_tmap);
6647 	RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
6648 		rsm->r_dupack = 0;
6649 		rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
6650 		/* We must re-add it back to the tlist */
6651 		if (trsm == NULL) {
6652 			TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
6653 		} else {
6654 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, trsm, rsm, r_tnext);
6655 		}
6656 		rsm->r_in_tmap = 1;
6657 		trsm = rsm;
6658 		if (rsm->r_flags & RACK_ACKED)
6659 			rsm->r_flags |= RACK_WAS_ACKED;
6660 		rsm->r_flags &= ~(RACK_ACKED | RACK_SACK_PASSED | RACK_WAS_SACKPASS);
6661 	}
6662 	/* Clear the count (we just un-acked them) */
6663 	rack->r_ctl.rc_last_timeout_snduna = tp->snd_una;
6664 	rack->r_ctl.rc_sacked = 0;
6665 	rack->r_ctl.rc_sacklast = NULL;
6666 	rack->r_ctl.rc_agg_delayed = 0;
6667 	rack->r_early = 0;
6668 	rack->r_ctl.rc_agg_early = 0;
6669 	rack->r_late = 0;
6670 	/* Clear the tlp rtx mark */
6671 	rack->r_ctl.rc_resend = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6672 	if (rack->r_ctl.rc_resend != NULL)
6673 		rack->r_ctl.rc_resend->r_flags |= RACK_TO_REXT;
6674 	rack->r_ctl.rc_prr_sndcnt = 0;
6675 	rack_log_to_prr(rack, 6, 0);
6676 	rack->r_timer_override = 1;
6677 	if ((((tp->t_flags & TF_SACK_PERMIT) == 0)
6678 #ifdef NETFLIX_EXP_DETECTION
6679 	    || (rack->sack_attack_disable != 0)
6680 #endif
6681 		    ) && ((tp->t_flags & TF_SENTFIN) == 0)) {
6682 		/*
6683 		 * For non-sack customers new data
6684 		 * needs to go out as retransmits until
6685 		 * we retransmit up to snd_max.
6686 		 */
6687 		rack->r_must_retran = 1;
6688 		rack->r_ctl.rc_out_at_rto = ctf_flight_size(rack->rc_tp,
6689 						rack->r_ctl.rc_sacked);
6690 	}
6691 	rack->r_ctl.rc_snd_max_at_rto = tp->snd_max;
6692 }
6693 
6694 static void
6695 rack_convert_rtts(struct tcpcb *tp)
6696 {
6697 	if (tp->t_srtt > 1) {
6698 		uint32_t val, frac;
6699 
6700 		val = tp->t_srtt >> TCP_RTT_SHIFT;
6701 		frac = tp->t_srtt & 0x1f;
6702 		tp->t_srtt = TICKS_2_USEC(val);
6703 		/*
6704 		 * frac is the fractional part of the srtt (if any)
6705 		 * but its in ticks and every bit represents
6706 		 * 1/32nd of a hz.
6707 		 */
6708 		if (frac) {
6709 			if (hz == 1000) {
6710 				frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
6711 			} else {
6712 				frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
6713 			}
6714 			tp->t_srtt += frac;
6715 		}
6716 	}
6717 	if (tp->t_rttvar) {
6718 		uint32_t val, frac;
6719 
6720 		val = tp->t_rttvar >> TCP_RTTVAR_SHIFT;
6721 		frac = tp->t_rttvar & 0x1f;
6722 		tp->t_rttvar = TICKS_2_USEC(val);
6723 		/*
6724 		 * frac is the fractional part of the srtt (if any)
6725 		 * but its in ticks and every bit represents
6726 		 * 1/32nd of a hz.
6727 		 */
6728 		if (frac) {
6729 			if (hz == 1000) {
6730 				frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_MSEC) / (uint64_t)TCP_RTT_SCALE);
6731 			} else {
6732 				frac = (((uint64_t)frac * (uint64_t)HPTS_USEC_IN_SEC) / ((uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE));
6733 			}
6734 			tp->t_rttvar += frac;
6735 		}
6736 	}
6737 	tp->t_rxtcur = RACK_REXMTVAL(tp);
6738 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
6739 		tp->t_rxtcur += TICKS_2_USEC(tcp_rexmit_slop);
6740 	}
6741 	if (tp->t_rxtcur > rack_rto_max) {
6742 		tp->t_rxtcur = rack_rto_max;
6743 	}
6744 }
6745 
6746 static void
6747 rack_cc_conn_init(struct tcpcb *tp)
6748 {
6749 	struct tcp_rack *rack;
6750 	uint32_t srtt;
6751 
6752 	rack = (struct tcp_rack *)tp->t_fb_ptr;
6753 	srtt = tp->t_srtt;
6754 	cc_conn_init(tp);
6755 	/*
6756 	 * Now convert to rack's internal format,
6757 	 * if required.
6758 	 */
6759 	if ((srtt == 0) && (tp->t_srtt != 0))
6760 		rack_convert_rtts(tp);
6761 	/*
6762 	 * We want a chance to stay in slowstart as
6763 	 * we create a connection. TCP spec says that
6764 	 * initially ssthresh is infinite. For our
6765 	 * purposes that is the snd_wnd.
6766 	 */
6767 	if (tp->snd_ssthresh < tp->snd_wnd) {
6768 		tp->snd_ssthresh = tp->snd_wnd;
6769 	}
6770 	/*
6771 	 * We also want to assure a IW worth of
6772 	 * data can get inflight.
6773 	 */
6774 	if (rc_init_window(rack) < tp->snd_cwnd)
6775 		tp->snd_cwnd = rc_init_window(rack);
6776 }
6777 
6778 /*
6779  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
6780  * we will setup to retransmit the lowest seq number outstanding.
6781  */
6782 static int
6783 rack_timeout_rxt(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts)
6784 {
6785 	int32_t rexmt;
6786 	struct inpcb *inp;
6787 	int32_t retval = 0;
6788 	bool isipv6;
6789 
6790 	inp = tp->t_inpcb;
6791 	if (tp->t_timers->tt_flags & TT_STOPPED) {
6792 		return (1);
6793 	}
6794 	if ((tp->t_flags & TF_GPUTINPROG) &&
6795 	    (tp->t_rxtshift)) {
6796 		/*
6797 		 * We have had a second timeout
6798 		 * measurements on successive rxt's are not profitable.
6799 		 * It is unlikely to be of any use (the network is
6800 		 * broken or the client went away).
6801 		 */
6802 		tp->t_flags &= ~TF_GPUTINPROG;
6803 		rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
6804 					   rack->r_ctl.rc_gp_srtt /*flex1*/,
6805 					   tp->gput_seq,
6806 					   0, 0, 18, __LINE__, NULL, 0);
6807 	}
6808 	if (ctf_progress_timeout_check(tp, false)) {
6809 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
6810 		rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
6811 		tcp_set_inp_to_drop(inp, ETIMEDOUT);
6812 		return (1);
6813 	}
6814 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
6815 	rack->r_ctl.retran_during_recovery = 0;
6816 	rack->r_ctl.dsack_byte_cnt = 0;
6817 	if (IN_FASTRECOVERY(tp->t_flags))
6818 		tp->t_flags |= TF_WASFRECOVERY;
6819 	else
6820 		tp->t_flags &= ~TF_WASFRECOVERY;
6821 	if (IN_CONGRECOVERY(tp->t_flags))
6822 		tp->t_flags |= TF_WASCRECOVERY;
6823 	else
6824 		tp->t_flags &= ~TF_WASCRECOVERY;
6825 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
6826 	    (tp->snd_una == tp->snd_max)) {
6827 		/* Nothing outstanding .. nothing to do */
6828 		return (0);
6829 	}
6830 	if (rack->r_ctl.dsack_persist) {
6831 		rack->r_ctl.dsack_persist--;
6832 		if (rack->r_ctl.num_dsack && (rack->r_ctl.dsack_persist == 0)) {
6833 			rack->r_ctl.num_dsack = 0;
6834 		}
6835 		rack_log_dsack_event(rack, 1, __LINE__, 0, 0);
6836 	}
6837 	/*
6838 	 * Rack can only run one timer  at a time, so we cannot
6839 	 * run a KEEPINIT (gating SYN sending) and a retransmit
6840 	 * timer for the SYN. So if we are in a front state and
6841 	 * have a KEEPINIT timer we need to check the first transmit
6842 	 * against now to see if we have exceeded the KEEPINIT time
6843 	 * (if one is set).
6844 	 */
6845 	if ((TCPS_HAVEESTABLISHED(tp->t_state) == 0) &&
6846 	    (TP_KEEPINIT(tp) != 0)) {
6847 		struct rack_sendmap *rsm;
6848 
6849 		rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
6850 		if (rsm) {
6851 			/* Ok we have something outstanding to test keepinit with */
6852 			if ((TSTMP_GT(cts, (uint32_t)rsm->r_tim_lastsent[0])) &&
6853 			    ((cts - (uint32_t)rsm->r_tim_lastsent[0]) >= TICKS_2_USEC(TP_KEEPINIT(tp)))) {
6854 				/* We have exceeded the KEEPINIT time */
6855 				tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
6856 				goto drop_it;
6857 			}
6858 		}
6859 	}
6860 	/*
6861 	 * Retransmission timer went off.  Message has not been acked within
6862 	 * retransmit interval.  Back off to a longer retransmit interval
6863 	 * and retransmit one segment.
6864 	 */
6865 	rack_remxt_tmr(tp);
6866 	if ((rack->r_ctl.rc_resend == NULL) ||
6867 	    ((rack->r_ctl.rc_resend->r_flags & RACK_RWND_COLLAPSED) == 0)) {
6868 		/*
6869 		 * If the rwnd collapsed on
6870 		 * the one we are retransmitting
6871 		 * it does not count against the
6872 		 * rxt count.
6873 		 */
6874 		tp->t_rxtshift++;
6875 	}
6876 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
6877 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
6878 drop_it:
6879 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
6880 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
6881 		retval = 1;
6882 		tcp_set_inp_to_drop(rack->rc_inp,
6883 		    (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
6884 		goto out;
6885 	}
6886 	if (tp->t_state == TCPS_SYN_SENT) {
6887 		/*
6888 		 * If the SYN was retransmitted, indicate CWND to be limited
6889 		 * to 1 segment in cc_conn_init().
6890 		 */
6891 		tp->snd_cwnd = 1;
6892 	} else if (tp->t_rxtshift == 1) {
6893 		/*
6894 		 * first retransmit; record ssthresh and cwnd so they can be
6895 		 * recovered if this turns out to be a "bad" retransmit. A
6896 		 * retransmit is considered "bad" if an ACK for this segment
6897 		 * is received within RTT/2 interval; the assumption here is
6898 		 * that the ACK was already in flight.  See "On Estimating
6899 		 * End-to-End Network Path Properties" by Allman and Paxson
6900 		 * for more details.
6901 		 */
6902 		tp->snd_cwnd_prev = tp->snd_cwnd;
6903 		tp->snd_ssthresh_prev = tp->snd_ssthresh;
6904 		tp->snd_recover_prev = tp->snd_recover;
6905 		tp->t_badrxtwin = ticks + (USEC_2_TICKS(tp->t_srtt)/2);
6906 		tp->t_flags |= TF_PREVVALID;
6907 	} else if ((tp->t_flags & TF_RCVD_TSTMP) == 0)
6908 		tp->t_flags &= ~TF_PREVVALID;
6909 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
6910 	if ((tp->t_state == TCPS_SYN_SENT) ||
6911 	    (tp->t_state == TCPS_SYN_RECEIVED))
6912 		rexmt = RACK_INITIAL_RTO * tcp_backoff[tp->t_rxtshift];
6913 	else
6914 		rexmt = max(rack_rto_min, (tp->t_srtt + (tp->t_rttvar << 2))) * tcp_backoff[tp->t_rxtshift];
6915 
6916 	RACK_TCPT_RANGESET(tp->t_rxtcur, rexmt,
6917 	   max(rack_rto_min, rexmt), rack_rto_max, rack->r_ctl.timer_slop);
6918 	/*
6919 	 * We enter the path for PLMTUD if connection is established or, if
6920 	 * connection is FIN_WAIT_1 status, reason for the last is that if
6921 	 * amount of data we send is very small, we could send it in couple
6922 	 * of packets and process straight to FIN. In that case we won't
6923 	 * catch ESTABLISHED state.
6924 	 */
6925 #ifdef INET6
6926 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
6927 #else
6928 	isipv6 = false;
6929 #endif
6930 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
6931 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
6932 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
6933 	    ((tp->t_state == TCPS_ESTABLISHED) ||
6934 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
6935 		/*
6936 		 * Idea here is that at each stage of mtu probe (usually,
6937 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
6938 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
6939 		 * should take care of that.
6940 		 */
6941 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
6942 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
6943 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
6944 		    tp->t_rxtshift % 2 == 0)) {
6945 			/*
6946 			 * Enter Path MTU Black-hole Detection mechanism: -
6947 			 * Disable Path MTU Discovery (IP "DF" bit). -
6948 			 * Reduce MTU to lower value than what we negotiated
6949 			 * with peer.
6950 			 */
6951 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
6952 				/* Record that we may have found a black hole. */
6953 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
6954 				/* Keep track of previous MSS. */
6955 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
6956 			}
6957 
6958 			/*
6959 			 * Reduce the MSS to blackhole value or to the
6960 			 * default in an attempt to retransmit.
6961 			 */
6962 #ifdef INET6
6963 			if (isipv6 &&
6964 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
6965 				/* Use the sysctl tuneable blackhole MSS. */
6966 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
6967 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
6968 			} else if (isipv6) {
6969 				/* Use the default MSS. */
6970 				tp->t_maxseg = V_tcp_v6mssdflt;
6971 				/*
6972 				 * Disable Path MTU Discovery when we switch
6973 				 * to minmss.
6974 				 */
6975 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
6976 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
6977 			}
6978 #endif
6979 #if defined(INET6) && defined(INET)
6980 			else
6981 #endif
6982 #ifdef INET
6983 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
6984 				/* Use the sysctl tuneable blackhole MSS. */
6985 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
6986 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
6987 			} else {
6988 				/* Use the default MSS. */
6989 				tp->t_maxseg = V_tcp_mssdflt;
6990 				/*
6991 				 * Disable Path MTU Discovery when we switch
6992 				 * to minmss.
6993 				 */
6994 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
6995 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
6996 			}
6997 #endif
6998 		} else {
6999 			/*
7000 			 * If further retransmissions are still unsuccessful
7001 			 * with a lowered MTU, maybe this isn't a blackhole
7002 			 * and we restore the previous MSS and blackhole
7003 			 * detection flags. The limit '6' is determined by
7004 			 * giving each probe stage (1448, 1188, 524) 2
7005 			 * chances to recover.
7006 			 */
7007 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
7008 			    (tp->t_rxtshift >= 6)) {
7009 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
7010 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
7011 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
7012 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
7013 			}
7014 		}
7015 	}
7016 	/*
7017 	 * Disable RFC1323 and SACK if we haven't got any response to
7018 	 * our third SYN to work-around some broken terminal servers
7019 	 * (most of which have hopefully been retired) that have bad VJ
7020 	 * header compression code which trashes TCP segments containing
7021 	 * unknown-to-them TCP options.
7022 	 */
7023 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
7024 	    (tp->t_rxtshift == 3))
7025 		tp->t_flags &= ~(TF_REQ_SCALE|TF_REQ_TSTMP|TF_SACK_PERMIT);
7026 	/*
7027 	 * If we backed off this far, our srtt estimate is probably bogus.
7028 	 * Clobber it so we'll take the next rtt measurement as our srtt;
7029 	 * move the current srtt into rttvar to keep the current retransmit
7030 	 * times until then.
7031 	 */
7032 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
7033 #ifdef INET6
7034 		if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
7035 			in6_losing(tp->t_inpcb);
7036 		else
7037 #endif
7038 			in_losing(tp->t_inpcb);
7039 		tp->t_rttvar += tp->t_srtt;
7040 		tp->t_srtt = 0;
7041 	}
7042 	sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
7043 	tp->snd_recover = tp->snd_max;
7044 	tp->t_flags |= TF_ACKNOW;
7045 	tp->t_rtttime = 0;
7046 	rack_cong_signal(tp, CC_RTO, tp->snd_una);
7047 out:
7048 	return (retval);
7049 }
7050 
7051 static int
7052 rack_process_timers(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, uint8_t hpts_calling, uint8_t *doing_tlp)
7053 {
7054 	int32_t ret = 0;
7055 	int32_t timers = (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
7056 
7057 	if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7058 	    (tp->t_flags & TF_GPUTINPROG)) {
7059 		/*
7060 		 * We have a goodput in progress
7061 		 * and we have entered a late state.
7062 		 * Do we have enough data in the sb
7063 		 * to handle the GPUT request?
7064 		 */
7065 		uint32_t bytes;
7066 
7067 		bytes = tp->gput_ack - tp->gput_seq;
7068 		if (SEQ_GT(tp->gput_seq, tp->snd_una))
7069 			bytes += tp->gput_seq - tp->snd_una;
7070 		if (bytes > sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
7071 			/*
7072 			 * There are not enough bytes in the socket
7073 			 * buffer that have been sent to cover this
7074 			 * measurement. Cancel it.
7075 			 */
7076 			rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
7077 						   rack->r_ctl.rc_gp_srtt /*flex1*/,
7078 						   tp->gput_seq,
7079 						   0, 0, 18, __LINE__, NULL, 0);
7080 			tp->t_flags &= ~TF_GPUTINPROG;
7081 		}
7082 	}
7083 	if (timers == 0) {
7084 		return (0);
7085 	}
7086 	if (tp->t_state == TCPS_LISTEN) {
7087 		/* no timers on listen sockets */
7088 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
7089 			return (0);
7090 		return (1);
7091 	}
7092 	if ((timers & PACE_TMR_RACK) &&
7093 	    rack->rc_on_min_to) {
7094 		/*
7095 		 * For the rack timer when we
7096 		 * are on a min-timeout (which means rrr_conf = 3)
7097 		 * we don't want to check the timer. It may
7098 		 * be going off for a pace and thats ok we
7099 		 * want to send the retransmit (if its ready).
7100 		 *
7101 		 * If its on a normal rack timer (non-min) then
7102 		 * we will check if its expired.
7103 		 */
7104 		goto skip_time_check;
7105 	}
7106 	if (TSTMP_LT(cts, rack->r_ctl.rc_timer_exp)) {
7107 		uint32_t left;
7108 
7109 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
7110 			ret = -1;
7111 			rack_log_to_processing(rack, cts, ret, 0);
7112 			return (0);
7113 		}
7114 		if (hpts_calling == 0) {
7115 			/*
7116 			 * A user send or queued mbuf (sack) has called us? We
7117 			 * return 0 and let the pacing guards
7118 			 * deal with it if they should or
7119 			 * should not cause a send.
7120 			 */
7121 			ret = -2;
7122 			rack_log_to_processing(rack, cts, ret, 0);
7123 			return (0);
7124 		}
7125 		/*
7126 		 * Ok our timer went off early and we are not paced false
7127 		 * alarm, go back to sleep.
7128 		 */
7129 		ret = -3;
7130 		left = rack->r_ctl.rc_timer_exp - cts;
7131 		tcp_hpts_insert(tp->t_inpcb, HPTS_MS_TO_SLOTS(left));
7132 		rack_log_to_processing(rack, cts, ret, left);
7133 		return (1);
7134 	}
7135 skip_time_check:
7136 	rack->rc_tmr_stopped = 0;
7137 	rack->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
7138 	if (timers & PACE_TMR_DELACK) {
7139 		ret = rack_timeout_delack(tp, rack, cts);
7140 	} else if (timers & PACE_TMR_RACK) {
7141 		rack->r_ctl.rc_tlp_rxt_last_time = cts;
7142 		rack->r_fast_output = 0;
7143 		ret = rack_timeout_rack(tp, rack, cts);
7144 	} else if (timers & PACE_TMR_TLP) {
7145 		rack->r_ctl.rc_tlp_rxt_last_time = cts;
7146 		ret = rack_timeout_tlp(tp, rack, cts, doing_tlp);
7147 	} else if (timers & PACE_TMR_RXT) {
7148 		rack->r_ctl.rc_tlp_rxt_last_time = cts;
7149 		rack->r_fast_output = 0;
7150 		ret = rack_timeout_rxt(tp, rack, cts);
7151 	} else if (timers & PACE_TMR_PERSIT) {
7152 		ret = rack_timeout_persist(tp, rack, cts);
7153 	} else if (timers & PACE_TMR_KEEP) {
7154 		ret = rack_timeout_keepalive(tp, rack, cts);
7155 	}
7156 	rack_log_to_processing(rack, cts, ret, timers);
7157 	return (ret);
7158 }
7159 
7160 static void
7161 rack_timer_cancel(struct tcpcb *tp, struct tcp_rack *rack, uint32_t cts, int line)
7162 {
7163 	struct timeval tv;
7164 	uint32_t us_cts, flags_on_entry;
7165 	uint8_t hpts_removed = 0;
7166 
7167 	flags_on_entry = rack->r_ctl.rc_hpts_flags;
7168 	us_cts = tcp_get_usecs(&tv);
7169 	if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
7170 	    ((TSTMP_GEQ(us_cts, rack->r_ctl.rc_last_output_to)) ||
7171 	     ((tp->snd_max - tp->snd_una) == 0))) {
7172 		tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
7173 		hpts_removed = 1;
7174 		/* If we were not delayed cancel out the flag. */
7175 		if ((tp->snd_max - tp->snd_una) == 0)
7176 			rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
7177 		rack_log_to_cancel(rack, hpts_removed, line, us_cts, &tv, flags_on_entry);
7178 	}
7179 	if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
7180 		rack->rc_tmr_stopped = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
7181 		if (rack->rc_inp->inp_in_hpts &&
7182 		    ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)) {
7183 			/*
7184 			 * Canceling timer's when we have no output being
7185 			 * paced. We also must remove ourselves from the
7186 			 * hpts.
7187 			 */
7188 			tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
7189 			hpts_removed = 1;
7190 		}
7191 		rack->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
7192 	}
7193 	if (hpts_removed == 0)
7194 		rack_log_to_cancel(rack, hpts_removed, line, us_cts, &tv, flags_on_entry);
7195 }
7196 
7197 static void
7198 rack_timer_stop(struct tcpcb *tp, uint32_t timer_type)
7199 {
7200 	return;
7201 }
7202 
7203 static int
7204 rack_stopall(struct tcpcb *tp)
7205 {
7206 	struct tcp_rack *rack;
7207 	rack = (struct tcp_rack *)tp->t_fb_ptr;
7208 	rack->t_timers_stopped = 1;
7209 	return (0);
7210 }
7211 
7212 static void
7213 rack_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
7214 {
7215 	return;
7216 }
7217 
7218 static int
7219 rack_timer_active(struct tcpcb *tp, uint32_t timer_type)
7220 {
7221 	return (0);
7222 }
7223 
7224 static void
7225 rack_stop_all_timers(struct tcpcb *tp)
7226 {
7227 	struct tcp_rack *rack;
7228 
7229 	/*
7230 	 * Assure no timers are running.
7231 	 */
7232 	if (tcp_timer_active(tp, TT_PERSIST)) {
7233 		/* We enter in persists, set the flag appropriately */
7234 		rack = (struct tcp_rack *)tp->t_fb_ptr;
7235 		rack->rc_in_persist = 1;
7236 	}
7237 	tcp_timer_suspend(tp, TT_PERSIST);
7238 	tcp_timer_suspend(tp, TT_REXMT);
7239 	tcp_timer_suspend(tp, TT_KEEP);
7240 	tcp_timer_suspend(tp, TT_DELACK);
7241 }
7242 
7243 static void
7244 rack_update_rsm(struct tcpcb *tp, struct tcp_rack *rack,
7245     struct rack_sendmap *rsm, uint64_t ts, uint16_t add_flag)
7246 {
7247 	int32_t idx;
7248 	uint16_t stripped_flags;
7249 
7250 	rsm->r_rtr_cnt++;
7251 	rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
7252 	rsm->r_dupack = 0;
7253 	if (rsm->r_rtr_cnt > RACK_NUM_OF_RETRANS) {
7254 		rsm->r_rtr_cnt = RACK_NUM_OF_RETRANS;
7255 		rsm->r_flags |= RACK_OVERMAX;
7256 	}
7257 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & RACK_TLP) == 0)) {
7258 		rack->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
7259 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
7260 	}
7261 	idx = rsm->r_rtr_cnt - 1;
7262 	rsm->r_tim_lastsent[idx] = ts;
7263 	stripped_flags = rsm->r_flags & ~(RACK_SENT_SP|RACK_SENT_FP);
7264 	if (rsm->r_flags & RACK_ACKED) {
7265 		/* Problably MTU discovery messing with us */
7266 		rsm->r_flags &= ~RACK_ACKED;
7267 		rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7268 	}
7269 	if (rsm->r_in_tmap) {
7270 		TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7271 		rsm->r_in_tmap = 0;
7272 	}
7273 	TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7274 	rsm->r_in_tmap = 1;
7275 	if (rsm->r_flags & RACK_SACK_PASSED) {
7276 		/* We have retransmitted due to the SACK pass */
7277 		rsm->r_flags &= ~RACK_SACK_PASSED;
7278 		rsm->r_flags |= RACK_WAS_SACKPASS;
7279 	}
7280 }
7281 
7282 static uint32_t
7283 rack_update_entry(struct tcpcb *tp, struct tcp_rack *rack,
7284     struct rack_sendmap *rsm, uint64_t ts, int32_t *lenp, uint16_t add_flag)
7285 {
7286 	/*
7287 	 * We (re-)transmitted starting at rsm->r_start for some length
7288 	 * (possibly less than r_end.
7289 	 */
7290 	struct rack_sendmap *nrsm, *insret;
7291 	uint32_t c_end;
7292 	int32_t len;
7293 
7294 	len = *lenp;
7295 	c_end = rsm->r_start + len;
7296 	if (SEQ_GEQ(c_end, rsm->r_end)) {
7297 		/*
7298 		 * We retransmitted the whole piece or more than the whole
7299 		 * slopping into the next rsm.
7300 		 */
7301 		rack_update_rsm(tp, rack, rsm, ts, add_flag);
7302 		if (c_end == rsm->r_end) {
7303 			*lenp = 0;
7304 			return (0);
7305 		} else {
7306 			int32_t act_len;
7307 
7308 			/* Hangs over the end return whats left */
7309 			act_len = rsm->r_end - rsm->r_start;
7310 			*lenp = (len - act_len);
7311 			return (rsm->r_end);
7312 		}
7313 		/* We don't get out of this block. */
7314 	}
7315 	/*
7316 	 * Here we retransmitted less than the whole thing which means we
7317 	 * have to split this into what was transmitted and what was not.
7318 	 */
7319 	nrsm = rack_alloc_full_limit(rack);
7320 	if (nrsm == NULL) {
7321 		/*
7322 		 * We can't get memory, so lets not proceed.
7323 		 */
7324 		*lenp = 0;
7325 		return (0);
7326 	}
7327 	/*
7328 	 * So here we are going to take the original rsm and make it what we
7329 	 * retransmitted. nrsm will be the tail portion we did not
7330 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
7331 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
7332 	 * 1, 6 and the new piece will be 6, 11.
7333 	 */
7334 	rack_clone_rsm(rack, nrsm, rsm, c_end);
7335 	nrsm->r_dupack = 0;
7336 	rack_log_retran_reason(rack, nrsm, __LINE__, 0, 2);
7337 	insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7338 #ifdef INVARIANTS
7339 	if (insret != NULL) {
7340 		panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7341 		      nrsm, insret, rack, rsm);
7342 	}
7343 #endif
7344 	if (rsm->r_in_tmap) {
7345 		TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7346 		nrsm->r_in_tmap = 1;
7347 	}
7348 	rsm->r_flags &= (~RACK_HAS_FIN);
7349 	rack_update_rsm(tp, rack, rsm, ts, add_flag);
7350 	/* Log a split of rsm into rsm and nrsm */
7351 	rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
7352 	*lenp = 0;
7353 	return (0);
7354 }
7355 
7356 static void
7357 rack_log_output(struct tcpcb *tp, struct tcpopt *to, int32_t len,
7358 		uint32_t seq_out, uint8_t th_flags, int32_t err, uint64_t cts,
7359 		struct rack_sendmap *hintrsm, uint16_t add_flag, struct mbuf *s_mb, uint32_t s_moff, int hw_tls)
7360 {
7361 	struct tcp_rack *rack;
7362 	struct rack_sendmap *rsm, *nrsm, *insret, fe;
7363 	register uint32_t snd_max, snd_una;
7364 
7365 	/*
7366 	 * Add to the RACK log of packets in flight or retransmitted. If
7367 	 * there is a TS option we will use the TS echoed, if not we will
7368 	 * grab a TS.
7369 	 *
7370 	 * Retransmissions will increment the count and move the ts to its
7371 	 * proper place. Note that if options do not include TS's then we
7372 	 * won't be able to effectively use the ACK for an RTT on a retran.
7373 	 *
7374 	 * Notes about r_start and r_end. Lets consider a send starting at
7375 	 * sequence 1 for 10 bytes. In such an example the r_start would be
7376 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
7377 	 * This means that r_end is actually the first sequence for the next
7378 	 * slot (11).
7379 	 *
7380 	 */
7381 	/*
7382 	 * If err is set what do we do XXXrrs? should we not add the thing?
7383 	 * -- i.e. return if err != 0 or should we pretend we sent it? --
7384 	 * i.e. proceed with add ** do this for now.
7385 	 */
7386 	INP_WLOCK_ASSERT(tp->t_inpcb);
7387 	if (err)
7388 		/*
7389 		 * We don't log errors -- we could but snd_max does not
7390 		 * advance in this case either.
7391 		 */
7392 		return;
7393 
7394 	if (th_flags & TH_RST) {
7395 		/*
7396 		 * We don't log resets and we return immediately from
7397 		 * sending
7398 		 */
7399 		return;
7400 	}
7401 	rack = (struct tcp_rack *)tp->t_fb_ptr;
7402 	snd_una = tp->snd_una;
7403 	snd_max = tp->snd_max;
7404 	if (th_flags & (TH_SYN | TH_FIN)) {
7405 		/*
7406 		 * The call to rack_log_output is made before bumping
7407 		 * snd_max. This means we can record one extra byte on a SYN
7408 		 * or FIN if seq_out is adding more on and a FIN is present
7409 		 * (and we are not resending).
7410 		 */
7411 		if ((th_flags & TH_SYN) && (seq_out == tp->iss))
7412 			len++;
7413 		if (th_flags & TH_FIN)
7414 			len++;
7415 		if (SEQ_LT(snd_max, tp->snd_nxt)) {
7416 			/*
7417 			 * The add/update as not been done for the FIN/SYN
7418 			 * yet.
7419 			 */
7420 			snd_max = tp->snd_nxt;
7421 		}
7422 	}
7423 	if (SEQ_LEQ((seq_out + len), snd_una)) {
7424 		/* Are sending an old segment to induce an ack (keep-alive)? */
7425 		return;
7426 	}
7427 	if (SEQ_LT(seq_out, snd_una)) {
7428 		/* huh? should we panic? */
7429 		uint32_t end;
7430 
7431 		end = seq_out + len;
7432 		seq_out = snd_una;
7433 		if (SEQ_GEQ(end, seq_out))
7434 			len = end - seq_out;
7435 		else
7436 			len = 0;
7437 	}
7438 	if (len == 0) {
7439 		/* We don't log zero window probes */
7440 		return;
7441 	}
7442 	rack->r_ctl.rc_time_last_sent = cts;
7443 	if (IN_FASTRECOVERY(tp->t_flags)) {
7444 		rack->r_ctl.rc_prr_out += len;
7445 	}
7446 	/* First question is it a retransmission or new? */
7447 	if (seq_out == snd_max) {
7448 		/* Its new */
7449 again:
7450 		rsm = rack_alloc(rack);
7451 		if (rsm == NULL) {
7452 			/*
7453 			 * Hmm out of memory and the tcb got destroyed while
7454 			 * we tried to wait.
7455 			 */
7456 			return;
7457 		}
7458 		if (th_flags & TH_FIN) {
7459 			rsm->r_flags = RACK_HAS_FIN|add_flag;
7460 		} else {
7461 			rsm->r_flags = add_flag;
7462 		}
7463 		if (hw_tls)
7464 			rsm->r_hw_tls = 1;
7465 		rsm->r_tim_lastsent[0] = cts;
7466 		rsm->r_rtr_cnt = 1;
7467 		rsm->r_rtr_bytes = 0;
7468 		if (th_flags & TH_SYN) {
7469 			/* The data space is one beyond snd_una */
7470 			rsm->r_flags |= RACK_HAS_SYN;
7471 		}
7472 		rsm->r_start = seq_out;
7473 		rsm->r_end = rsm->r_start + len;
7474 		rsm->r_dupack = 0;
7475 		/*
7476 		 * save off the mbuf location that
7477 		 * sndmbuf_noadv returned (which is
7478 		 * where we started copying from)..
7479 		 */
7480 		rsm->m = s_mb;
7481 		rsm->soff = s_moff;
7482 		/* rsm->m will be NULL if RACK_HAS_SYN or RACK_HAS_FIN is set */
7483 		if (rsm->m) {
7484 			if (rsm->m->m_len <= rsm->soff) {
7485 				/*
7486 				 * XXXrrs Question, will this happen?
7487 				 *
7488 				 * If sbsndptr is set at the correct place
7489 				 * then s_moff should always be somewhere
7490 				 * within rsm->m. But if the sbsndptr was
7491 				 * off then that won't be true. If it occurs
7492 				 * we need to walkout to the correct location.
7493 				 */
7494 				struct mbuf *lm;
7495 
7496 				lm = rsm->m;
7497 				while (lm->m_len <= rsm->soff) {
7498 					rsm->soff -= lm->m_len;
7499 					lm = lm->m_next;
7500 					KASSERT(lm != NULL, ("%s rack:%p lm goes null orig_off:%u origmb:%p rsm->soff:%u",
7501 							     __func__, rack, s_moff, s_mb, rsm->soff));
7502 				}
7503 				rsm->m = lm;
7504 				counter_u64_add(rack_sbsndptr_wrong, 1);
7505 			} else
7506 				counter_u64_add(rack_sbsndptr_right, 1);
7507 			rsm->orig_m_len = rsm->m->m_len;
7508 		} else
7509 			rsm->orig_m_len = 0;
7510 		rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
7511 		/* Log a new rsm */
7512 		rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_NEW, 0, __LINE__);
7513 		insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7514 #ifdef INVARIANTS
7515 		if (insret != NULL) {
7516 			panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7517 			      nrsm, insret, rack, rsm);
7518 		}
7519 #endif
7520 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
7521 		rsm->r_in_tmap = 1;
7522 		/*
7523 		 * Special case detection, is there just a single
7524 		 * packet outstanding when we are not in recovery?
7525 		 *
7526 		 * If this is true mark it so.
7527 		 */
7528 		if ((IN_FASTRECOVERY(tp->t_flags) == 0) &&
7529 		    (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) == ctf_fixed_maxseg(tp))) {
7530 			struct rack_sendmap *prsm;
7531 
7532 			prsm = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
7533 			if (prsm)
7534 				prsm->r_one_out_nr = 1;
7535 		}
7536 		return;
7537 	}
7538 	/*
7539 	 * If we reach here its a retransmission and we need to find it.
7540 	 */
7541 	memset(&fe, 0, sizeof(fe));
7542 more:
7543 	if (hintrsm && (hintrsm->r_start == seq_out)) {
7544 		rsm = hintrsm;
7545 		hintrsm = NULL;
7546 	} else {
7547 		/* No hints sorry */
7548 		rsm = NULL;
7549 	}
7550 	if ((rsm) && (rsm->r_start == seq_out)) {
7551 		seq_out = rack_update_entry(tp, rack, rsm, cts, &len, add_flag);
7552 		if (len == 0) {
7553 			return;
7554 		} else {
7555 			goto more;
7556 		}
7557 	}
7558 	/* Ok it was not the last pointer go through it the hard way. */
7559 refind:
7560 	fe.r_start = seq_out;
7561 	rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
7562 	if (rsm) {
7563 		if (rsm->r_start == seq_out) {
7564 			seq_out = rack_update_entry(tp, rack, rsm, cts, &len, add_flag);
7565 			if (len == 0) {
7566 				return;
7567 			} else {
7568 				goto refind;
7569 			}
7570 		}
7571 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
7572 			/* Transmitted within this piece */
7573 			/*
7574 			 * Ok we must split off the front and then let the
7575 			 * update do the rest
7576 			 */
7577 			nrsm = rack_alloc_full_limit(rack);
7578 			if (nrsm == NULL) {
7579 				rack_update_rsm(tp, rack, rsm, cts, add_flag);
7580 				return;
7581 			}
7582 			/*
7583 			 * copy rsm to nrsm and then trim the front of rsm
7584 			 * to not include this part.
7585 			 */
7586 			rack_clone_rsm(rack, nrsm, rsm, seq_out);
7587 			insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
7588 			rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SPLIT, 0, __LINE__);
7589 #ifdef INVARIANTS
7590 			if (insret != NULL) {
7591 				panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
7592 				      nrsm, insret, rack, rsm);
7593 			}
7594 #endif
7595 			if (rsm->r_in_tmap) {
7596 				TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7597 				nrsm->r_in_tmap = 1;
7598 			}
7599 			rsm->r_flags &= (~RACK_HAS_FIN);
7600 			seq_out = rack_update_entry(tp, rack, nrsm, cts, &len, add_flag);
7601 			if (len == 0) {
7602 				return;
7603 			} else if (len > 0)
7604 				goto refind;
7605 		}
7606 	}
7607 	/*
7608 	 * Hmm not found in map did they retransmit both old and on into the
7609 	 * new?
7610 	 */
7611 	if (seq_out == tp->snd_max) {
7612 		goto again;
7613 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
7614 #ifdef INVARIANTS
7615 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
7616 		       seq_out, len, tp->snd_una, tp->snd_max);
7617 		printf("Starting Dump of all rack entries\n");
7618 		RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
7619 			printf("rsm:%p start:%u end:%u\n",
7620 			       rsm, rsm->r_start, rsm->r_end);
7621 		}
7622 		printf("Dump complete\n");
7623 		panic("seq_out not found rack:%p tp:%p",
7624 		      rack, tp);
7625 #endif
7626 	} else {
7627 #ifdef INVARIANTS
7628 		/*
7629 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
7630 		 * flag)
7631 		 */
7632 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
7633 		      seq_out, len, tp->snd_max, tp);
7634 #endif
7635 	}
7636 }
7637 
7638 /*
7639  * Record one of the RTT updates from an ack into
7640  * our sample structure.
7641  */
7642 
7643 static void
7644 tcp_rack_xmit_timer(struct tcp_rack *rack, int32_t rtt, uint32_t len, uint32_t us_rtt,
7645 		    int confidence, struct rack_sendmap *rsm, uint16_t rtrcnt)
7646 {
7647 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7648 	    (rack->r_ctl.rack_rs.rs_rtt_lowest > rtt)) {
7649 		rack->r_ctl.rack_rs.rs_rtt_lowest = rtt;
7650 	}
7651 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7652 	    (rack->r_ctl.rack_rs.rs_rtt_highest < rtt)) {
7653 		rack->r_ctl.rack_rs.rs_rtt_highest = rtt;
7654 	}
7655 	if (rack->rc_tp->t_flags & TF_GPUTINPROG) {
7656 	    if (us_rtt < rack->r_ctl.rc_gp_lowrtt)
7657 		rack->r_ctl.rc_gp_lowrtt = us_rtt;
7658 	    if (rack->rc_tp->snd_wnd > rack->r_ctl.rc_gp_high_rwnd)
7659 		    rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
7660 	}
7661 	if ((confidence == 1) &&
7662 	    ((rsm == NULL) ||
7663 	     (rsm->r_just_ret) ||
7664 	     (rsm->r_one_out_nr &&
7665 	      len < (ctf_fixed_maxseg(rack->rc_tp) * 2)))) {
7666 		/*
7667 		 * If the rsm had a just return
7668 		 * hit it then we can't trust the
7669 		 * rtt measurement for buffer deterimination
7670 		 * Note that a confidence of 2, indicates
7671 		 * SACK'd which overrides the r_just_ret or
7672 		 * the r_one_out_nr. If it was a CUM-ACK and
7673 		 * we had only two outstanding, but get an
7674 		 * ack for only 1. Then that also lowers our
7675 		 * confidence.
7676 		 */
7677 		confidence = 0;
7678 	}
7679 	if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY) ||
7680 	    (rack->r_ctl.rack_rs.rs_us_rtt > us_rtt)) {
7681 		if (rack->r_ctl.rack_rs.confidence == 0) {
7682 			/*
7683 			 * We take anything with no current confidence
7684 			 * saved.
7685 			 */
7686 			rack->r_ctl.rack_rs.rs_us_rtt = us_rtt;
7687 			rack->r_ctl.rack_rs.confidence = confidence;
7688 			rack->r_ctl.rack_rs.rs_us_rtrcnt = rtrcnt;
7689 		} else if (confidence || rack->r_ctl.rack_rs.confidence) {
7690 			/*
7691 			 * Once we have a confident number,
7692 			 * we can update it with a smaller
7693 			 * value since this confident number
7694 			 * may include the DSACK time until
7695 			 * the next segment (the second one) arrived.
7696 			 */
7697 			rack->r_ctl.rack_rs.rs_us_rtt = us_rtt;
7698 			rack->r_ctl.rack_rs.confidence = confidence;
7699 			rack->r_ctl.rack_rs.rs_us_rtrcnt = rtrcnt;
7700 		}
7701 	}
7702 	rack_log_rtt_upd(rack->rc_tp, rack, us_rtt, len, rsm, confidence);
7703 	rack->r_ctl.rack_rs.rs_flags = RACK_RTT_VALID;
7704 	rack->r_ctl.rack_rs.rs_rtt_tot += rtt;
7705 	rack->r_ctl.rack_rs.rs_rtt_cnt++;
7706 }
7707 
7708 /*
7709  * Collect new round-trip time estimate
7710  * and update averages and current timeout.
7711  */
7712 static void
7713 tcp_rack_xmit_timer_commit(struct tcp_rack *rack, struct tcpcb *tp)
7714 {
7715 	int32_t delta;
7716 	uint32_t o_srtt, o_var;
7717 	int32_t hrtt_up = 0;
7718 	int32_t rtt;
7719 
7720 	if (rack->r_ctl.rack_rs.rs_flags & RACK_RTT_EMPTY)
7721 		/* No valid sample */
7722 		return;
7723 	if (rack->r_ctl.rc_rate_sample_method == USE_RTT_LOW) {
7724 		/* We are to use the lowest RTT seen in a single ack */
7725 		rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
7726 	} else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_HIGH) {
7727 		/* We are to use the highest RTT seen in a single ack */
7728 		rtt = rack->r_ctl.rack_rs.rs_rtt_highest;
7729 	} else if (rack->r_ctl.rc_rate_sample_method == USE_RTT_AVG) {
7730 		/* We are to use the average RTT seen in a single ack */
7731 		rtt = (int32_t)(rack->r_ctl.rack_rs.rs_rtt_tot /
7732 				(uint64_t)rack->r_ctl.rack_rs.rs_rtt_cnt);
7733 	} else {
7734 #ifdef INVARIANTS
7735 		panic("Unknown rtt variant %d", rack->r_ctl.rc_rate_sample_method);
7736 #endif
7737 		return;
7738 	}
7739 	if (rtt == 0)
7740 		rtt = 1;
7741 	if (rack->rc_gp_rtt_set == 0) {
7742 		/*
7743 		 * With no RTT we have to accept
7744 		 * even one we are not confident of.
7745 		 */
7746 		rack->r_ctl.rc_gp_srtt = rack->r_ctl.rack_rs.rs_us_rtt;
7747 		rack->rc_gp_rtt_set = 1;
7748 	} else if (rack->r_ctl.rack_rs.confidence) {
7749 		/* update the running gp srtt */
7750 		rack->r_ctl.rc_gp_srtt -= (rack->r_ctl.rc_gp_srtt/8);
7751 		rack->r_ctl.rc_gp_srtt += rack->r_ctl.rack_rs.rs_us_rtt / 8;
7752 	}
7753 	if (rack->r_ctl.rack_rs.confidence) {
7754 		/*
7755 		 * record the low and high for highly buffered path computation,
7756 		 * we only do this if we are confident (not a retransmission).
7757 		 */
7758 		if (rack->r_ctl.rc_highest_us_rtt < rack->r_ctl.rack_rs.rs_us_rtt) {
7759 			rack->r_ctl.rc_highest_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7760 			hrtt_up = 1;
7761 		}
7762 		if (rack->rc_highly_buffered == 0) {
7763 			/*
7764 			 * Currently once we declare a path has
7765 			 * highly buffered there is no going
7766 			 * back, which may be a problem...
7767 			 */
7768 			if ((rack->r_ctl.rc_highest_us_rtt / rack->r_ctl.rc_lowest_us_rtt) > rack_hbp_thresh) {
7769 				rack_log_rtt_shrinks(rack, rack->r_ctl.rack_rs.rs_us_rtt,
7770 						     rack->r_ctl.rc_highest_us_rtt,
7771 						     rack->r_ctl.rc_lowest_us_rtt,
7772 						     RACK_RTTS_SEEHBP);
7773 				rack->rc_highly_buffered = 1;
7774 			}
7775 		}
7776 	}
7777 	if ((rack->r_ctl.rack_rs.confidence) ||
7778 	    (rack->r_ctl.rack_rs.rs_us_rtrcnt == 1)) {
7779 		/*
7780 		 * If we are highly confident of it <or> it was
7781 		 * never retransmitted we accept it as the last us_rtt.
7782 		 */
7783 		rack->r_ctl.rc_last_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7784 		/* The lowest rtt can be set if its was not retransmited */
7785 		if (rack->r_ctl.rc_lowest_us_rtt > rack->r_ctl.rack_rs.rs_us_rtt) {
7786 			rack->r_ctl.rc_lowest_us_rtt = rack->r_ctl.rack_rs.rs_us_rtt;
7787 			if (rack->r_ctl.rc_lowest_us_rtt == 0)
7788 				rack->r_ctl.rc_lowest_us_rtt = 1;
7789 		}
7790 	}
7791 	o_srtt = tp->t_srtt;
7792 	o_var = tp->t_rttvar;
7793 	rack = (struct tcp_rack *)tp->t_fb_ptr;
7794 	if (tp->t_srtt != 0) {
7795 		/*
7796 		 * We keep a simple srtt in microseconds, like our rtt
7797 		 * measurement. We don't need to do any tricks with shifting
7798 		 * etc. Instead we just add in 1/8th of the new measurement
7799 		 * and subtract out 1/8 of the old srtt. We do the same with
7800 		 * the variance after finding the absolute value of the
7801 		 * difference between this sample and the current srtt.
7802 		 */
7803 		delta = tp->t_srtt - rtt;
7804 		/* Take off 1/8th of the current sRTT */
7805 		tp->t_srtt -= (tp->t_srtt >> 3);
7806 		/* Add in 1/8th of the new RTT just measured */
7807 		tp->t_srtt += (rtt >> 3);
7808 		if (tp->t_srtt <= 0)
7809 			tp->t_srtt = 1;
7810 		/* Now lets make the absolute value of the variance */
7811 		if (delta < 0)
7812 			delta = -delta;
7813 		/* Subtract out 1/8th */
7814 		tp->t_rttvar -= (tp->t_rttvar >> 3);
7815 		/* Add in 1/8th of the new variance we just saw */
7816 		tp->t_rttvar += (delta >> 3);
7817 		if (tp->t_rttvar <= 0)
7818 			tp->t_rttvar = 1;
7819 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
7820 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
7821 	} else {
7822 		/*
7823 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
7824 		 * variance to half the rtt (so our first retransmit happens
7825 		 * at 3*rtt).
7826 		 */
7827 		tp->t_srtt = rtt;
7828 		tp->t_rttvar = rtt >> 1;
7829 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
7830 	}
7831 	rack->rc_srtt_measure_made = 1;
7832 	KMOD_TCPSTAT_INC(tcps_rttupdated);
7833 	tp->t_rttupdated++;
7834 #ifdef STATS
7835 	if (rack_stats_gets_ms_rtt == 0) {
7836 		/* Send in the microsecond rtt used for rxt timeout purposes */
7837 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt));
7838 	} else if (rack_stats_gets_ms_rtt == 1) {
7839 		/* Send in the millisecond rtt used for rxt timeout purposes */
7840 		int32_t ms_rtt;
7841 
7842 		/* Round up */
7843 		ms_rtt = (rtt + HPTS_USEC_IN_MSEC - 1) / HPTS_USEC_IN_MSEC;
7844 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, ms_rtt));
7845 	} else if (rack_stats_gets_ms_rtt == 2) {
7846 		/* Send in the millisecond rtt has close to the path RTT as we can get  */
7847 		int32_t ms_rtt;
7848 
7849 		/* Round up */
7850 		ms_rtt = (rack->r_ctl.rack_rs.rs_us_rtt + HPTS_USEC_IN_MSEC - 1) / HPTS_USEC_IN_MSEC;
7851 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, ms_rtt));
7852 	}  else {
7853 		/* Send in the microsecond rtt has close to the path RTT as we can get  */
7854 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rack->r_ctl.rack_rs.rs_us_rtt));
7855 	}
7856 
7857 #endif
7858 	/*
7859 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
7860 	 * way we do the smoothing, srtt and rttvar will each average +1/2
7861 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
7862 	 * tick of rounding and 1 extra tick because of +-1/2 tick
7863 	 * uncertainty in the firing of the timer.  The bias will give us
7864 	 * exactly the 1.5 tick we need.  But, because the bias is
7865 	 * statistical, we have to test that we don't drop below the minimum
7866 	 * feasible timer (which is 2 ticks).
7867 	 */
7868 	tp->t_rxtshift = 0;
7869 	RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
7870 		      max(rack_rto_min, rtt + 2), rack_rto_max, rack->r_ctl.timer_slop);
7871 	rack_log_rtt_sample(rack, rtt);
7872 	tp->t_softerror = 0;
7873 }
7874 
7875 
7876 static void
7877 rack_apply_updated_usrtt(struct tcp_rack *rack, uint32_t us_rtt, uint32_t us_cts)
7878 {
7879 	/*
7880 	 * Apply to filter the inbound us-rtt at us_cts.
7881 	 */
7882 	uint32_t old_rtt;
7883 
7884 	old_rtt = get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt);
7885 	apply_filter_min_small(&rack->r_ctl.rc_gp_min_rtt,
7886 			       us_rtt, us_cts);
7887 	if (rack->r_ctl.last_pacing_time &&
7888 	    rack->rc_gp_dyn_mul &&
7889 	    (rack->r_ctl.last_pacing_time > us_rtt))
7890 		rack->pacing_longer_than_rtt = 1;
7891 	else
7892 		rack->pacing_longer_than_rtt = 0;
7893 	if (old_rtt > us_rtt) {
7894 		/* We just hit a new lower rtt time */
7895 		rack_log_rtt_shrinks(rack,  us_cts,  old_rtt,
7896 				     __LINE__, RACK_RTTS_NEWRTT);
7897 		/*
7898 		 * Only count it if its lower than what we saw within our
7899 		 * calculated range.
7900 		 */
7901 		if ((old_rtt - us_rtt) > rack_min_rtt_movement) {
7902 			if (rack_probertt_lower_within &&
7903 			    rack->rc_gp_dyn_mul &&
7904 			    (rack->use_fixed_rate == 0) &&
7905 			    (rack->rc_always_pace)) {
7906 				/*
7907 				 * We are seeing a new lower rtt very close
7908 				 * to the time that we would have entered probe-rtt.
7909 				 * This is probably due to the fact that a peer flow
7910 				 * has entered probe-rtt. Lets go in now too.
7911 				 */
7912 				uint32_t val;
7913 
7914 				val = rack_probertt_lower_within * rack_time_between_probertt;
7915 				val /= 100;
7916 				if ((rack->in_probe_rtt == 0)  &&
7917 				    ((us_cts - rack->r_ctl.rc_lower_rtt_us_cts) >= (rack_time_between_probertt - val)))	{
7918 					rack_enter_probertt(rack, us_cts);
7919 				}
7920 			}
7921 			rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
7922 		}
7923 	}
7924 }
7925 
7926 static int
7927 rack_update_rtt(struct tcpcb *tp, struct tcp_rack *rack,
7928     struct rack_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, tcp_seq th_ack)
7929 {
7930 	int32_t i, all;
7931 	uint32_t t, len_acked;
7932 
7933 	if ((rsm->r_flags & RACK_ACKED) ||
7934 	    (rsm->r_flags & RACK_WAS_ACKED))
7935 		/* Already done */
7936 		return (0);
7937 	if (rsm->r_no_rtt_allowed) {
7938 		/* Not allowed */
7939 		return (0);
7940 	}
7941 	if (ack_type == CUM_ACKED) {
7942 		if (SEQ_GT(th_ack, rsm->r_end)) {
7943 			len_acked = rsm->r_end - rsm->r_start;
7944 			all = 1;
7945 		} else {
7946 			len_acked = th_ack - rsm->r_start;
7947 			all = 0;
7948 		}
7949 	} else {
7950 		len_acked = rsm->r_end - rsm->r_start;
7951 		all = 0;
7952 	}
7953 	if (rsm->r_rtr_cnt == 1) {
7954 		uint32_t us_rtt;
7955 
7956 		t = cts - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
7957 		if ((int)t <= 0)
7958 			t = 1;
7959 		if (!tp->t_rttlow || tp->t_rttlow > t)
7960 			tp->t_rttlow = t;
7961 		if (!rack->r_ctl.rc_rack_min_rtt ||
7962 		    SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
7963 			rack->r_ctl.rc_rack_min_rtt = t;
7964 			if (rack->r_ctl.rc_rack_min_rtt == 0) {
7965 				rack->r_ctl.rc_rack_min_rtt = 1;
7966 			}
7967 		}
7968 		if (TSTMP_GT(tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time), rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]))
7969 			us_rtt = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time) - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
7970 		else
7971 			us_rtt = tcp_get_usecs(NULL) - (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
7972 		if (us_rtt == 0)
7973 			us_rtt = 1;
7974 		rack_apply_updated_usrtt(rack, us_rtt, tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time));
7975 		if (ack_type == SACKED) {
7976 			rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)], cts, 1);
7977 			tcp_rack_xmit_timer(rack, t + 1, len_acked, us_rtt, 2 , rsm, rsm->r_rtr_cnt);
7978 		} else {
7979 			/*
7980 			 * We need to setup what our confidence
7981 			 * is in this ack.
7982 			 *
7983 			 * If the rsm was app limited and it is
7984 			 * less than a mss in length (the end
7985 			 * of the send) then we have a gap. If we
7986 			 * were app limited but say we were sending
7987 			 * multiple MSS's then we are more confident
7988 			 * int it.
7989 			 *
7990 			 * When we are not app-limited then we see if
7991 			 * the rsm is being included in the current
7992 			 * measurement, we tell this by the app_limited_needs_set
7993 			 * flag.
7994 			 *
7995 			 * Note that being cwnd blocked is not applimited
7996 			 * as well as the pacing delay between packets which
7997 			 * are sending only 1 or 2 MSS's also will show up
7998 			 * in the RTT. We probably need to examine this algorithm
7999 			 * a bit more and enhance it to account for the delay
8000 			 * between rsm's. We could do that by saving off the
8001 			 * pacing delay of each rsm (in an rsm) and then
8002 			 * factoring that in somehow though for now I am
8003 			 * not sure how :)
8004 			 */
8005 			int calc_conf = 0;
8006 
8007 			if (rsm->r_flags & RACK_APP_LIMITED) {
8008 				if (all && (len_acked <= ctf_fixed_maxseg(tp)))
8009 					calc_conf = 0;
8010 				else
8011 					calc_conf = 1;
8012 			} else if (rack->app_limited_needs_set == 0) {
8013 				calc_conf = 1;
8014 			} else {
8015 				calc_conf = 0;
8016 			}
8017 			rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)], cts, 2);
8018 			tcp_rack_xmit_timer(rack, t + 1, len_acked, us_rtt,
8019 					    calc_conf, rsm, rsm->r_rtr_cnt);
8020 		}
8021 		if ((rsm->r_flags & RACK_TLP) &&
8022 		    (!IN_FASTRECOVERY(tp->t_flags))) {
8023 			/* Segment was a TLP and our retrans matched */
8024 			if (rack->r_ctl.rc_tlp_cwnd_reduce) {
8025 				rack->r_ctl.rc_rsm_start = tp->snd_max;
8026 				rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
8027 				rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
8028 				rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
8029 			}
8030 		}
8031 		if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
8032 			/* New more recent rack_tmit_time */
8033 			rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
8034 			rack->rc_rack_rtt = t;
8035 		}
8036 		return (1);
8037 	}
8038 	/*
8039 	 * We clear the soft/rxtshift since we got an ack.
8040 	 * There is no assurance we will call the commit() function
8041 	 * so we need to clear these to avoid incorrect handling.
8042 	 */
8043 	tp->t_rxtshift = 0;
8044 	RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
8045 		      rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
8046 	tp->t_softerror = 0;
8047 	if (to && (to->to_flags & TOF_TS) &&
8048 	    (ack_type == CUM_ACKED) &&
8049 	    (to->to_tsecr) &&
8050 	    ((rsm->r_flags & RACK_OVERMAX) == 0)) {
8051 		/*
8052 		 * Now which timestamp does it match? In this block the ACK
8053 		 * must be coming from a previous transmission.
8054 		 */
8055 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
8056 			if (rack_ts_to_msec(rsm->r_tim_lastsent[i]) == to->to_tsecr) {
8057 				t = cts - (uint32_t)rsm->r_tim_lastsent[i];
8058 				if ((int)t <= 0)
8059 					t = 1;
8060 				if ((i + 1) < rsm->r_rtr_cnt) {
8061 					/*
8062 					 * The peer ack'd from our previous
8063 					 * transmission. We have a spurious
8064 					 * retransmission and thus we dont
8065 					 * want to update our rack_rtt.
8066 					 */
8067 					return (0);
8068 				}
8069 				if (!tp->t_rttlow || tp->t_rttlow > t)
8070 					tp->t_rttlow = t;
8071 				if (!rack->r_ctl.rc_rack_min_rtt || SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
8072 					rack->r_ctl.rc_rack_min_rtt = t;
8073 					if (rack->r_ctl.rc_rack_min_rtt == 0) {
8074 						rack->r_ctl.rc_rack_min_rtt = 1;
8075 					}
8076 				}
8077 				if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time,
8078 					   (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)])) {
8079 					/* New more recent rack_tmit_time */
8080 					rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
8081 					rack->rc_rack_rtt = t;
8082 				}
8083 				rack_log_rtt_sample_calc(rack, t, (uint32_t)rsm->r_tim_lastsent[i], cts, 3);
8084 				tcp_rack_xmit_timer(rack, t + 1, len_acked, t, 0, rsm,
8085 						    rsm->r_rtr_cnt);
8086 				return (1);
8087 			}
8088 		}
8089 		goto ts_not_found;
8090 	} else {
8091 		/*
8092 		 * Ok its a SACK block that we retransmitted. or a windows
8093 		 * machine without timestamps. We can tell nothing from the
8094 		 * time-stamp since its not there or the time the peer last
8095 		 * recieved a segment that moved forward its cum-ack point.
8096 		 */
8097 ts_not_found:
8098 		i = rsm->r_rtr_cnt - 1;
8099 		t = cts - (uint32_t)rsm->r_tim_lastsent[i];
8100 		if ((int)t <= 0)
8101 			t = 1;
8102 		if (rack->r_ctl.rc_rack_min_rtt && SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
8103 			/*
8104 			 * We retransmitted and the ack came back in less
8105 			 * than the smallest rtt we have observed. We most
8106 			 * likely did an improper retransmit as outlined in
8107 			 * 6.2 Step 2 point 2 in the rack-draft so we
8108 			 * don't want to update our rack_rtt. We in
8109 			 * theory (in future) might want to think about reverting our
8110 			 * cwnd state but we won't for now.
8111 			 */
8112 			return (0);
8113 		} else if (rack->r_ctl.rc_rack_min_rtt) {
8114 			/*
8115 			 * We retransmitted it and the retransmit did the
8116 			 * job.
8117 			 */
8118 			if (!rack->r_ctl.rc_rack_min_rtt ||
8119 			    SEQ_LT(t, rack->r_ctl.rc_rack_min_rtt)) {
8120 				rack->r_ctl.rc_rack_min_rtt = t;
8121 				if (rack->r_ctl.rc_rack_min_rtt == 0) {
8122 					rack->r_ctl.rc_rack_min_rtt = 1;
8123 				}
8124 			}
8125 			if (SEQ_LT(rack->r_ctl.rc_rack_tmit_time, (uint32_t)rsm->r_tim_lastsent[i])) {
8126 				/* New more recent rack_tmit_time */
8127 				rack->r_ctl.rc_rack_tmit_time = (uint32_t)rsm->r_tim_lastsent[i];
8128 				rack->rc_rack_rtt = t;
8129 			}
8130 			return (1);
8131 		}
8132 	}
8133 	return (0);
8134 }
8135 
8136 /*
8137  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
8138  */
8139 static void
8140 rack_log_sack_passed(struct tcpcb *tp,
8141     struct tcp_rack *rack, struct rack_sendmap *rsm)
8142 {
8143 	struct rack_sendmap *nrsm;
8144 
8145 	nrsm = rsm;
8146 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &rack->r_ctl.rc_tmap,
8147 	    rack_head, r_tnext) {
8148 		if (nrsm == rsm) {
8149 			/* Skip orginal segment he is acked */
8150 			continue;
8151 		}
8152 		if (nrsm->r_flags & RACK_ACKED) {
8153 			/*
8154 			 * Skip ack'd segments, though we
8155 			 * should not see these, since tmap
8156 			 * should not have ack'd segments.
8157 			 */
8158 			continue;
8159 		}
8160 		if (nrsm->r_flags & RACK_SACK_PASSED) {
8161 			/*
8162 			 * We found one that is already marked
8163 			 * passed, we have been here before and
8164 			 * so all others below this are marked.
8165 			 */
8166 			break;
8167 		}
8168 		nrsm->r_flags |= RACK_SACK_PASSED;
8169 		nrsm->r_flags &= ~RACK_WAS_SACKPASS;
8170 	}
8171 }
8172 
8173 static void
8174 rack_need_set_test(struct tcpcb *tp,
8175 		   struct tcp_rack *rack,
8176 		   struct rack_sendmap *rsm,
8177 		   tcp_seq th_ack,
8178 		   int line,
8179 		   int use_which)
8180 {
8181 
8182 	if ((tp->t_flags & TF_GPUTINPROG) &&
8183 	    SEQ_GEQ(rsm->r_end, tp->gput_seq)) {
8184 		/*
8185 		 * We were app limited, and this ack
8186 		 * butts up or goes beyond the point where we want
8187 		 * to start our next measurement. We need
8188 		 * to record the new gput_ts as here and
8189 		 * possibly update the start sequence.
8190 		 */
8191 		uint32_t seq, ts;
8192 
8193 		if (rsm->r_rtr_cnt > 1) {
8194 			/*
8195 			 * This is a retransmit, can we
8196 			 * really make any assessment at this
8197 			 * point?  We are not really sure of
8198 			 * the timestamp, is it this or the
8199 			 * previous transmission?
8200 			 *
8201 			 * Lets wait for something better that
8202 			 * is not retransmitted.
8203 			 */
8204 			return;
8205 		}
8206 		seq = tp->gput_seq;
8207 		ts = tp->gput_ts;
8208 		rack->app_limited_needs_set = 0;
8209 		tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
8210 		/* Do we start at a new end? */
8211 		if ((use_which == RACK_USE_BEG) &&
8212 		    SEQ_GEQ(rsm->r_start, tp->gput_seq)) {
8213 			/*
8214 			 * When we get an ACK that just eats
8215 			 * up some of the rsm, we set RACK_USE_BEG
8216 			 * since whats at r_start (i.e. th_ack)
8217 			 * is left unacked and thats where the
8218 			 * measurement not starts.
8219 			 */
8220 			tp->gput_seq = rsm->r_start;
8221 			rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8222 		}
8223 		if ((use_which == RACK_USE_END) &&
8224 		    SEQ_GEQ(rsm->r_end, tp->gput_seq)) {
8225 			    /*
8226 			     * We use the end when the cumack
8227 			     * is moving forward and completely
8228 			     * deleting the rsm passed so basically
8229 			     * r_end holds th_ack.
8230 			     *
8231 			     * For SACK's we also want to use the end
8232 			     * since this piece just got sacked and
8233 			     * we want to target anything after that
8234 			     * in our measurement.
8235 			     */
8236 			    tp->gput_seq = rsm->r_end;
8237 			    rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8238 		}
8239 		if (use_which == RACK_USE_END_OR_THACK) {
8240 			/*
8241 			 * special case for ack moving forward,
8242 			 * not a sack, we need to move all the
8243 			 * way up to where this ack cum-ack moves
8244 			 * to.
8245 			 */
8246 			if (SEQ_GT(th_ack, rsm->r_end))
8247 				tp->gput_seq = th_ack;
8248 			else
8249 				tp->gput_seq = rsm->r_end;
8250 			rack->r_ctl.rc_gp_output_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
8251 		}
8252 		if (SEQ_GT(tp->gput_seq, tp->gput_ack)) {
8253 			/*
8254 			 * We moved beyond this guy's range, re-calculate
8255 			 * the new end point.
8256 			 */
8257 			if (rack->rc_gp_filled == 0) {
8258 				tp->gput_ack = tp->gput_seq + max(rc_init_window(rack), (MIN_GP_WIN * ctf_fixed_maxseg(tp)));
8259 			} else {
8260 				tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
8261 			}
8262 		}
8263 		/*
8264 		 * We are moving the goal post, we may be able to clear the
8265 		 * measure_saw_probe_rtt flag.
8266 		 */
8267 		if ((rack->in_probe_rtt == 0) &&
8268 		    (rack->measure_saw_probe_rtt) &&
8269 		    (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
8270 			rack->measure_saw_probe_rtt = 0;
8271 		rack_log_pacing_delay_calc(rack, ts, tp->gput_ts,
8272 					   seq, tp->gput_seq, 0, 5, line, NULL, 0);
8273 		if (rack->rc_gp_filled &&
8274 		    ((tp->gput_ack - tp->gput_seq) <
8275 		     max(rc_init_window(rack), (MIN_GP_WIN *
8276 						ctf_fixed_maxseg(tp))))) {
8277 			uint32_t ideal_amount;
8278 
8279 			ideal_amount = rack_get_measure_window(tp, rack);
8280 			if (ideal_amount > sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
8281 				/*
8282 				 * There is no sense of continuing this measurement
8283 				 * because its too small to gain us anything we
8284 				 * trust. Skip it and that way we can start a new
8285 				 * measurement quicker.
8286 				 */
8287 				tp->t_flags &= ~TF_GPUTINPROG;
8288 				rack_log_pacing_delay_calc(rack, tp->gput_ack, tp->gput_seq,
8289 							   0, 0, 0, 6, __LINE__, NULL, 0);
8290 			} else {
8291 				/*
8292 				 * Reset the window further out.
8293 				 */
8294 				tp->gput_ack = tp->gput_seq + ideal_amount;
8295 			}
8296 		}
8297 	}
8298 }
8299 
8300 static inline int
8301 is_rsm_inside_declared_tlp_block(struct tcp_rack *rack, struct rack_sendmap *rsm)
8302 {
8303 	if (SEQ_LT(rsm->r_end, rack->r_ctl.last_tlp_acked_start)) {
8304 		/* Behind our TLP definition or right at */
8305 		return (0);
8306 	}
8307 	if (SEQ_GT(rsm->r_start, rack->r_ctl.last_tlp_acked_end)) {
8308 		/* The start is beyond or right at our end of TLP definition */
8309 		return (0);
8310 	}
8311 	/* It has to be a sub-part of the original TLP recorded */
8312 	return (1);
8313 }
8314 
8315 
8316 static uint32_t
8317 rack_proc_sack_blk(struct tcpcb *tp, struct tcp_rack *rack, struct sackblk *sack,
8318 		   struct tcpopt *to, struct rack_sendmap **prsm, uint32_t cts, int *moved_two)
8319 {
8320 	uint32_t start, end, changed = 0;
8321 	struct rack_sendmap stack_map;
8322 	struct rack_sendmap *rsm, *nrsm, fe, *insret, *prev, *next;
8323 	int32_t used_ref = 1;
8324 	int moved = 0;
8325 
8326 	start = sack->start;
8327 	end = sack->end;
8328 	rsm = *prsm;
8329 	memset(&fe, 0, sizeof(fe));
8330 do_rest_ofb:
8331 	if ((rsm == NULL) ||
8332 	    (SEQ_LT(end, rsm->r_start)) ||
8333 	    (SEQ_GEQ(start, rsm->r_end)) ||
8334 	    (SEQ_LT(start, rsm->r_start))) {
8335 		/*
8336 		 * We are not in the right spot,
8337 		 * find the correct spot in the tree.
8338 		 */
8339 		used_ref = 0;
8340 		fe.r_start = start;
8341 		rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
8342 		moved++;
8343 	}
8344 	if (rsm == NULL) {
8345 		/* TSNH */
8346 		goto out;
8347 	}
8348 	/* Ok we have an ACK for some piece of this rsm */
8349 	if (rsm->r_start != start) {
8350 		if ((rsm->r_flags & RACK_ACKED) == 0) {
8351 			/*
8352 			 * Before any splitting or hookery is
8353 			 * done is it a TLP of interest i.e. rxt?
8354 			 */
8355 			if ((rsm->r_flags & RACK_TLP) &&
8356 			    (rsm->r_rtr_cnt > 1)) {
8357 				/*
8358 				 * We are splitting a rxt TLP, check
8359 				 * if we need to save off the start/end
8360 				 */
8361 				if (rack->rc_last_tlp_acked_set &&
8362 				    (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8363 					/*
8364 					 * We already turned this on since we are inside
8365 					 * the previous one was a partially sack now we
8366 					 * are getting another one (maybe all of it).
8367 					 *
8368 					 */
8369 					rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8370 					/*
8371 					 * Lets make sure we have all of it though.
8372 					 */
8373 					if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8374 						rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8375 						rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8376 								     rack->r_ctl.last_tlp_acked_end);
8377 					}
8378 					if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8379 						rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8380 						rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8381 								     rack->r_ctl.last_tlp_acked_end);
8382 					}
8383 				} else {
8384 					rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8385 					rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8386 					rack->rc_last_tlp_past_cumack = 0;
8387 					rack->rc_last_tlp_acked_set = 1;
8388 					rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8389 				}
8390 			}
8391 			/**
8392 			 * Need to split this in two pieces the before and after,
8393 			 * the before remains in the map, the after must be
8394 			 * added. In other words we have:
8395 			 * rsm        |--------------|
8396 			 * sackblk        |------->
8397 			 * rsm will become
8398 			 *     rsm    |---|
8399 			 * and nrsm will be  the sacked piece
8400 			 *     nrsm       |----------|
8401 			 *
8402 			 * But before we start down that path lets
8403 			 * see if the sack spans over on top of
8404 			 * the next guy and it is already sacked.
8405 			 *
8406 			 */
8407 			next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8408 			if (next && (next->r_flags & RACK_ACKED) &&
8409 			    SEQ_GEQ(end, next->r_start)) {
8410 				/**
8411 				 * So the next one is already acked, and
8412 				 * we can thus by hookery use our stack_map
8413 				 * to reflect the piece being sacked and
8414 				 * then adjust the two tree entries moving
8415 				 * the start and ends around. So we start like:
8416 				 *  rsm     |------------|             (not-acked)
8417 				 *  next                 |-----------| (acked)
8418 				 *  sackblk        |-------->
8419 				 *  We want to end like so:
8420 				 *  rsm     |------|                   (not-acked)
8421 				 *  next           |-----------------| (acked)
8422 				 *  nrsm           |-----|
8423 				 * Where nrsm is a temporary stack piece we
8424 				 * use to update all the gizmos.
8425 				 */
8426 				/* Copy up our fudge block */
8427 				nrsm = &stack_map;
8428 				memcpy(nrsm, rsm, sizeof(struct rack_sendmap));
8429 				/* Now adjust our tree blocks */
8430 				rsm->r_end = start;
8431 				next->r_start = start;
8432 				/* Now we must adjust back where next->m is */
8433 				rack_setup_offset_for_rsm(rsm, next);
8434 
8435 				/* We don't need to adjust rsm, it did not change */
8436 				/* Clear out the dup ack count of the remainder */
8437 				rsm->r_dupack = 0;
8438 				rsm->r_just_ret = 0;
8439 				rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8440 				/* Now lets make sure our fudge block is right */
8441 				nrsm->r_start = start;
8442 				/* Now lets update all the stats and such */
8443 				rack_update_rtt(tp, rack, nrsm, to, cts, SACKED, 0);
8444 				if (rack->app_limited_needs_set)
8445 					rack_need_set_test(tp, rack, nrsm, tp->snd_una, __LINE__, RACK_USE_END);
8446 				changed += (nrsm->r_end - nrsm->r_start);
8447 				rack->r_ctl.rc_sacked += (nrsm->r_end - nrsm->r_start);
8448 				if (nrsm->r_flags & RACK_SACK_PASSED) {
8449 					counter_u64_add(rack_reorder_seen, 1);
8450 					rack->r_ctl.rc_reorder_ts = cts;
8451 				}
8452 				/*
8453 				 * Now we want to go up from rsm (the
8454 				 * one left un-acked) to the next one
8455 				 * in the tmap. We do this so when
8456 				 * we walk backwards we include marking
8457 				 * sack-passed on rsm (The one passed in
8458 				 * is skipped since it is generally called
8459 				 * on something sacked before removing it
8460 				 * from the tmap).
8461 				 */
8462 				if (rsm->r_in_tmap) {
8463 					nrsm = TAILQ_NEXT(rsm, r_tnext);
8464 					/*
8465 					 * Now that we have the next
8466 					 * one walk backwards from there.
8467 					 */
8468 					if (nrsm && nrsm->r_in_tmap)
8469 						rack_log_sack_passed(tp, rack, nrsm);
8470 				}
8471 				/* Now are we done? */
8472 				if (SEQ_LT(end, next->r_end) ||
8473 				    (end == next->r_end)) {
8474 					/* Done with block */
8475 					goto out;
8476 				}
8477 				rack_log_map_chg(tp, rack, &stack_map, rsm, next, MAP_SACK_M1, end, __LINE__);
8478 				counter_u64_add(rack_sack_used_next_merge, 1);
8479 				/* Postion for the next block */
8480 				start = next->r_end;
8481 				rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, next);
8482 				if (rsm == NULL)
8483 					goto out;
8484 			} else {
8485 				/**
8486 				 * We can't use any hookery here, so we
8487 				 * need to split the map. We enter like
8488 				 * so:
8489 				 *  rsm      |--------|
8490 				 *  sackblk       |----->
8491 				 * We will add the new block nrsm and
8492 				 * that will be the new portion, and then
8493 				 * fall through after reseting rsm. So we
8494 				 * split and look like this:
8495 				 *  rsm      |----|
8496 				 *  sackblk       |----->
8497 				 *  nrsm          |---|
8498 				 * We then fall through reseting
8499 				 * rsm to nrsm, so the next block
8500 				 * picks it up.
8501 				 */
8502 				nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
8503 				if (nrsm == NULL) {
8504 					/*
8505 					 * failed XXXrrs what can we do but loose the sack
8506 					 * info?
8507 					 */
8508 					goto out;
8509 				}
8510 				counter_u64_add(rack_sack_splits, 1);
8511 				rack_clone_rsm(rack, nrsm, rsm, start);
8512 				rsm->r_just_ret = 0;
8513 				insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8514 #ifdef INVARIANTS
8515 				if (insret != NULL) {
8516 					panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
8517 					      nrsm, insret, rack, rsm);
8518 				}
8519 #endif
8520 				if (rsm->r_in_tmap) {
8521 					TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8522 					nrsm->r_in_tmap = 1;
8523 				}
8524 				rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SACK_M2, end, __LINE__);
8525 				rsm->r_flags &= (~RACK_HAS_FIN);
8526 				/* Position us to point to the new nrsm that starts the sack blk */
8527 				rsm = nrsm;
8528 			}
8529 		} else {
8530 			/* Already sacked this piece */
8531 			counter_u64_add(rack_sack_skipped_acked, 1);
8532 			moved++;
8533 			if (end == rsm->r_end) {
8534 				/* Done with block */
8535 				rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8536 				goto out;
8537 			} else if (SEQ_LT(end, rsm->r_end)) {
8538 				/* A partial sack to a already sacked block */
8539 				moved++;
8540 				rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8541 				goto out;
8542 			} else {
8543 				/*
8544 				 * The end goes beyond this guy
8545 				 * repostion the start to the
8546 				 * next block.
8547 				 */
8548 				start = rsm->r_end;
8549 				rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8550 				if (rsm == NULL)
8551 					goto out;
8552 			}
8553 		}
8554 	}
8555 	if (SEQ_GEQ(end, rsm->r_end)) {
8556 		/**
8557 		 * The end of this block is either beyond this guy or right
8558 		 * at this guy. I.e.:
8559 		 *  rsm ---                 |-----|
8560 		 *  end                     |-----|
8561 		 *  <or>
8562 		 *  end                     |---------|
8563 		 */
8564 		if ((rsm->r_flags & RACK_ACKED) == 0) {
8565 			/*
8566 			 * Is it a TLP of interest?
8567 			 */
8568 			if ((rsm->r_flags & RACK_TLP) &&
8569 			    (rsm->r_rtr_cnt > 1)) {
8570 				/*
8571 				 * We are splitting a rxt TLP, check
8572 				 * if we need to save off the start/end
8573 				 */
8574 				if (rack->rc_last_tlp_acked_set &&
8575 				    (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8576 					/*
8577 					 * We already turned this on since we are inside
8578 					 * the previous one was a partially sack now we
8579 					 * are getting another one (maybe all of it).
8580 					 */
8581 					rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8582 					/*
8583 					 * Lets make sure we have all of it though.
8584 					 */
8585 					if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8586 						rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8587 						rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8588 								     rack->r_ctl.last_tlp_acked_end);
8589 					}
8590 					if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8591 						rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8592 						rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8593 								     rack->r_ctl.last_tlp_acked_end);
8594 					}
8595 				} else {
8596 					rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8597 					rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8598 					rack->rc_last_tlp_past_cumack = 0;
8599 					rack->rc_last_tlp_acked_set = 1;
8600 					rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8601 				}
8602 			}
8603 			rack_update_rtt(tp, rack, rsm, to, cts, SACKED, 0);
8604 			changed += (rsm->r_end - rsm->r_start);
8605 			rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
8606 			if (rsm->r_in_tmap) /* should be true */
8607 				rack_log_sack_passed(tp, rack, rsm);
8608 			/* Is Reordering occuring? */
8609 			if (rsm->r_flags & RACK_SACK_PASSED) {
8610 				rsm->r_flags &= ~RACK_SACK_PASSED;
8611 				counter_u64_add(rack_reorder_seen, 1);
8612 				rack->r_ctl.rc_reorder_ts = cts;
8613 			}
8614 			if (rack->app_limited_needs_set)
8615 				rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_END);
8616 			rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8617 			rsm->r_flags |= RACK_ACKED;
8618 			if (rsm->r_in_tmap) {
8619 				TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8620 				rsm->r_in_tmap = 0;
8621 			}
8622 			rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_SACK_M3, end, __LINE__);
8623 		} else {
8624 			counter_u64_add(rack_sack_skipped_acked, 1);
8625 			moved++;
8626 		}
8627 		if (end == rsm->r_end) {
8628 			/* This block only - done, setup for next */
8629 			goto out;
8630 		}
8631 		/*
8632 		 * There is more not coverend by this rsm move on
8633 		 * to the next block in the RB tree.
8634 		 */
8635 		nrsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8636 		start = rsm->r_end;
8637 		rsm = nrsm;
8638 		if (rsm == NULL)
8639 			goto out;
8640 		goto do_rest_ofb;
8641 	}
8642 	/**
8643 	 * The end of this sack block is smaller than
8644 	 * our rsm i.e.:
8645 	 *  rsm ---                 |-----|
8646 	 *  end                     |--|
8647 	 */
8648 	if ((rsm->r_flags & RACK_ACKED) == 0) {
8649 		/*
8650 		 * Is it a TLP of interest?
8651 		 */
8652 		if ((rsm->r_flags & RACK_TLP) &&
8653 		    (rsm->r_rtr_cnt > 1)) {
8654 			/*
8655 			 * We are splitting a rxt TLP, check
8656 			 * if we need to save off the start/end
8657 			 */
8658 			if (rack->rc_last_tlp_acked_set &&
8659 			    (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8660 				/*
8661 				 * We already turned this on since we are inside
8662 				 * the previous one was a partially sack now we
8663 				 * are getting another one (maybe all of it).
8664 				 */
8665 				rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8666 				/*
8667 				 * Lets make sure we have all of it though.
8668 				 */
8669 				if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8670 					rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8671 					rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8672 							     rack->r_ctl.last_tlp_acked_end);
8673 				}
8674 				if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8675 					rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8676 					rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8677 							     rack->r_ctl.last_tlp_acked_end);
8678 				}
8679 			} else {
8680 				rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8681 				rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8682 				rack->rc_last_tlp_past_cumack = 0;
8683 				rack->rc_last_tlp_acked_set = 1;
8684 				rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8685 			}
8686 		}
8687 		prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8688 		if (prev &&
8689 		    (prev->r_flags & RACK_ACKED)) {
8690 			/**
8691 			 * Goal, we want the right remainder of rsm to shrink
8692 			 * in place and span from (rsm->r_start = end) to rsm->r_end.
8693 			 * We want to expand prev to go all the way
8694 			 * to prev->r_end <- end.
8695 			 * so in the tree we have before:
8696 			 *   prev     |--------|         (acked)
8697 			 *   rsm               |-------| (non-acked)
8698 			 *   sackblk           |-|
8699 			 * We churn it so we end up with
8700 			 *   prev     |----------|       (acked)
8701 			 *   rsm                 |-----| (non-acked)
8702 			 *   nrsm              |-| (temporary)
8703 			 *
8704 			 * Note if either prev/rsm is a TLP we don't
8705 			 * do this.
8706 			 */
8707 			nrsm = &stack_map;
8708 			memcpy(nrsm, rsm, sizeof(struct rack_sendmap));
8709 			prev->r_end = end;
8710 			rsm->r_start = end;
8711 			/* Now adjust nrsm (stack copy) to be
8712 			 * the one that is the small
8713 			 * piece that was "sacked".
8714 			 */
8715 			nrsm->r_end = end;
8716 			rsm->r_dupack = 0;
8717 			rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
8718 			/*
8719 			 * Now that the rsm has had its start moved forward
8720 			 * lets go ahead and get its new place in the world.
8721 			 */
8722 			rack_setup_offset_for_rsm(prev, rsm);
8723 			/*
8724 			 * Now nrsm is our new little piece
8725 			 * that is acked (which was merged
8726 			 * to prev). Update the rtt and changed
8727 			 * based on that. Also check for reordering.
8728 			 */
8729 			rack_update_rtt(tp, rack, nrsm, to, cts, SACKED, 0);
8730 			if (rack->app_limited_needs_set)
8731 				rack_need_set_test(tp, rack, nrsm, tp->snd_una, __LINE__, RACK_USE_END);
8732 			changed += (nrsm->r_end - nrsm->r_start);
8733 			rack->r_ctl.rc_sacked += (nrsm->r_end - nrsm->r_start);
8734 			if (nrsm->r_flags & RACK_SACK_PASSED) {
8735 				counter_u64_add(rack_reorder_seen, 1);
8736 				rack->r_ctl.rc_reorder_ts = cts;
8737 			}
8738 			rack_log_map_chg(tp, rack, prev, &stack_map, rsm, MAP_SACK_M4, end, __LINE__);
8739 			rsm = prev;
8740 			counter_u64_add(rack_sack_used_prev_merge, 1);
8741 		} else {
8742 			/**
8743 			 * This is the case where our previous
8744 			 * block is not acked either, so we must
8745 			 * split the block in two.
8746 			 */
8747 			nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
8748 			if (nrsm == NULL) {
8749 				/* failed rrs what can we do but loose the sack info? */
8750 				goto out;
8751 			}
8752 			if ((rsm->r_flags & RACK_TLP) &&
8753 			    (rsm->r_rtr_cnt > 1)) {
8754 				/*
8755 				 * We are splitting a rxt TLP, check
8756 				 * if we need to save off the start/end
8757 				 */
8758 				if (rack->rc_last_tlp_acked_set &&
8759 				    (is_rsm_inside_declared_tlp_block(rack, rsm))) {
8760 					    /*
8761 					     * We already turned this on since this block is inside
8762 					     * the previous one was a partially sack now we
8763 					     * are getting another one (maybe all of it).
8764 					     */
8765 					    rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
8766 					    /*
8767 					     * Lets make sure we have all of it though.
8768 					     */
8769 					    if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
8770 						    rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8771 						    rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8772 									 rack->r_ctl.last_tlp_acked_end);
8773 					    }
8774 					    if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
8775 						    rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8776 						    rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
8777 									 rack->r_ctl.last_tlp_acked_end);
8778 					    }
8779 				    } else {
8780 					    rack->r_ctl.last_tlp_acked_start = rsm->r_start;
8781 					    rack->r_ctl.last_tlp_acked_end = rsm->r_end;
8782 					    rack->rc_last_tlp_acked_set = 1;
8783 					    rack->rc_last_tlp_past_cumack = 0;
8784 					    rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
8785 				    }
8786 			}
8787 			/**
8788 			 * In this case nrsm becomes
8789 			 * nrsm->r_start = end;
8790 			 * nrsm->r_end = rsm->r_end;
8791 			 * which is un-acked.
8792 			 * <and>
8793 			 * rsm->r_end = nrsm->r_start;
8794 			 * i.e. the remaining un-acked
8795 			 * piece is left on the left
8796 			 * hand side.
8797 			 *
8798 			 * So we start like this
8799 			 * rsm      |----------| (not acked)
8800 			 * sackblk  |---|
8801 			 * build it so we have
8802 			 * rsm      |---|         (acked)
8803 			 * nrsm         |------|  (not acked)
8804 			 */
8805 			counter_u64_add(rack_sack_splits, 1);
8806 			rack_clone_rsm(rack, nrsm, rsm, end);
8807 			rsm->r_flags &= (~RACK_HAS_FIN);
8808 			rsm->r_just_ret = 0;
8809 			insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
8810 #ifdef INVARIANTS
8811 			if (insret != NULL) {
8812 				panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
8813 				      nrsm, insret, rack, rsm);
8814 			}
8815 #endif
8816 			if (rsm->r_in_tmap) {
8817 				TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8818 				nrsm->r_in_tmap = 1;
8819 			}
8820 			nrsm->r_dupack = 0;
8821 			rack_log_retran_reason(rack, nrsm, __LINE__, 0, 2);
8822 			rack_update_rtt(tp, rack, rsm, to, cts, SACKED, 0);
8823 			changed += (rsm->r_end - rsm->r_start);
8824 			rack->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
8825 			if (rsm->r_in_tmap) /* should be true */
8826 				rack_log_sack_passed(tp, rack, rsm);
8827 			/* Is Reordering occuring? */
8828 			if (rsm->r_flags & RACK_SACK_PASSED) {
8829 				rsm->r_flags &= ~RACK_SACK_PASSED;
8830 				counter_u64_add(rack_reorder_seen, 1);
8831 				rack->r_ctl.rc_reorder_ts = cts;
8832 			}
8833 			if (rack->app_limited_needs_set)
8834 				rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_END);
8835 			rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
8836 			rsm->r_flags |= RACK_ACKED;
8837 			rack_log_map_chg(tp, rack, NULL, rsm, nrsm, MAP_SACK_M5, end, __LINE__);
8838 			if (rsm->r_in_tmap) {
8839 				TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8840 				rsm->r_in_tmap = 0;
8841 			}
8842 		}
8843 	} else if (start != end){
8844 		/*
8845 		 * The block was already acked.
8846 		 */
8847 		counter_u64_add(rack_sack_skipped_acked, 1);
8848 		moved++;
8849 	}
8850 out:
8851 	if (rsm &&
8852 	    ((rsm->r_flags & RACK_TLP) == 0) &&
8853 	    (rsm->r_flags & RACK_ACKED)) {
8854 		/*
8855 		 * Now can we merge where we worked
8856 		 * with either the previous or
8857 		 * next block?
8858 		 */
8859 		next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8860 		while (next) {
8861 			if (next->r_flags & RACK_TLP)
8862 				break;
8863 			if (next->r_flags & RACK_ACKED) {
8864 			/* yep this and next can be merged */
8865 				rsm = rack_merge_rsm(rack, rsm, next);
8866 				next = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8867 			} else
8868 				break;
8869 		}
8870 		/* Now what about the previous? */
8871 		prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8872 		while (prev) {
8873 			if (prev->r_flags & RACK_TLP)
8874 				break;
8875 			if (prev->r_flags & RACK_ACKED) {
8876 				/* yep the previous and this can be merged */
8877 				rsm = rack_merge_rsm(rack, prev, rsm);
8878 				prev = RB_PREV(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8879 			} else
8880 				break;
8881 		}
8882 	}
8883 	if (used_ref == 0) {
8884 		counter_u64_add(rack_sack_proc_all, 1);
8885 	} else {
8886 		counter_u64_add(rack_sack_proc_short, 1);
8887 	}
8888 	/* Save off the next one for quick reference. */
8889 	if (rsm)
8890 		nrsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8891 	else
8892 		nrsm = NULL;
8893 	*prsm = rack->r_ctl.rc_sacklast = nrsm;
8894 	/* Pass back the moved. */
8895 	*moved_two = moved;
8896 	return (changed);
8897 }
8898 
8899 static void inline
8900 rack_peer_reneges(struct tcp_rack *rack, struct rack_sendmap *rsm, tcp_seq th_ack)
8901 {
8902 	struct rack_sendmap *tmap;
8903 
8904 	tmap = NULL;
8905 	while (rsm && (rsm->r_flags & RACK_ACKED)) {
8906 		/* Its no longer sacked, mark it so */
8907 		rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
8908 #ifdef INVARIANTS
8909 		if (rsm->r_in_tmap) {
8910 			panic("rack:%p rsm:%p flags:0x%x in tmap?",
8911 			      rack, rsm, rsm->r_flags);
8912 		}
8913 #endif
8914 		rsm->r_flags &= ~(RACK_ACKED|RACK_SACK_PASSED|RACK_WAS_SACKPASS);
8915 		/* Rebuild it into our tmap */
8916 		if (tmap == NULL) {
8917 			TAILQ_INSERT_HEAD(&rack->r_ctl.rc_tmap, rsm, r_tnext);
8918 			tmap = rsm;
8919 		} else {
8920 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, tmap, rsm, r_tnext);
8921 			tmap = rsm;
8922 		}
8923 		tmap->r_in_tmap = 1;
8924 		rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
8925 	}
8926 	/*
8927 	 * Now lets possibly clear the sack filter so we start
8928 	 * recognizing sacks that cover this area.
8929 	 */
8930 	sack_filter_clear(&rack->r_ctl.rack_sf, th_ack);
8931 
8932 }
8933 
8934 static void
8935 rack_do_decay(struct tcp_rack *rack)
8936 {
8937 	struct timeval res;
8938 
8939 #define	timersub(tvp, uvp, vvp)						\
8940 	do {								\
8941 		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
8942 		(vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;	\
8943 		if ((vvp)->tv_usec < 0) {				\
8944 			(vvp)->tv_sec--;				\
8945 			(vvp)->tv_usec += 1000000;			\
8946 		}							\
8947 	} while (0)
8948 
8949 	timersub(&rack->r_ctl.act_rcv_time, &rack->r_ctl.rc_last_time_decay, &res);
8950 #undef timersub
8951 
8952 	rack->r_ctl.input_pkt++;
8953 	if ((rack->rc_in_persist) ||
8954 	    (res.tv_sec >= 1) ||
8955 	    (rack->rc_tp->snd_max == rack->rc_tp->snd_una)) {
8956 		/*
8957 		 * Check for decay of non-SAD,
8958 		 * we want all SAD detection metrics to
8959 		 * decay 1/4 per second (or more) passed.
8960 		 */
8961 		uint32_t pkt_delta;
8962 
8963 		pkt_delta = rack->r_ctl.input_pkt - rack->r_ctl.saved_input_pkt;
8964 		/* Update our saved tracking values */
8965 		rack->r_ctl.saved_input_pkt = rack->r_ctl.input_pkt;
8966 		rack->r_ctl.rc_last_time_decay = rack->r_ctl.act_rcv_time;
8967 		/* Now do we escape without decay? */
8968 #ifdef NETFLIX_EXP_DETECTION
8969 		if (rack->rc_in_persist ||
8970 		    (rack->rc_tp->snd_max == rack->rc_tp->snd_una) ||
8971 		    (pkt_delta < tcp_sad_low_pps)){
8972 			/*
8973 			 * We don't decay idle connections
8974 			 * or ones that have a low input pps.
8975 			 */
8976 			return;
8977 		}
8978 		/* Decay the counters */
8979 		rack->r_ctl.ack_count = ctf_decay_count(rack->r_ctl.ack_count,
8980 							tcp_sad_decay_val);
8981 		rack->r_ctl.sack_count = ctf_decay_count(rack->r_ctl.sack_count,
8982 							 tcp_sad_decay_val);
8983 		rack->r_ctl.sack_moved_extra = ctf_decay_count(rack->r_ctl.sack_moved_extra,
8984 							       tcp_sad_decay_val);
8985 		rack->r_ctl.sack_noextra_move = ctf_decay_count(rack->r_ctl.sack_noextra_move,
8986 								tcp_sad_decay_val);
8987 #endif
8988 	}
8989 }
8990 
8991 static void
8992 rack_process_to_cumack(struct tcpcb *tp, struct tcp_rack *rack, register uint32_t th_ack, uint32_t cts, struct tcpopt *to)
8993 {
8994 	struct rack_sendmap *rsm, *rm;
8995 
8996 	/*
8997 	 * The ACK point is advancing to th_ack, we must drop off
8998 	 * the packets in the rack log and calculate any eligble
8999 	 * RTT's.
9000 	 */
9001 	rack->r_wanted_output = 1;
9002 
9003 	/* Tend any TLP that has been marked for 1/2 the seq space (its old)  */
9004 	if ((rack->rc_last_tlp_acked_set == 1)&&
9005 	    (rack->rc_last_tlp_past_cumack == 1) &&
9006 	    (SEQ_GT(rack->r_ctl.last_tlp_acked_start, th_ack))) {
9007 		/*
9008 		 * We have reached the point where our last rack
9009 		 * tlp retransmit sequence is ahead of the cum-ack.
9010 		 * This can only happen when the cum-ack moves all
9011 		 * the way around (its been a full 2^^31+1 bytes
9012 		 * or more since we sent a retransmitted TLP). Lets
9013 		 * turn off the valid flag since its not really valid.
9014 		 *
9015 		 * Note since sack's also turn on this event we have
9016 		 * a complication, we have to wait to age it out until
9017 		 * the cum-ack is by the TLP before checking which is
9018 		 * what the next else clause does.
9019 		 */
9020 		rack_log_dsack_event(rack, 9, __LINE__,
9021 				     rack->r_ctl.last_tlp_acked_start,
9022 				     rack->r_ctl.last_tlp_acked_end);
9023 		rack->rc_last_tlp_acked_set = 0;
9024 		rack->rc_last_tlp_past_cumack = 0;
9025 	} else if ((rack->rc_last_tlp_acked_set == 1) &&
9026 		   (rack->rc_last_tlp_past_cumack == 0) &&
9027 		   (SEQ_GEQ(th_ack, rack->r_ctl.last_tlp_acked_end))) {
9028 		/*
9029 		 * It is safe to start aging TLP's out.
9030 		 */
9031 		rack->rc_last_tlp_past_cumack = 1;
9032 	}
9033 	/* We do the same for the tlp send seq as well */
9034 	if ((rack->rc_last_sent_tlp_seq_valid == 1) &&
9035 	    (rack->rc_last_sent_tlp_past_cumack == 1) &&
9036 	    (SEQ_GT(rack->r_ctl.last_sent_tlp_seq,  th_ack))) {
9037 		rack_log_dsack_event(rack, 9, __LINE__,
9038 				     rack->r_ctl.last_sent_tlp_seq,
9039 				     (rack->r_ctl.last_sent_tlp_seq +
9040 				      rack->r_ctl.last_sent_tlp_len));
9041 		rack->rc_last_sent_tlp_seq_valid = 0;
9042 		rack->rc_last_sent_tlp_past_cumack = 0;
9043 	} else if ((rack->rc_last_sent_tlp_seq_valid == 1) &&
9044 		   (rack->rc_last_sent_tlp_past_cumack == 0) &&
9045 		   (SEQ_GEQ(th_ack, rack->r_ctl.last_sent_tlp_seq))) {
9046 		/*
9047 		 * It is safe to start aging TLP's send.
9048 		 */
9049 		rack->rc_last_sent_tlp_past_cumack = 1;
9050 	}
9051 more:
9052 	rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9053 	if (rsm == NULL) {
9054 		if ((th_ack - 1) == tp->iss) {
9055 			/*
9056 			 * For the SYN incoming case we will not
9057 			 * have called tcp_output for the sending of
9058 			 * the SYN, so there will be no map. All
9059 			 * other cases should probably be a panic.
9060 			 */
9061 			return;
9062 		}
9063 		if (tp->t_flags & TF_SENTFIN) {
9064 			/* if we sent a FIN we often will not have map */
9065 			return;
9066 		}
9067 #ifdef INVARIANTS
9068 		panic("No rack map tp:%p for state:%d ack:%u rack:%p snd_una:%u snd_max:%u snd_nxt:%u\n",
9069 		      tp,
9070 		      tp->t_state, th_ack, rack,
9071 		      tp->snd_una, tp->snd_max, tp->snd_nxt);
9072 #endif
9073 		return;
9074 	}
9075 	if (SEQ_LT(th_ack, rsm->r_start)) {
9076 		/* Huh map is missing this */
9077 #ifdef INVARIANTS
9078 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d\n",
9079 		       rsm->r_start,
9080 		       th_ack, tp->t_state, rack->r_state);
9081 #endif
9082 		return;
9083 	}
9084 	rack_update_rtt(tp, rack, rsm, to, cts, CUM_ACKED, th_ack);
9085 
9086 	/* Now was it a retransmitted TLP? */
9087 	if ((rsm->r_flags & RACK_TLP) &&
9088 	    (rsm->r_rtr_cnt > 1)) {
9089 		/*
9090 		 * Yes, this rsm was a TLP and retransmitted, remember that
9091 		 * since if a DSACK comes back on this we don't want
9092 		 * to think of it as a reordered segment. This may
9093 		 * get updated again with possibly even other TLPs
9094 		 * in flight, but thats ok. Only when we don't send
9095 		 * a retransmitted TLP for 1/2 the sequences space
9096 		 * will it get turned off (above).
9097 		 */
9098 		if (rack->rc_last_tlp_acked_set &&
9099 		    (is_rsm_inside_declared_tlp_block(rack, rsm))) {
9100 			/*
9101 			 * We already turned this on since the end matches,
9102 			 * the previous one was a partially ack now we
9103 			 * are getting another one (maybe all of it).
9104 			 */
9105 			rack_log_dsack_event(rack, 10, __LINE__, rsm->r_start, rsm->r_end);
9106 			/*
9107 			 * Lets make sure we have all of it though.
9108 			 */
9109 			if (SEQ_LT(rsm->r_start, rack->r_ctl.last_tlp_acked_start)) {
9110 				rack->r_ctl.last_tlp_acked_start = rsm->r_start;
9111 				rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
9112 						     rack->r_ctl.last_tlp_acked_end);
9113 			}
9114 			if (SEQ_GT(rsm->r_end, rack->r_ctl.last_tlp_acked_end)) {
9115 				rack->r_ctl.last_tlp_acked_end = rsm->r_end;
9116 				rack_log_dsack_event(rack, 11, __LINE__, rack->r_ctl.last_tlp_acked_start,
9117 						     rack->r_ctl.last_tlp_acked_end);
9118 			}
9119 		} else {
9120 			rack->rc_last_tlp_past_cumack = 1;
9121 			rack->r_ctl.last_tlp_acked_start = rsm->r_start;
9122 			rack->r_ctl.last_tlp_acked_end = rsm->r_end;
9123 			rack->rc_last_tlp_acked_set = 1;
9124 			rack_log_dsack_event(rack, 8, __LINE__, rsm->r_start, rsm->r_end);
9125 		}
9126 	}
9127 	/* Now do we consume the whole thing? */
9128 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
9129 		/* Its all consumed. */
9130 		uint32_t left;
9131 		uint8_t newly_acked;
9132 
9133 		rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_FREE, rsm->r_end, __LINE__);
9134 		rack->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
9135 		rsm->r_rtr_bytes = 0;
9136 		/* Record the time of highest cumack sent */
9137 		rack->r_ctl.rc_gp_cumack_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
9138 		rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
9139 #ifdef INVARIANTS
9140 		if (rm != rsm) {
9141 			panic("removing head in rack:%p rsm:%p rm:%p",
9142 			      rack, rsm, rm);
9143 		}
9144 #endif
9145 		if (rsm->r_in_tmap) {
9146 			TAILQ_REMOVE(&rack->r_ctl.rc_tmap, rsm, r_tnext);
9147 			rsm->r_in_tmap = 0;
9148 		}
9149 		newly_acked = 1;
9150 		if (rsm->r_flags & RACK_ACKED) {
9151 			/*
9152 			 * It was acked on the scoreboard -- remove
9153 			 * it from total
9154 			 */
9155 			rack->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
9156 			newly_acked = 0;
9157 		} else if (rsm->r_flags & RACK_SACK_PASSED) {
9158 			/*
9159 			 * There are segments ACKED on the
9160 			 * scoreboard further up. We are seeing
9161 			 * reordering.
9162 			 */
9163 			rsm->r_flags &= ~RACK_SACK_PASSED;
9164 			counter_u64_add(rack_reorder_seen, 1);
9165 			rsm->r_ack_arrival = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
9166 			rsm->r_flags |= RACK_ACKED;
9167 			rack->r_ctl.rc_reorder_ts = cts;
9168 			if (rack->r_ent_rec_ns) {
9169 				/*
9170 				 * We have sent no more, and we saw an sack
9171 				 * then ack arrive.
9172 				 */
9173 				rack->r_might_revert = 1;
9174 			}
9175 		}
9176 		if ((rsm->r_flags & RACK_TO_REXT) &&
9177 		    (tp->t_flags & TF_RCVD_TSTMP) &&
9178 		    (to->to_flags & TOF_TS) &&
9179 		    (to->to_tsecr != 0) &&
9180 		    (tp->t_flags & TF_PREVVALID)) {
9181 			/*
9182 			 * We can use the timestamp to see
9183 			 * if this retransmission was from the
9184 			 * first transmit. If so we made a mistake.
9185 			 */
9186 			tp->t_flags &= ~TF_PREVVALID;
9187 			if (to->to_tsecr == rack_ts_to_msec(rsm->r_tim_lastsent[0])) {
9188 				/* The first transmit is what this ack is for */
9189 				rack_cong_signal(tp, CC_RTO_ERR, th_ack);
9190 			}
9191 		}
9192 		left = th_ack - rsm->r_end;
9193 		if (rack->app_limited_needs_set && newly_acked)
9194 			rack_need_set_test(tp, rack, rsm, th_ack, __LINE__, RACK_USE_END_OR_THACK);
9195 		/* Free back to zone */
9196 		rack_free(rack, rsm);
9197 		if (left) {
9198 			goto more;
9199 		}
9200 		/* Check for reneging */
9201 		rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9202 		if (rsm && (rsm->r_flags & RACK_ACKED) && (th_ack == rsm->r_start)) {
9203 			/*
9204 			 * The peer has moved snd_una up to
9205 			 * the edge of this send, i.e. one
9206 			 * that it had previously acked. The only
9207 			 * way that can be true if the peer threw
9208 			 * away data (space issues) that it had
9209 			 * previously sacked (else it would have
9210 			 * given us snd_una up to (rsm->r_end).
9211 			 * We need to undo the acked markings here.
9212 			 *
9213 			 * Note we have to look to make sure th_ack is
9214 			 * our rsm->r_start in case we get an old ack
9215 			 * where th_ack is behind snd_una.
9216 			 */
9217 			rack_peer_reneges(rack, rsm, th_ack);
9218 		}
9219 		return;
9220 	}
9221 	if (rsm->r_flags & RACK_ACKED) {
9222 		/*
9223 		 * It was acked on the scoreboard -- remove it from
9224 		 * total for the part being cum-acked.
9225 		 */
9226 		rack->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
9227 	}
9228 	/*
9229 	 * Clear the dup ack count for
9230 	 * the piece that remains.
9231 	 */
9232 	rsm->r_dupack = 0;
9233 	rack_log_retran_reason(rack, rsm, __LINE__, 0, 2);
9234 	if (rsm->r_rtr_bytes) {
9235 		/*
9236 		 * It was retransmitted adjust the
9237 		 * sack holes for what was acked.
9238 		 */
9239 		int ack_am;
9240 
9241 		ack_am = (th_ack - rsm->r_start);
9242 		if (ack_am >= rsm->r_rtr_bytes) {
9243 			rack->r_ctl.rc_holes_rxt -= ack_am;
9244 			rsm->r_rtr_bytes -= ack_am;
9245 		}
9246 	}
9247 	/*
9248 	 * Update where the piece starts and record
9249 	 * the time of send of highest cumack sent.
9250 	 */
9251 	rack->r_ctl.rc_gp_cumack_ts = rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)];
9252 	rack_log_map_chg(tp, rack, NULL, rsm, NULL, MAP_TRIM_HEAD, th_ack, __LINE__);
9253 	/* Now we need to move our offset forward too */
9254 	if (rsm->m && (rsm->orig_m_len != rsm->m->m_len)) {
9255 		/* Fix up the orig_m_len and possibly the mbuf offset */
9256 		rack_adjust_orig_mlen(rsm);
9257 	}
9258 	rsm->soff += (th_ack - rsm->r_start);
9259 	rsm->r_start = th_ack;
9260 	/* Now do we need to move the mbuf fwd too? */
9261 	if (rsm->m) {
9262 		while (rsm->soff >= rsm->m->m_len) {
9263 			rsm->soff -= rsm->m->m_len;
9264 			rsm->m = rsm->m->m_next;
9265 			KASSERT((rsm->m != NULL),
9266 				(" nrsm:%p hit at soff:%u null m",
9267 				 rsm, rsm->soff));
9268 		}
9269 		rsm->orig_m_len = rsm->m->m_len;
9270 	}
9271 	if (rack->app_limited_needs_set)
9272 		rack_need_set_test(tp, rack, rsm, tp->snd_una, __LINE__, RACK_USE_BEG);
9273 }
9274 
9275 static void
9276 rack_handle_might_revert(struct tcpcb *tp, struct tcp_rack *rack)
9277 {
9278 	struct rack_sendmap *rsm;
9279 	int sack_pass_fnd = 0;
9280 
9281 	if (rack->r_might_revert) {
9282 		/*
9283 		 * Ok we have reordering, have not sent anything, we
9284 		 * might want to revert the congestion state if nothing
9285 		 * further has SACK_PASSED on it. Lets check.
9286 		 *
9287 		 * We also get here when we have DSACKs come in for
9288 		 * all the data that we FR'd. Note that a rxt or tlp
9289 		 * timer clears this from happening.
9290 		 */
9291 
9292 		TAILQ_FOREACH(rsm, &rack->r_ctl.rc_tmap, r_tnext) {
9293 			if (rsm->r_flags & RACK_SACK_PASSED) {
9294 				sack_pass_fnd = 1;
9295 				break;
9296 			}
9297 		}
9298 		if (sack_pass_fnd == 0) {
9299 			/*
9300 			 * We went into recovery
9301 			 * incorrectly due to reordering!
9302 			 */
9303 			int orig_cwnd;
9304 
9305 			rack->r_ent_rec_ns = 0;
9306 			orig_cwnd = tp->snd_cwnd;
9307 			tp->snd_cwnd = rack->r_ctl.rc_cwnd_at_erec;
9308 			tp->snd_ssthresh = rack->r_ctl.rc_ssthresh_at_erec;
9309 			tp->snd_recover = tp->snd_una;
9310 			rack_log_to_prr(rack, 14, orig_cwnd);
9311 			EXIT_RECOVERY(tp->t_flags);
9312 		}
9313 		rack->r_might_revert = 0;
9314 	}
9315 }
9316 
9317 #ifdef NETFLIX_EXP_DETECTION
9318 static void
9319 rack_do_detection(struct tcpcb *tp, struct tcp_rack *rack,  uint32_t bytes_this_ack, uint32_t segsiz)
9320 {
9321 	if ((rack->do_detection || tcp_force_detection) &&
9322 	    tcp_sack_to_ack_thresh &&
9323 	    tcp_sack_to_move_thresh &&
9324 	    ((rack->r_ctl.rc_num_maps_alloced > tcp_map_minimum) || rack->sack_attack_disable)) {
9325 		/*
9326 		 * We have thresholds set to find
9327 		 * possible attackers and disable sack.
9328 		 * Check them.
9329 		 */
9330 		uint64_t ackratio, moveratio, movetotal;
9331 
9332 		/* Log detecting */
9333 		rack_log_sad(rack, 1);
9334 		ackratio = (uint64_t)(rack->r_ctl.sack_count);
9335 		ackratio *= (uint64_t)(1000);
9336 		if (rack->r_ctl.ack_count)
9337 			ackratio /= (uint64_t)(rack->r_ctl.ack_count);
9338 		else {
9339 			/* We really should not hit here */
9340 			ackratio = 1000;
9341 		}
9342 		if ((rack->sack_attack_disable == 0) &&
9343 		    (ackratio > rack_highest_sack_thresh_seen))
9344 			rack_highest_sack_thresh_seen = (uint32_t)ackratio;
9345 		movetotal = rack->r_ctl.sack_moved_extra;
9346 		movetotal += rack->r_ctl.sack_noextra_move;
9347 		moveratio = rack->r_ctl.sack_moved_extra;
9348 		moveratio *= (uint64_t)1000;
9349 		if (movetotal)
9350 			moveratio /= movetotal;
9351 		else {
9352 			/* No moves, thats pretty good */
9353 			moveratio = 0;
9354 		}
9355 		if ((rack->sack_attack_disable == 0) &&
9356 		    (moveratio > rack_highest_move_thresh_seen))
9357 			rack_highest_move_thresh_seen = (uint32_t)moveratio;
9358 		if (rack->sack_attack_disable == 0) {
9359 			if ((ackratio > tcp_sack_to_ack_thresh) &&
9360 			    (moveratio > tcp_sack_to_move_thresh)) {
9361 				/* Disable sack processing */
9362 				rack->sack_attack_disable = 1;
9363 				if (rack->r_rep_attack == 0) {
9364 					rack->r_rep_attack = 1;
9365 					counter_u64_add(rack_sack_attacks_detected, 1);
9366 				}
9367 				if (tcp_attack_on_turns_on_logging) {
9368 					/*
9369 					 * Turn on logging, used for debugging
9370 					 * false positives.
9371 					 */
9372 					rack->rc_tp->t_logstate = tcp_attack_on_turns_on_logging;
9373 				}
9374 				/* Clamp the cwnd at flight size */
9375 				rack->r_ctl.rc_saved_cwnd = rack->rc_tp->snd_cwnd;
9376 				rack->rc_tp->snd_cwnd = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
9377 				rack_log_sad(rack, 2);
9378 			}
9379 		} else {
9380 			/* We are sack-disabled check for false positives */
9381 			if ((ackratio <= tcp_restoral_thresh) ||
9382 			    (rack->r_ctl.rc_num_maps_alloced  < tcp_map_minimum)) {
9383 				rack->sack_attack_disable = 0;
9384 				rack_log_sad(rack, 3);
9385 				/* Restart counting */
9386 				rack->r_ctl.sack_count = 0;
9387 				rack->r_ctl.sack_moved_extra = 0;
9388 				rack->r_ctl.sack_noextra_move = 1;
9389 				rack->r_ctl.ack_count = max(1,
9390 				      (bytes_this_ack / segsiz));
9391 
9392 				if (rack->r_rep_reverse == 0) {
9393 					rack->r_rep_reverse = 1;
9394 					counter_u64_add(rack_sack_attacks_reversed, 1);
9395 				}
9396 				/* Restore the cwnd */
9397 				if (rack->r_ctl.rc_saved_cwnd > rack->rc_tp->snd_cwnd)
9398 					rack->rc_tp->snd_cwnd = rack->r_ctl.rc_saved_cwnd;
9399 			}
9400 		}
9401 	}
9402 }
9403 #endif
9404 
9405 static void
9406 rack_note_dsack(struct tcp_rack *rack, tcp_seq start, tcp_seq end)
9407 {
9408 
9409 	uint32_t am, l_end;
9410 
9411 	if (SEQ_GT(end, start))
9412 		am = end - start;
9413 	else
9414 		am = 0;
9415 	if ((rack->rc_last_tlp_acked_set ) &&
9416 	    (SEQ_GEQ(start, rack->r_ctl.last_tlp_acked_start)) &&
9417 	    (SEQ_LEQ(end, rack->r_ctl.last_tlp_acked_end))) {
9418 		/*
9419 		 * The DSACK is because of a TLP which we don't
9420 		 * do anything with the reordering window over since
9421 		 * it was not reordering that caused the DSACK but
9422 		 * our previous retransmit TLP.
9423 		 */
9424 		rack_log_dsack_event(rack, 7, __LINE__, start, end);
9425 		goto skip_dsack_round;
9426 	}
9427 	if (rack->rc_last_sent_tlp_seq_valid) {
9428 		l_end = rack->r_ctl.last_sent_tlp_seq + rack->r_ctl.last_sent_tlp_len;
9429 		if (SEQ_GEQ(start, rack->r_ctl.last_sent_tlp_seq) &&
9430 		    (SEQ_LEQ(end, l_end))) {
9431 			/*
9432 			 * This dsack is from the last sent TLP, ignore it
9433 			 * for reordering purposes.
9434 			 */
9435 			rack_log_dsack_event(rack, 7, __LINE__, start, end);
9436 			goto skip_dsack_round;
9437 		}
9438 	}
9439 	if (rack->rc_dsack_round_seen == 0) {
9440 		rack->rc_dsack_round_seen = 1;
9441 		rack->r_ctl.dsack_round_end = rack->rc_tp->snd_max;
9442 		rack->r_ctl.num_dsack++;
9443 		rack->r_ctl.dsack_persist = 16;	/* 16 is from the standard */
9444 		rack_log_dsack_event(rack, 2, __LINE__, 0, 0);
9445 	}
9446 skip_dsack_round:
9447 	/*
9448 	 * We keep track of how many DSACK blocks we get
9449 	 * after a recovery incident.
9450 	 */
9451 	rack->r_ctl.dsack_byte_cnt += am;
9452 	if (!IN_FASTRECOVERY(rack->rc_tp->t_flags) &&
9453 	    rack->r_ctl.retran_during_recovery &&
9454 	    (rack->r_ctl.dsack_byte_cnt >= rack->r_ctl.retran_during_recovery)) {
9455 		/*
9456 		 * False recovery most likely culprit is reordering. If
9457 		 * nothing else is missing we need to revert.
9458 		 */
9459 		rack->r_might_revert = 1;
9460 		rack_handle_might_revert(rack->rc_tp, rack);
9461 		rack->r_might_revert = 0;
9462 		rack->r_ctl.retran_during_recovery = 0;
9463 		rack->r_ctl.dsack_byte_cnt = 0;
9464 	}
9465 }
9466 
9467 static void
9468 rack_update_prr(struct tcpcb *tp, struct tcp_rack *rack, uint32_t changed, tcp_seq th_ack)
9469 {
9470 	/* Deal with changed and PRR here (in recovery only) */
9471 	uint32_t pipe, snd_una;
9472 
9473 	rack->r_ctl.rc_prr_delivered += changed;
9474 
9475 	if (sbavail(&rack->rc_inp->inp_socket->so_snd) <= (tp->snd_max - tp->snd_una)) {
9476 		/*
9477 		 * It is all outstanding, we are application limited
9478 		 * and thus we don't need more room to send anything.
9479 		 * Note we use tp->snd_una here and not th_ack because
9480 		 * the data as yet not been cut from the sb.
9481 		 */
9482 		rack->r_ctl.rc_prr_sndcnt = 0;
9483 		return;
9484 	}
9485 	/* Compute prr_sndcnt */
9486 	if (SEQ_GT(tp->snd_una, th_ack)) {
9487 		snd_una = tp->snd_una;
9488 	} else {
9489 		snd_una = th_ack;
9490 	}
9491 	pipe = ((tp->snd_max - snd_una) - rack->r_ctl.rc_sacked) + rack->r_ctl.rc_holes_rxt;
9492 	if (pipe > tp->snd_ssthresh) {
9493 		long sndcnt;
9494 
9495 		sndcnt = rack->r_ctl.rc_prr_delivered * tp->snd_ssthresh;
9496 		if (rack->r_ctl.rc_prr_recovery_fs > 0)
9497 			sndcnt /= (long)rack->r_ctl.rc_prr_recovery_fs;
9498 		else {
9499 			rack->r_ctl.rc_prr_sndcnt = 0;
9500 			rack_log_to_prr(rack, 9, 0);
9501 			sndcnt = 0;
9502 		}
9503 		sndcnt++;
9504 		if (sndcnt > (long)rack->r_ctl.rc_prr_out)
9505 			sndcnt -= rack->r_ctl.rc_prr_out;
9506 		else
9507 			sndcnt = 0;
9508 		rack->r_ctl.rc_prr_sndcnt = sndcnt;
9509 		rack_log_to_prr(rack, 10, 0);
9510 	} else {
9511 		uint32_t limit;
9512 
9513 		if (rack->r_ctl.rc_prr_delivered > rack->r_ctl.rc_prr_out)
9514 			limit = (rack->r_ctl.rc_prr_delivered - rack->r_ctl.rc_prr_out);
9515 		else
9516 			limit = 0;
9517 		if (changed > limit)
9518 			limit = changed;
9519 		limit += ctf_fixed_maxseg(tp);
9520 		if (tp->snd_ssthresh > pipe) {
9521 			rack->r_ctl.rc_prr_sndcnt = min((tp->snd_ssthresh - pipe), limit);
9522 			rack_log_to_prr(rack, 11, 0);
9523 		} else {
9524 			rack->r_ctl.rc_prr_sndcnt = min(0, limit);
9525 			rack_log_to_prr(rack, 12, 0);
9526 		}
9527 	}
9528 }
9529 
9530 static void
9531 rack_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th, int entered_recovery, int dup_ack_struck)
9532 {
9533 	uint32_t changed;
9534 	struct tcp_rack *rack;
9535 	struct rack_sendmap *rsm;
9536 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
9537 	register uint32_t th_ack;
9538 	int32_t i, j, k, num_sack_blks = 0;
9539 	uint32_t cts, acked, ack_point, sack_changed = 0;
9540 	int loop_start = 0, moved_two = 0;
9541 	uint32_t tsused;
9542 
9543 
9544 	INP_WLOCK_ASSERT(tp->t_inpcb);
9545 	if (th->th_flags & TH_RST) {
9546 		/* We don't log resets */
9547 		return;
9548 	}
9549 	rack = (struct tcp_rack *)tp->t_fb_ptr;
9550 	cts = tcp_get_usecs(NULL);
9551 	rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
9552 	changed = 0;
9553 	th_ack = th->th_ack;
9554 	if (rack->sack_attack_disable == 0)
9555 		rack_do_decay(rack);
9556 	if (BYTES_THIS_ACK(tp, th) >= ctf_fixed_maxseg(rack->rc_tp)) {
9557 		/*
9558 		 * You only get credit for
9559 		 * MSS and greater (and you get extra
9560 		 * credit for larger cum-ack moves).
9561 		 */
9562 		int ac;
9563 
9564 		ac = BYTES_THIS_ACK(tp, th) / ctf_fixed_maxseg(rack->rc_tp);
9565 		rack->r_ctl.ack_count += ac;
9566 		counter_u64_add(rack_ack_total, ac);
9567 	}
9568 	if (rack->r_ctl.ack_count > 0xfff00000) {
9569 		/*
9570 		 * reduce the number to keep us under
9571 		 * a uint32_t.
9572 		 */
9573 		rack->r_ctl.ack_count /= 2;
9574 		rack->r_ctl.sack_count /= 2;
9575 	}
9576 	if (SEQ_GT(th_ack, tp->snd_una)) {
9577 		rack_log_progress_event(rack, tp, ticks, PROGRESS_UPDATE, __LINE__);
9578 		tp->t_acktime = ticks;
9579 	}
9580 	if (rsm && SEQ_GT(th_ack, rsm->r_start))
9581 		changed = th_ack - rsm->r_start;
9582 	if (changed) {
9583 		rack_process_to_cumack(tp, rack, th_ack, cts, to);
9584 	}
9585 	if ((to->to_flags & TOF_SACK) == 0) {
9586 		/* We are done nothing left and no sack. */
9587 		rack_handle_might_revert(tp, rack);
9588 		/*
9589 		 * For cases where we struck a dup-ack
9590 		 * with no SACK, add to the changes so
9591 		 * PRR will work right.
9592 		 */
9593 		if (dup_ack_struck && (changed == 0)) {
9594 			changed += ctf_fixed_maxseg(rack->rc_tp);
9595 		}
9596 		goto out;
9597 	}
9598 	/* Sack block processing */
9599 	if (SEQ_GT(th_ack, tp->snd_una))
9600 		ack_point = th_ack;
9601 	else
9602 		ack_point = tp->snd_una;
9603 	for (i = 0; i < to->to_nsacks; i++) {
9604 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
9605 		      &sack, sizeof(sack));
9606 		sack.start = ntohl(sack.start);
9607 		sack.end = ntohl(sack.end);
9608 		if (SEQ_GT(sack.end, sack.start) &&
9609 		    SEQ_GT(sack.start, ack_point) &&
9610 		    SEQ_LT(sack.start, tp->snd_max) &&
9611 		    SEQ_GT(sack.end, ack_point) &&
9612 		    SEQ_LEQ(sack.end, tp->snd_max)) {
9613 			sack_blocks[num_sack_blks] = sack;
9614 			num_sack_blks++;
9615 		} else if (SEQ_LEQ(sack.start, th_ack) &&
9616 			   SEQ_LEQ(sack.end, th_ack)) {
9617 #ifdef NETFLIX_STATS
9618 			/*
9619 			 * Its a D-SACK block.
9620 			 */
9621 			tcp_record_dsack(sack.start, sack.end);
9622 #endif
9623 			rack_note_dsack(rack, sack.start, sack.end);
9624 		}
9625 	}
9626 	if (rack->rc_dsack_round_seen) {
9627 		/* Is the dsack roound over? */
9628 		if (SEQ_GEQ(th_ack, rack->r_ctl.dsack_round_end)) {
9629 			/* Yes it is */
9630 			rack->rc_dsack_round_seen = 0;
9631 			rack_log_dsack_event(rack, 3, __LINE__, 0, 0);
9632 		}
9633 	}
9634 	/*
9635 	 * Sort the SACK blocks so we can update the rack scoreboard with
9636 	 * just one pass.
9637 	 */
9638 	num_sack_blks = sack_filter_blks(&rack->r_ctl.rack_sf, sack_blocks,
9639 					 num_sack_blks, th->th_ack);
9640 	ctf_log_sack_filter(rack->rc_tp, num_sack_blks, sack_blocks);
9641 	if (num_sack_blks == 0) {
9642 		/* Nothing to sack (DSACKs?) */
9643 		goto out_with_totals;
9644 	}
9645 	if (num_sack_blks < 2) {
9646 		/* Only one, we don't need to sort */
9647 		goto do_sack_work;
9648 	}
9649 	/* Sort the sacks */
9650 	for (i = 0; i < num_sack_blks; i++) {
9651 		for (j = i + 1; j < num_sack_blks; j++) {
9652 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
9653 				sack = sack_blocks[i];
9654 				sack_blocks[i] = sack_blocks[j];
9655 				sack_blocks[j] = sack;
9656 			}
9657 		}
9658 	}
9659 	/*
9660 	 * Now are any of the sack block ends the same (yes some
9661 	 * implementations send these)?
9662 	 */
9663 again:
9664 	if (num_sack_blks == 0)
9665 		goto out_with_totals;
9666 	if (num_sack_blks > 1) {
9667 		for (i = 0; i < num_sack_blks; i++) {
9668 			for (j = i + 1; j < num_sack_blks; j++) {
9669 				if (sack_blocks[i].end == sack_blocks[j].end) {
9670 					/*
9671 					 * Ok these two have the same end we
9672 					 * want the smallest end and then
9673 					 * throw away the larger and start
9674 					 * again.
9675 					 */
9676 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
9677 						/*
9678 						 * The second block covers
9679 						 * more area use that
9680 						 */
9681 						sack_blocks[i].start = sack_blocks[j].start;
9682 					}
9683 					/*
9684 					 * Now collapse out the dup-sack and
9685 					 * lower the count
9686 					 */
9687 					for (k = (j + 1); k < num_sack_blks; k++) {
9688 						sack_blocks[j].start = sack_blocks[k].start;
9689 						sack_blocks[j].end = sack_blocks[k].end;
9690 						j++;
9691 					}
9692 					num_sack_blks--;
9693 					goto again;
9694 				}
9695 			}
9696 		}
9697 	}
9698 do_sack_work:
9699 	/*
9700 	 * First lets look to see if
9701 	 * we have retransmitted and
9702 	 * can use the transmit next?
9703 	 */
9704 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
9705 	if (rsm &&
9706 	    SEQ_GT(sack_blocks[0].end, rsm->r_start) &&
9707 	    SEQ_LT(sack_blocks[0].start, rsm->r_end)) {
9708 		/*
9709 		 * We probably did the FR and the next
9710 		 * SACK in continues as we would expect.
9711 		 */
9712 		acked = rack_proc_sack_blk(tp, rack, &sack_blocks[0], to, &rsm, cts, &moved_two);
9713 		if (acked) {
9714 			rack->r_wanted_output = 1;
9715 			changed += acked;
9716 			sack_changed += acked;
9717 		}
9718 		if (num_sack_blks == 1) {
9719 			/*
9720 			 * This is what we would expect from
9721 			 * a normal implementation to happen
9722 			 * after we have retransmitted the FR,
9723 			 * i.e the sack-filter pushes down
9724 			 * to 1 block and the next to be retransmitted
9725 			 * is the sequence in the sack block (has more
9726 			 * are acked). Count this as ACK'd data to boost
9727 			 * up the chances of recovering any false positives.
9728 			 */
9729 			rack->r_ctl.ack_count += (acked / ctf_fixed_maxseg(rack->rc_tp));
9730 			counter_u64_add(rack_ack_total, (acked / ctf_fixed_maxseg(rack->rc_tp)));
9731 			counter_u64_add(rack_express_sack, 1);
9732 			if (rack->r_ctl.ack_count > 0xfff00000) {
9733 				/*
9734 				 * reduce the number to keep us under
9735 				 * a uint32_t.
9736 				 */
9737 				rack->r_ctl.ack_count /= 2;
9738 				rack->r_ctl.sack_count /= 2;
9739 			}
9740 			goto out_with_totals;
9741 		} else {
9742 			/*
9743 			 * Start the loop through the
9744 			 * rest of blocks, past the first block.
9745 			 */
9746 			moved_two = 0;
9747 			loop_start = 1;
9748 		}
9749 	}
9750 	/* Its a sack of some sort */
9751 	rack->r_ctl.sack_count++;
9752 	if (rack->r_ctl.sack_count > 0xfff00000) {
9753 		/*
9754 		 * reduce the number to keep us under
9755 		 * a uint32_t.
9756 		 */
9757 		rack->r_ctl.ack_count /= 2;
9758 		rack->r_ctl.sack_count /= 2;
9759 	}
9760 	counter_u64_add(rack_sack_total, 1);
9761 	if (rack->sack_attack_disable) {
9762 		/* An attacker disablement is in place */
9763 		if (num_sack_blks > 1) {
9764 			rack->r_ctl.sack_count += (num_sack_blks - 1);
9765 			rack->r_ctl.sack_moved_extra++;
9766 			counter_u64_add(rack_move_some, 1);
9767 			if (rack->r_ctl.sack_moved_extra > 0xfff00000) {
9768 				rack->r_ctl.sack_moved_extra /= 2;
9769 				rack->r_ctl.sack_noextra_move /= 2;
9770 			}
9771 		}
9772 		goto out;
9773 	}
9774 	rsm = rack->r_ctl.rc_sacklast;
9775 	for (i = loop_start; i < num_sack_blks; i++) {
9776 		acked = rack_proc_sack_blk(tp, rack, &sack_blocks[i], to, &rsm, cts, &moved_two);
9777 		if (acked) {
9778 			rack->r_wanted_output = 1;
9779 			changed += acked;
9780 			sack_changed += acked;
9781 		}
9782 		if (moved_two) {
9783 			/*
9784 			 * If we did not get a SACK for at least a MSS and
9785 			 * had to move at all, or if we moved more than our
9786 			 * threshold, it counts against the "extra" move.
9787 			 */
9788 			rack->r_ctl.sack_moved_extra += moved_two;
9789 			counter_u64_add(rack_move_some, 1);
9790 		} else {
9791 			/*
9792 			 * else we did not have to move
9793 			 * any more than we would expect.
9794 			 */
9795 			rack->r_ctl.sack_noextra_move++;
9796 			counter_u64_add(rack_move_none, 1);
9797 		}
9798 		if (moved_two && (acked < ctf_fixed_maxseg(rack->rc_tp))) {
9799 			/*
9800 			 * If the SACK was not a full MSS then
9801 			 * we add to sack_count the number of
9802 			 * MSS's (or possibly more than
9803 			 * a MSS if its a TSO send) we had to skip by.
9804 			 */
9805 			rack->r_ctl.sack_count += moved_two;
9806 			counter_u64_add(rack_sack_total, moved_two);
9807 		}
9808 		/*
9809 		 * Now we need to setup for the next
9810 		 * round. First we make sure we won't
9811 		 * exceed the size of our uint32_t on
9812 		 * the various counts, and then clear out
9813 		 * moved_two.
9814 		 */
9815 		if ((rack->r_ctl.sack_moved_extra > 0xfff00000) ||
9816 		    (rack->r_ctl.sack_noextra_move > 0xfff00000)) {
9817 			rack->r_ctl.sack_moved_extra /= 2;
9818 			rack->r_ctl.sack_noextra_move /= 2;
9819 		}
9820 		if (rack->r_ctl.sack_count > 0xfff00000) {
9821 			rack->r_ctl.ack_count /= 2;
9822 			rack->r_ctl.sack_count /= 2;
9823 		}
9824 		moved_two = 0;
9825 	}
9826 out_with_totals:
9827 	if (num_sack_blks > 1) {
9828 		/*
9829 		 * You get an extra stroke if
9830 		 * you have more than one sack-blk, this
9831 		 * could be where we are skipping forward
9832 		 * and the sack-filter is still working, or
9833 		 * it could be an attacker constantly
9834 		 * moving us.
9835 		 */
9836 		rack->r_ctl.sack_moved_extra++;
9837 		counter_u64_add(rack_move_some, 1);
9838 	}
9839 out:
9840 #ifdef NETFLIX_EXP_DETECTION
9841 	rack_do_detection(tp, rack, BYTES_THIS_ACK(tp, th), ctf_fixed_maxseg(rack->rc_tp));
9842 #endif
9843 	if (changed) {
9844 		/* Something changed cancel the rack timer */
9845 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
9846 	}
9847 	tsused = tcp_get_usecs(NULL);
9848 	rsm = tcp_rack_output(tp, rack, tsused);
9849 	if ((!IN_FASTRECOVERY(tp->t_flags)) &&
9850 	    rsm) {
9851 		/* Enter recovery */
9852 		rack->r_ctl.rc_rsm_start = rsm->r_start;
9853 		rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
9854 		rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
9855 		entered_recovery = 1;
9856 		rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
9857 		/*
9858 		 * When we enter recovery we need to assure we send
9859 		 * one packet.
9860 		 */
9861 		if (rack->rack_no_prr == 0) {
9862 			rack->r_ctl.rc_prr_sndcnt = ctf_fixed_maxseg(tp);
9863 			rack_log_to_prr(rack, 8, 0);
9864 		}
9865 		rack->r_timer_override = 1;
9866 		rack->r_early = 0;
9867 		rack->r_ctl.rc_agg_early = 0;
9868 	} else if (IN_FASTRECOVERY(tp->t_flags) &&
9869 		   rsm &&
9870 		   (rack->r_rr_config == 3)) {
9871 		/*
9872 		 * Assure we can output and we get no
9873 		 * remembered pace time except the retransmit.
9874 		 */
9875 		rack->r_timer_override = 1;
9876 		rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
9877 		rack->r_ctl.rc_resend = rsm;
9878 	}
9879 	if (IN_FASTRECOVERY(tp->t_flags) &&
9880 	    (rack->rack_no_prr == 0) &&
9881 	    (entered_recovery == 0)) {
9882 		rack_update_prr(tp, rack, changed, th_ack);
9883 		if ((rsm && (rack->r_ctl.rc_prr_sndcnt >= ctf_fixed_maxseg(tp)) &&
9884 		     ((rack->rc_inp->inp_in_hpts == 0) &&
9885 		      ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0)))) {
9886 			/*
9887 			 * If you are pacing output you don't want
9888 			 * to override.
9889 			 */
9890 			rack->r_early = 0;
9891 			rack->r_ctl.rc_agg_early = 0;
9892 			rack->r_timer_override = 1;
9893 		}
9894 	}
9895 }
9896 
9897 static void
9898 rack_strike_dupack(struct tcp_rack *rack)
9899 {
9900 	struct rack_sendmap *rsm;
9901 
9902 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
9903 	while (rsm && (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
9904 		rsm = TAILQ_NEXT(rsm, r_tnext);
9905 	}
9906 	if (rsm && (rsm->r_dupack < 0xff)) {
9907 		rsm->r_dupack++;
9908 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD) {
9909 			struct timeval tv;
9910 			uint32_t cts;
9911 			/*
9912 			 * Here we see if we need to retransmit. For
9913 			 * a SACK type connection if enough time has passed
9914 			 * we will get a return of the rsm. For a non-sack
9915 			 * connection we will get the rsm returned if the
9916 			 * dupack value is 3 or more.
9917 			 */
9918 			cts = tcp_get_usecs(&tv);
9919 			rack->r_ctl.rc_resend = tcp_rack_output(rack->rc_tp, rack, cts);
9920 			if (rack->r_ctl.rc_resend != NULL) {
9921 				if (!IN_FASTRECOVERY(rack->rc_tp->t_flags)) {
9922 					rack_cong_signal(rack->rc_tp, CC_NDUPACK,
9923 							 rack->rc_tp->snd_una);
9924 				}
9925 				rack->r_wanted_output = 1;
9926 				rack->r_timer_override = 1;
9927 				rack_log_retran_reason(rack, rsm, __LINE__, 1, 3);
9928 			}
9929 		} else {
9930 			rack_log_retran_reason(rack, rsm, __LINE__, 0, 3);
9931 		}
9932 	}
9933 }
9934 
9935 static void
9936 rack_check_bottom_drag(struct tcpcb *tp,
9937 		       struct tcp_rack *rack,
9938 		       struct socket *so, int32_t acked)
9939 {
9940 	uint32_t segsiz, minseg;
9941 
9942 	segsiz = ctf_fixed_maxseg(tp);
9943 	minseg = segsiz;
9944 
9945 	if (tp->snd_max == tp->snd_una) {
9946 		/*
9947 		 * We are doing dynamic pacing and we are way
9948 		 * under. Basically everything got acked while
9949 		 * we were still waiting on the pacer to expire.
9950 		 *
9951 		 * This means we need to boost the b/w in
9952 		 * addition to any earlier boosting of
9953 		 * the multipler.
9954 		 */
9955 		rack->rc_dragged_bottom = 1;
9956 		rack_validate_multipliers_at_or_above100(rack);
9957 		/*
9958 		 * Lets use the segment bytes acked plus
9959 		 * the lowest RTT seen as the basis to
9960 		 * form a b/w estimate. This will be off
9961 		 * due to the fact that the true estimate
9962 		 * should be around 1/2 the time of the RTT
9963 		 * but we can settle for that.
9964 		 */
9965 		if ((rack->r_ctl.rack_rs.rs_flags & RACK_RTT_VALID) &&
9966 		    acked) {
9967 			uint64_t bw, calc_bw, rtt;
9968 
9969 			rtt = rack->r_ctl.rack_rs.rs_us_rtt;
9970 			if (rtt == 0) {
9971 				/* no us sample is there a ms one? */
9972 				if (rack->r_ctl.rack_rs.rs_rtt_lowest) {
9973 					rtt = rack->r_ctl.rack_rs.rs_rtt_lowest;
9974 				} else {
9975 					goto no_measurement;
9976 				}
9977 			}
9978 			bw = acked;
9979 			calc_bw = bw * 1000000;
9980 			calc_bw /= rtt;
9981 			if (rack->r_ctl.last_max_bw &&
9982 			    (rack->r_ctl.last_max_bw < calc_bw)) {
9983 				/*
9984 				 * If we have a last calculated max bw
9985 				 * enforce it.
9986 				 */
9987 				calc_bw = rack->r_ctl.last_max_bw;
9988 			}
9989 			/* now plop it in */
9990 			if (rack->rc_gp_filled == 0) {
9991 				if (calc_bw > ONE_POINT_TWO_MEG) {
9992 					/*
9993 					 * If we have no measurement
9994 					 * don't let us set in more than
9995 					 * 1.2Mbps. If we are still too
9996 					 * low after pacing with this we
9997 					 * will hopefully have a max b/w
9998 					 * available to sanity check things.
9999 					 */
10000 					calc_bw = ONE_POINT_TWO_MEG;
10001 				}
10002 				rack->r_ctl.rc_rtt_diff = 0;
10003 				rack->r_ctl.gp_bw = calc_bw;
10004 				rack->rc_gp_filled = 1;
10005 				if (rack->r_ctl.num_measurements < RACK_REQ_AVG)
10006 					rack->r_ctl.num_measurements = RACK_REQ_AVG;
10007 				rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
10008 			} else if (calc_bw > rack->r_ctl.gp_bw) {
10009 				rack->r_ctl.rc_rtt_diff = 0;
10010 				if (rack->r_ctl.num_measurements < RACK_REQ_AVG)
10011 					rack->r_ctl.num_measurements = RACK_REQ_AVG;
10012 				rack->r_ctl.gp_bw = calc_bw;
10013 				rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
10014 			} else
10015 				rack_increase_bw_mul(rack, -1, 0, 0, 1);
10016 			if ((rack->gp_ready == 0) &&
10017 			    (rack->r_ctl.num_measurements >= rack->r_ctl.req_measurements)) {
10018 				/* We have enough measurements now */
10019 				rack->gp_ready = 1;
10020 				rack_set_cc_pacing(rack);
10021 				if (rack->defer_options)
10022 					rack_apply_deferred_options(rack);
10023 			}
10024 			/*
10025 			 * For acks over 1mss we do a extra boost to simulate
10026 			 * where we would get 2 acks (we want 110 for the mul).
10027 			 */
10028 			if (acked > segsiz)
10029 				rack_increase_bw_mul(rack, -1, 0, 0, 1);
10030 		} else {
10031 			/*
10032 			 * zero rtt possibly?, settle for just an old increase.
10033 			 */
10034 no_measurement:
10035 			rack_increase_bw_mul(rack, -1, 0, 0, 1);
10036 		}
10037 	} else if ((IN_FASTRECOVERY(tp->t_flags) == 0) &&
10038 		   (sbavail(&so->so_snd) > max((segsiz * (4 + rack_req_segs)),
10039 					       minseg)) &&
10040 		   (rack->r_ctl.cwnd_to_use > max((segsiz * (rack_req_segs + 2)), minseg)) &&
10041 		   (tp->snd_wnd > max((segsiz * (rack_req_segs + 2)), minseg)) &&
10042 		   (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) <=
10043 		    (segsiz * rack_req_segs))) {
10044 		/*
10045 		 * We are doing dynamic GP pacing and
10046 		 * we have everything except 1MSS or less
10047 		 * bytes left out. We are still pacing away.
10048 		 * And there is data that could be sent, This
10049 		 * means we are inserting delayed ack time in
10050 		 * our measurements because we are pacing too slow.
10051 		 */
10052 		rack_validate_multipliers_at_or_above100(rack);
10053 		rack->rc_dragged_bottom = 1;
10054 		rack_increase_bw_mul(rack, -1, 0, 0, 1);
10055 	}
10056 }
10057 
10058 
10059 
10060 static void
10061 rack_gain_for_fastoutput(struct tcp_rack *rack, struct tcpcb *tp, struct socket *so, uint32_t acked_amount)
10062 {
10063 	/*
10064 	 * The fast output path is enabled and we
10065 	 * have moved the cumack forward. Lets see if
10066 	 * we can expand forward the fast path length by
10067 	 * that amount. What we would ideally like to
10068 	 * do is increase the number of bytes in the
10069 	 * fast path block (left_to_send) by the
10070 	 * acked amount. However we have to gate that
10071 	 * by two factors:
10072 	 * 1) The amount outstanding and the rwnd of the peer
10073 	 *    (i.e. we don't want to exceed the rwnd of the peer).
10074 	 *    <and>
10075 	 * 2) The amount of data left in the socket buffer (i.e.
10076 	 *    we can't send beyond what is in the buffer).
10077 	 *
10078 	 * Note that this does not take into account any increase
10079 	 * in the cwnd. We will only extend the fast path by
10080 	 * what was acked.
10081 	 */
10082 	uint32_t new_total, gating_val;
10083 
10084 	new_total = acked_amount + rack->r_ctl.fsb.left_to_send;
10085 	gating_val = min((sbavail(&so->so_snd) - (tp->snd_max - tp->snd_una)),
10086 			 (tp->snd_wnd - (tp->snd_max - tp->snd_una)));
10087 	if (new_total <= gating_val) {
10088 		/* We can increase left_to_send by the acked amount */
10089 		counter_u64_add(rack_extended_rfo, 1);
10090 		rack->r_ctl.fsb.left_to_send = new_total;
10091 		KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(&rack->rc_inp->inp_socket->so_snd) - (tp->snd_max - tp->snd_una))),
10092 			("rack:%p left_to_send:%u sbavail:%u out:%u",
10093 			 rack, rack->r_ctl.fsb.left_to_send,
10094 			 sbavail(&rack->rc_inp->inp_socket->so_snd),
10095 			 (tp->snd_max - tp->snd_una)));
10096 
10097 	}
10098 }
10099 
10100 static void
10101 rack_adjust_sendmap(struct tcp_rack *rack, struct sockbuf *sb, tcp_seq snd_una)
10102 {
10103 	/*
10104 	 * Here any sendmap entry that points to the
10105 	 * beginning mbuf must be adjusted to the correct
10106 	 * offset. This must be called with:
10107 	 * 1) The socket buffer locked
10108 	 * 2) snd_una adjusted to its new postion.
10109 	 *
10110 	 * Note that (2) implies rack_ack_received has also
10111 	 * been called.
10112 	 *
10113 	 * We grab the first mbuf in the socket buffer and
10114 	 * then go through the front of the sendmap, recalculating
10115 	 * the stored offset for any sendmap entry that has
10116 	 * that mbuf. We must use the sb functions to do this
10117 	 * since its possible an add was done has well as
10118 	 * the subtraction we may have just completed. This should
10119 	 * not be a penalty though, since we just referenced the sb
10120 	 * to go in and trim off the mbufs that we freed (of course
10121 	 * there will be a penalty for the sendmap references though).
10122 	 */
10123 	struct mbuf *m;
10124 	struct rack_sendmap *rsm;
10125 
10126 	SOCKBUF_LOCK_ASSERT(sb);
10127 	m = sb->sb_mb;
10128 	rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
10129 	if ((rsm == NULL) || (m == NULL)) {
10130 		/* Nothing outstanding */
10131 		return;
10132 	}
10133 	while (rsm->m && (rsm->m == m)) {
10134 		/* one to adjust */
10135 #ifdef INVARIANTS
10136 		struct mbuf *tm;
10137 		uint32_t soff;
10138 
10139 		tm = sbsndmbuf(sb, (rsm->r_start - snd_una), &soff);
10140 		if (rsm->orig_m_len != m->m_len) {
10141 			rack_adjust_orig_mlen(rsm);
10142 		}
10143 		if (rsm->soff != soff) {
10144 			/*
10145 			 * This is not a fatal error, we anticipate it
10146 			 * might happen (the else code), so we count it here
10147 			 * so that under invariant we can see that it really
10148 			 * does happen.
10149 			 */
10150 			counter_u64_add(rack_adjust_map_bw, 1);
10151 		}
10152 		rsm->m = tm;
10153 		rsm->soff = soff;
10154 		if (tm)
10155 			rsm->orig_m_len = rsm->m->m_len;
10156 		else
10157 			rsm->orig_m_len = 0;
10158 #else
10159 		rsm->m = sbsndmbuf(sb, (rsm->r_start - snd_una), &rsm->soff);
10160 		if (rsm->m)
10161 			rsm->orig_m_len = rsm->m->m_len;
10162 		else
10163 			rsm->orig_m_len = 0;
10164 #endif
10165 		rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
10166 			      rsm);
10167 		if (rsm == NULL)
10168 			break;
10169 	}
10170 }
10171 
10172 /*
10173  * Return value of 1, we do not need to call rack_process_data().
10174  * return value of 0, rack_process_data can be called.
10175  * For ret_val if its 0 the TCP is locked, if its non-zero
10176  * its unlocked and probably unsafe to touch the TCB.
10177  */
10178 static int
10179 rack_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
10180     struct tcpcb *tp, struct tcpopt *to,
10181     uint32_t tiwin, int32_t tlen,
10182     int32_t * ofia, int32_t thflags, int32_t *ret_val)
10183 {
10184 	int32_t ourfinisacked = 0;
10185 	int32_t nsegs, acked_amount;
10186 	int32_t acked;
10187 	struct mbuf *mfree;
10188 	struct tcp_rack *rack;
10189 	int32_t under_pacing = 0;
10190 	int32_t recovery = 0;
10191 
10192 	rack = (struct tcp_rack *)tp->t_fb_ptr;
10193 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
10194 		__ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val,
10195 				      &rack->r_ctl.challenge_ack_ts,
10196 				      &rack->r_ctl.challenge_ack_cnt);
10197 		rack->r_wanted_output = 1;
10198 		return (1);
10199 	}
10200 	if (rack->gp_ready &&
10201 	    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
10202 		under_pacing = 1;
10203 	}
10204 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
10205 		int in_rec, dup_ack_struck = 0;
10206 
10207 		in_rec = IN_FASTRECOVERY(tp->t_flags);
10208 		if (rack->rc_in_persist) {
10209 			tp->t_rxtshift = 0;
10210 			RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
10211 				      rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
10212 		}
10213 		if ((th->th_ack == tp->snd_una) &&
10214 		    (tiwin == tp->snd_wnd) &&
10215 		    ((to->to_flags & TOF_SACK) == 0)) {
10216 			rack_strike_dupack(rack);
10217 			dup_ack_struck = 1;
10218 		}
10219 		rack_log_ack(tp, to, th, ((in_rec == 0) && IN_FASTRECOVERY(tp->t_flags)), dup_ack_struck);
10220 	}
10221 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
10222 		/*
10223 		 * Old ack, behind (or duplicate to) the last one rcv'd
10224 		 * Note: We mark reordering is occuring if its
10225 		 * less than and we have not closed our window.
10226 		 */
10227 		if (SEQ_LT(th->th_ack, tp->snd_una) && (sbspace(&so->so_rcv) > ctf_fixed_maxseg(tp))) {
10228 			counter_u64_add(rack_reorder_seen, 1);
10229 			rack->r_ctl.rc_reorder_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
10230 		}
10231 		return (0);
10232 	}
10233 	/*
10234 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
10235 	 * something we sent.
10236 	 */
10237 	if (tp->t_flags & TF_NEEDSYN) {
10238 		/*
10239 		 * T/TCP: Connection was half-synchronized, and our SYN has
10240 		 * been ACK'd (so connection is now fully synchronized).  Go
10241 		 * to non-starred state, increment snd_una for ACK of SYN,
10242 		 * and check if we can do window scaling.
10243 		 */
10244 		tp->t_flags &= ~TF_NEEDSYN;
10245 		tp->snd_una++;
10246 		/* Do window scaling? */
10247 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
10248 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
10249 			tp->rcv_scale = tp->request_r_scale;
10250 			/* Send window already scaled. */
10251 		}
10252 	}
10253 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
10254 	INP_WLOCK_ASSERT(tp->t_inpcb);
10255 
10256 	acked = BYTES_THIS_ACK(tp, th);
10257 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, nsegs);
10258 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
10259 	/*
10260 	 * If we just performed our first retransmit, and the ACK arrives
10261 	 * within our recovery window, then it was a mistake to do the
10262 	 * retransmit in the first place.  Recover our original cwnd and
10263 	 * ssthresh, and proceed to transmit where we left off.
10264 	 */
10265 	if ((tp->t_flags & TF_PREVVALID) &&
10266 	    ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
10267 		tp->t_flags &= ~TF_PREVVALID;
10268 		if (tp->t_rxtshift == 1 &&
10269 		    (int)(ticks - tp->t_badrxtwin) < 0)
10270 			rack_cong_signal(tp, CC_RTO_ERR, th->th_ack);
10271 	}
10272 	if (acked) {
10273 		/* assure we are not backed off */
10274 		tp->t_rxtshift = 0;
10275 		RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
10276 			      rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
10277 		rack->rc_tlp_in_progress = 0;
10278 		rack->r_ctl.rc_tlp_cnt_out = 0;
10279 		/*
10280 		 * If it is the RXT timer we want to
10281 		 * stop it, so we can restart a TLP.
10282 		 */
10283 		if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
10284 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
10285 #ifdef NETFLIX_HTTP_LOGGING
10286 		tcp_http_check_for_comp(rack->rc_tp, th->th_ack);
10287 #endif
10288 	}
10289 	/*
10290 	 * If we have a timestamp reply, update smoothed round trip time. If
10291 	 * no timestamp is present but transmit timer is running and timed
10292 	 * sequence number was acked, update smoothed round trip time. Since
10293 	 * we now have an rtt measurement, cancel the timer backoff (cf.,
10294 	 * Phil Karn's retransmit alg.). Recompute the initial retransmit
10295 	 * timer.
10296 	 *
10297 	 * Some boxes send broken timestamp replies during the SYN+ACK
10298 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
10299 	 * and blow up the retransmit timer.
10300 	 */
10301 	/*
10302 	 * If all outstanding data is acked, stop retransmit timer and
10303 	 * remember to restart (more output or persist). If there is more
10304 	 * data to be acked, restart retransmit timer, using current
10305 	 * (possibly backed-off) value.
10306 	 */
10307 	if (acked == 0) {
10308 		if (ofia)
10309 			*ofia = ourfinisacked;
10310 		return (0);
10311 	}
10312 	if (IN_RECOVERY(tp->t_flags)) {
10313 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
10314 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
10315 			tcp_rack_partialack(tp);
10316 		} else {
10317 			rack_post_recovery(tp, th->th_ack);
10318 			recovery = 1;
10319 		}
10320 	}
10321 	/*
10322 	 * Let the congestion control algorithm update congestion control
10323 	 * related information. This typically means increasing the
10324 	 * congestion window.
10325 	 */
10326 	rack_ack_received(tp, rack, th->th_ack, nsegs, CC_ACK, recovery);
10327 	SOCKBUF_LOCK(&so->so_snd);
10328 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
10329 	tp->snd_wnd -= acked_amount;
10330 	mfree = sbcut_locked(&so->so_snd, acked_amount);
10331 	if ((sbused(&so->so_snd) == 0) &&
10332 	    (acked > acked_amount) &&
10333 	    (tp->t_state >= TCPS_FIN_WAIT_1) &&
10334 	    (tp->t_flags & TF_SENTFIN)) {
10335 		/*
10336 		 * We must be sure our fin
10337 		 * was sent and acked (we can be
10338 		 * in FIN_WAIT_1 without having
10339 		 * sent the fin).
10340 		 */
10341 		ourfinisacked = 1;
10342 	}
10343 	tp->snd_una = th->th_ack;
10344 	if (acked_amount && sbavail(&so->so_snd))
10345 		rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
10346 	rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
10347 	/* NB: sowwakeup_locked() does an implicit unlock. */
10348 	sowwakeup_locked(so);
10349 	m_freem(mfree);
10350 	if (SEQ_GT(tp->snd_una, tp->snd_recover))
10351 		tp->snd_recover = tp->snd_una;
10352 
10353 	if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
10354 		tp->snd_nxt = tp->snd_una;
10355 	}
10356 	if (under_pacing &&
10357 	    (rack->use_fixed_rate == 0) &&
10358 	    (rack->in_probe_rtt == 0) &&
10359 	    rack->rc_gp_dyn_mul &&
10360 	    rack->rc_always_pace) {
10361 		/* Check if we are dragging bottom */
10362 		rack_check_bottom_drag(tp, rack, so, acked);
10363 	}
10364 	if (tp->snd_una == tp->snd_max) {
10365 		/* Nothing left outstanding */
10366 		tp->t_flags &= ~TF_PREVVALID;
10367 		rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
10368 		rack->r_ctl.retran_during_recovery = 0;
10369 		rack->r_ctl.dsack_byte_cnt = 0;
10370 		if (rack->r_ctl.rc_went_idle_time == 0)
10371 			rack->r_ctl.rc_went_idle_time = 1;
10372 		rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
10373 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
10374 			tp->t_acktime = 0;
10375 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
10376 		/* Set need output so persist might get set */
10377 		rack->r_wanted_output = 1;
10378 		sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
10379 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
10380 		    (sbavail(&so->so_snd) == 0) &&
10381 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
10382 			/*
10383 			 * The socket was gone and the
10384 			 * peer sent data (now or in the past), time to
10385 			 * reset him.
10386 			 */
10387 			*ret_val = 1;
10388 			/* tcp_close will kill the inp pre-log the Reset */
10389 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
10390 			tp = tcp_close(tp);
10391 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
10392 			return (1);
10393 		}
10394 	}
10395 	if (ofia)
10396 		*ofia = ourfinisacked;
10397 	return (0);
10398 }
10399 
10400 static void
10401 rack_collapsed_window(struct tcp_rack *rack)
10402 {
10403 	/*
10404 	 * Now we must walk the
10405 	 * send map and divide the
10406 	 * ones left stranded. These
10407 	 * guys can't cause us to abort
10408 	 * the connection and are really
10409 	 * "unsent". However if a buggy
10410 	 * client actually did keep some
10411 	 * of the data i.e. collapsed the win
10412 	 * and refused to ack and then opened
10413 	 * the win and acked that data. We would
10414 	 * get into an ack war, the simplier
10415 	 * method then of just pretending we
10416 	 * did not send those segments something
10417 	 * won't work.
10418 	 */
10419 	struct rack_sendmap *rsm, *nrsm, fe, *insret;
10420 	tcp_seq max_seq;
10421 
10422 	max_seq = rack->rc_tp->snd_una + rack->rc_tp->snd_wnd;
10423 	memset(&fe, 0, sizeof(fe));
10424 	fe.r_start = max_seq;
10425 	/* Find the first seq past or at maxseq */
10426 	rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
10427 	if (rsm == NULL) {
10428 		/* Nothing to do strange */
10429 		rack->rc_has_collapsed = 0;
10430 		return;
10431 	}
10432 	/*
10433 	 * Now do we need to split at
10434 	 * the collapse point?
10435 	 */
10436 	if (SEQ_GT(max_seq, rsm->r_start)) {
10437 		nrsm = rack_alloc_limit(rack, RACK_LIMIT_TYPE_SPLIT);
10438 		if (nrsm == NULL) {
10439 			/* We can't get a rsm, mark all? */
10440 			nrsm = rsm;
10441 			goto no_split;
10442 		}
10443 		/* Clone it */
10444 		rack_clone_rsm(rack, nrsm, rsm, max_seq);
10445 		insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm);
10446 #ifdef INVARIANTS
10447 		if (insret != NULL) {
10448 			panic("Insert in rb tree of %p fails ret:%p rack:%p rsm:%p",
10449 			      nrsm, insret, rack, rsm);
10450 		}
10451 #endif
10452 		rack_log_map_chg(rack->rc_tp, rack, NULL, rsm, nrsm, MAP_SPLIT, max_seq, __LINE__);
10453 		if (rsm->r_in_tmap) {
10454 			TAILQ_INSERT_AFTER(&rack->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
10455 			nrsm->r_in_tmap = 1;
10456 		}
10457 		/*
10458 		 * Set in the new RSM as the
10459 		 * collapsed starting point
10460 		 */
10461 		rsm = nrsm;
10462 	}
10463 no_split:
10464 	counter_u64_add(rack_collapsed_win, 1);
10465 	RB_FOREACH_FROM(nrsm, rack_rb_tree_head, rsm) {
10466 		nrsm->r_flags |= RACK_RWND_COLLAPSED;
10467 	}
10468 	rack->rc_has_collapsed = 1;
10469 }
10470 
10471 static void
10472 rack_un_collapse_window(struct tcp_rack *rack)
10473 {
10474 	struct rack_sendmap *rsm;
10475 
10476 	RB_FOREACH_REVERSE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
10477 		if (rsm->r_flags & RACK_RWND_COLLAPSED)
10478 			rsm->r_flags &= ~RACK_RWND_COLLAPSED;
10479 		else
10480 			break;
10481 	}
10482 	rack->rc_has_collapsed = 0;
10483 }
10484 
10485 static void
10486 rack_handle_delayed_ack(struct tcpcb *tp, struct tcp_rack *rack,
10487 			int32_t tlen, int32_t tfo_syn)
10488 {
10489 	if (DELAY_ACK(tp, tlen) || tfo_syn) {
10490 		if (rack->rc_dack_mode &&
10491 		    (tlen > 500) &&
10492 		    (rack->rc_dack_toggle == 1)) {
10493 			goto no_delayed_ack;
10494 		}
10495 		rack_timer_cancel(tp, rack,
10496 				  rack->r_ctl.rc_rcvtime, __LINE__);
10497 		tp->t_flags |= TF_DELACK;
10498 	} else {
10499 no_delayed_ack:
10500 		rack->r_wanted_output = 1;
10501 		tp->t_flags |= TF_ACKNOW;
10502 		if (rack->rc_dack_mode) {
10503 			if (tp->t_flags & TF_DELACK)
10504 				rack->rc_dack_toggle = 1;
10505 			else
10506 				rack->rc_dack_toggle = 0;
10507 		}
10508 	}
10509 }
10510 
10511 static void
10512 rack_validate_fo_sendwin_up(struct tcpcb *tp, struct tcp_rack *rack)
10513 {
10514 	/*
10515 	 * If fast output is in progress, lets validate that
10516 	 * the new window did not shrink on us and make it
10517 	 * so fast output should end.
10518 	 */
10519 	if (rack->r_fast_output) {
10520 		uint32_t out;
10521 
10522 		/*
10523 		 * Calculate what we will send if left as is
10524 		 * and compare that to our send window.
10525 		 */
10526 		out = ctf_outstanding(tp);
10527 		if ((out + rack->r_ctl.fsb.left_to_send) > tp->snd_wnd) {
10528 			/* ok we have an issue */
10529 			if (out >= tp->snd_wnd) {
10530 				/* Turn off fast output the window is met or collapsed */
10531 				rack->r_fast_output = 0;
10532 			} else {
10533 				/* we have some room left */
10534 				rack->r_ctl.fsb.left_to_send = tp->snd_wnd - out;
10535 				if (rack->r_ctl.fsb.left_to_send < ctf_fixed_maxseg(tp)) {
10536 					/* If not at least 1 full segment never mind */
10537 					rack->r_fast_output = 0;
10538 				}
10539 			}
10540 		}
10541 	}
10542 }
10543 
10544 
10545 /*
10546  * Return value of 1, the TCB is unlocked and most
10547  * likely gone, return value of 0, the TCP is still
10548  * locked.
10549  */
10550 static int
10551 rack_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
10552     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
10553     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
10554 {
10555 	/*
10556 	 * Update window information. Don't look at window if no ACK: TAC's
10557 	 * send garbage on first SYN.
10558 	 */
10559 	int32_t nsegs;
10560 	int32_t tfo_syn;
10561 	struct tcp_rack *rack;
10562 
10563 	rack = (struct tcp_rack *)tp->t_fb_ptr;
10564 	INP_WLOCK_ASSERT(tp->t_inpcb);
10565 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
10566 	if ((thflags & TH_ACK) &&
10567 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
10568 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
10569 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
10570 		/* keep track of pure window updates */
10571 		if (tlen == 0 &&
10572 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
10573 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
10574 		tp->snd_wnd = tiwin;
10575 		rack_validate_fo_sendwin_up(tp, rack);
10576 		tp->snd_wl1 = th->th_seq;
10577 		tp->snd_wl2 = th->th_ack;
10578 		if (tp->snd_wnd > tp->max_sndwnd)
10579 			tp->max_sndwnd = tp->snd_wnd;
10580 		rack->r_wanted_output = 1;
10581 	} else if (thflags & TH_ACK) {
10582 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
10583 			tp->snd_wnd = tiwin;
10584 			rack_validate_fo_sendwin_up(tp, rack);
10585 			tp->snd_wl1 = th->th_seq;
10586 			tp->snd_wl2 = th->th_ack;
10587 		}
10588 	}
10589 	if (tp->snd_wnd < ctf_outstanding(tp))
10590 		/* The peer collapsed the window */
10591 		rack_collapsed_window(rack);
10592 	else if (rack->rc_has_collapsed)
10593 		rack_un_collapse_window(rack);
10594 	/* Was persist timer active and now we have window space? */
10595 	if ((rack->rc_in_persist != 0) &&
10596 	    (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
10597 				rack->r_ctl.rc_pace_min_segs))) {
10598 		rack_exit_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10599 		tp->snd_nxt = tp->snd_max;
10600 		/* Make sure we output to start the timer */
10601 		rack->r_wanted_output = 1;
10602 	}
10603 	/* Do we enter persists? */
10604 	if ((rack->rc_in_persist == 0) &&
10605 	    (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
10606 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
10607 	    (tp->snd_max == tp->snd_una) &&
10608 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
10609 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
10610 		/*
10611 		 * Here the rwnd is less than
10612 		 * the pacing size, we are established,
10613 		 * nothing is outstanding, and there is
10614 		 * data to send. Enter persists.
10615 		 */
10616 		rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
10617 	}
10618 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
10619 		m_freem(m);
10620 		return (0);
10621 	}
10622 	/*
10623 	 * don't process the URG bit, ignore them drag
10624 	 * along the up.
10625 	 */
10626 	tp->rcv_up = tp->rcv_nxt;
10627 	INP_WLOCK_ASSERT(tp->t_inpcb);
10628 
10629 	/*
10630 	 * Process the segment text, merging it into the TCP sequencing
10631 	 * queue, and arranging for acknowledgment of receipt if necessary.
10632 	 * This process logically involves adjusting tp->rcv_wnd as data is
10633 	 * presented to the user (this happens in tcp_usrreq.c, case
10634 	 * PRU_RCVD).  If a FIN has already been received on this connection
10635 	 * then we just ignore the text.
10636 	 */
10637 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
10638 		   IS_FASTOPEN(tp->t_flags));
10639 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
10640 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
10641 		tcp_seq save_start = th->th_seq;
10642 		tcp_seq save_rnxt  = tp->rcv_nxt;
10643 		int     save_tlen  = tlen;
10644 
10645 		m_adj(m, drop_hdrlen);	/* delayed header drop */
10646 		/*
10647 		 * Insert segment which includes th into TCP reassembly
10648 		 * queue with control block tp.  Set thflags to whether
10649 		 * reassembly now includes a segment with FIN.  This handles
10650 		 * the common case inline (segment is the next to be
10651 		 * received on an established connection, and the queue is
10652 		 * empty), avoiding linkage into and removal from the queue
10653 		 * and repetition of various conversions. Set DELACK for
10654 		 * segments received in order, but ack immediately when
10655 		 * segments are out of order (so fast retransmit can work).
10656 		 */
10657 		if (th->th_seq == tp->rcv_nxt &&
10658 		    SEGQ_EMPTY(tp) &&
10659 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
10660 		    tfo_syn)) {
10661 #ifdef NETFLIX_SB_LIMITS
10662 			u_int mcnt, appended;
10663 
10664 			if (so->so_rcv.sb_shlim) {
10665 				mcnt = m_memcnt(m);
10666 				appended = 0;
10667 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
10668 				    CFO_NOSLEEP, NULL) == false) {
10669 					counter_u64_add(tcp_sb_shlim_fails, 1);
10670 					m_freem(m);
10671 					return (0);
10672 				}
10673 			}
10674 #endif
10675 			rack_handle_delayed_ack(tp, rack, tlen, tfo_syn);
10676 			tp->rcv_nxt += tlen;
10677 			if (tlen &&
10678 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
10679 			    (tp->t_fbyte_in == 0)) {
10680 				tp->t_fbyte_in = ticks;
10681 				if (tp->t_fbyte_in == 0)
10682 					tp->t_fbyte_in = 1;
10683 				if (tp->t_fbyte_out && tp->t_fbyte_in)
10684 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
10685 			}
10686 			thflags = th->th_flags & TH_FIN;
10687 			KMOD_TCPSTAT_ADD(tcps_rcvpack, nsegs);
10688 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
10689 			SOCKBUF_LOCK(&so->so_rcv);
10690 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10691 				m_freem(m);
10692 			} else
10693 #ifdef NETFLIX_SB_LIMITS
10694 				appended =
10695 #endif
10696 					sbappendstream_locked(&so->so_rcv, m, 0);
10697 
10698 			rack_log_wakeup(tp,rack, &so->so_rcv, tlen, 1);
10699 			/* NB: sorwakeup_locked() does an implicit unlock. */
10700 			sorwakeup_locked(so);
10701 #ifdef NETFLIX_SB_LIMITS
10702 			if (so->so_rcv.sb_shlim && appended != mcnt)
10703 				counter_fo_release(so->so_rcv.sb_shlim,
10704 				    mcnt - appended);
10705 #endif
10706 		} else {
10707 			/*
10708 			 * XXX: Due to the header drop above "th" is
10709 			 * theoretically invalid by now.  Fortunately
10710 			 * m_adj() doesn't actually frees any mbufs when
10711 			 * trimming from the head.
10712 			 */
10713 			tcp_seq temp = save_start;
10714 
10715 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
10716 			tp->t_flags |= TF_ACKNOW;
10717 			if (tp->t_flags & TF_WAKESOR) {
10718 				tp->t_flags &= ~TF_WAKESOR;
10719 				/* NB: sorwakeup_locked() does an implicit unlock. */
10720 				sorwakeup_locked(so);
10721 			}
10722 		}
10723 		if ((tp->t_flags & TF_SACK_PERMIT) &&
10724 		    (save_tlen > 0) &&
10725 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
10726 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
10727 				/*
10728 				 * DSACK actually handled in the fastpath
10729 				 * above.
10730 				 */
10731 				RACK_OPTS_INC(tcp_sack_path_1);
10732 				tcp_update_sack_list(tp, save_start,
10733 				    save_start + save_tlen);
10734 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
10735 				if ((tp->rcv_numsacks >= 1) &&
10736 				    (tp->sackblks[0].end == save_start)) {
10737 					/*
10738 					 * Partial overlap, recorded at todrop
10739 					 * above.
10740 					 */
10741 					RACK_OPTS_INC(tcp_sack_path_2a);
10742 					tcp_update_sack_list(tp,
10743 					    tp->sackblks[0].start,
10744 					    tp->sackblks[0].end);
10745 				} else {
10746 					RACK_OPTS_INC(tcp_sack_path_2b);
10747 					tcp_update_dsack_list(tp, save_start,
10748 					    save_start + save_tlen);
10749 				}
10750 			} else if (tlen >= save_tlen) {
10751 				/* Update of sackblks. */
10752 				RACK_OPTS_INC(tcp_sack_path_3);
10753 				tcp_update_dsack_list(tp, save_start,
10754 				    save_start + save_tlen);
10755 			} else if (tlen > 0) {
10756 				RACK_OPTS_INC(tcp_sack_path_4);
10757 				tcp_update_dsack_list(tp, save_start,
10758 				    save_start + tlen);
10759 			}
10760 		}
10761 	} else {
10762 		m_freem(m);
10763 		thflags &= ~TH_FIN;
10764 	}
10765 
10766 	/*
10767 	 * If FIN is received ACK the FIN and let the user know that the
10768 	 * connection is closing.
10769 	 */
10770 	if (thflags & TH_FIN) {
10771 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
10772 			/* The socket upcall is handled by socantrcvmore. */
10773 			socantrcvmore(so);
10774 			/*
10775 			 * If connection is half-synchronized (ie NEEDSYN
10776 			 * flag on) then delay ACK, so it may be piggybacked
10777 			 * when SYN is sent. Otherwise, since we received a
10778 			 * FIN then no more input can be expected, send ACK
10779 			 * now.
10780 			 */
10781 			if (tp->t_flags & TF_NEEDSYN) {
10782 				rack_timer_cancel(tp, rack,
10783 				    rack->r_ctl.rc_rcvtime, __LINE__);
10784 				tp->t_flags |= TF_DELACK;
10785 			} else {
10786 				tp->t_flags |= TF_ACKNOW;
10787 			}
10788 			tp->rcv_nxt++;
10789 		}
10790 		switch (tp->t_state) {
10791 			/*
10792 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
10793 			 * CLOSE_WAIT state.
10794 			 */
10795 		case TCPS_SYN_RECEIVED:
10796 			tp->t_starttime = ticks;
10797 			/* FALLTHROUGH */
10798 		case TCPS_ESTABLISHED:
10799 			rack_timer_cancel(tp, rack,
10800 			    rack->r_ctl.rc_rcvtime, __LINE__);
10801 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
10802 			break;
10803 
10804 			/*
10805 			 * If still in FIN_WAIT_1 STATE FIN has not been
10806 			 * acked so enter the CLOSING state.
10807 			 */
10808 		case TCPS_FIN_WAIT_1:
10809 			rack_timer_cancel(tp, rack,
10810 			    rack->r_ctl.rc_rcvtime, __LINE__);
10811 			tcp_state_change(tp, TCPS_CLOSING);
10812 			break;
10813 
10814 			/*
10815 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
10816 			 * starting the time-wait timer, turning off the
10817 			 * other standard timers.
10818 			 */
10819 		case TCPS_FIN_WAIT_2:
10820 			rack_timer_cancel(tp, rack,
10821 			    rack->r_ctl.rc_rcvtime, __LINE__);
10822 			tcp_twstart(tp);
10823 			return (1);
10824 		}
10825 	}
10826 	/*
10827 	 * Return any desired output.
10828 	 */
10829 	if ((tp->t_flags & TF_ACKNOW) ||
10830 	    (sbavail(&so->so_snd) > (tp->snd_max - tp->snd_una))) {
10831 		rack->r_wanted_output = 1;
10832 	}
10833 	INP_WLOCK_ASSERT(tp->t_inpcb);
10834 	return (0);
10835 }
10836 
10837 /*
10838  * Here nothing is really faster, its just that we
10839  * have broken out the fast-data path also just like
10840  * the fast-ack.
10841  */
10842 static int
10843 rack_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
10844     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10845     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
10846 {
10847 	int32_t nsegs;
10848 	int32_t newsize = 0;	/* automatic sockbuf scaling */
10849 	struct tcp_rack *rack;
10850 #ifdef NETFLIX_SB_LIMITS
10851 	u_int mcnt, appended;
10852 #endif
10853 #ifdef TCPDEBUG
10854 	/*
10855 	 * The size of tcp_saveipgen must be the size of the max ip header,
10856 	 * now IPv6.
10857 	 */
10858 	u_char tcp_saveipgen[IP6_HDR_LEN];
10859 	struct tcphdr tcp_savetcp;
10860 	short ostate = 0;
10861 
10862 #endif
10863 	/*
10864 	 * If last ACK falls within this segment's sequence numbers, record
10865 	 * the timestamp. NOTE that the test is modified according to the
10866 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
10867 	 */
10868 	if (__predict_false(th->th_seq != tp->rcv_nxt)) {
10869 		return (0);
10870 	}
10871 	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
10872 		return (0);
10873 	}
10874 	if (tiwin && tiwin != tp->snd_wnd) {
10875 		return (0);
10876 	}
10877 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
10878 		return (0);
10879 	}
10880 	if (__predict_false((to->to_flags & TOF_TS) &&
10881 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
10882 		return (0);
10883 	}
10884 	if (__predict_false((th->th_ack != tp->snd_una))) {
10885 		return (0);
10886 	}
10887 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
10888 		return (0);
10889 	}
10890 	if ((to->to_flags & TOF_TS) != 0 &&
10891 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
10892 		tp->ts_recent_age = tcp_ts_getticks();
10893 		tp->ts_recent = to->to_tsval;
10894 	}
10895 	rack = (struct tcp_rack *)tp->t_fb_ptr;
10896 	/*
10897 	 * This is a pure, in-sequence data packet with nothing on the
10898 	 * reassembly queue and we have enough buffer space to take it.
10899 	 */
10900 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
10901 
10902 #ifdef NETFLIX_SB_LIMITS
10903 	if (so->so_rcv.sb_shlim) {
10904 		mcnt = m_memcnt(m);
10905 		appended = 0;
10906 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
10907 		    CFO_NOSLEEP, NULL) == false) {
10908 			counter_u64_add(tcp_sb_shlim_fails, 1);
10909 			m_freem(m);
10910 			return (1);
10911 		}
10912 	}
10913 #endif
10914 	/* Clean receiver SACK report if present */
10915 	if (tp->rcv_numsacks)
10916 		tcp_clean_sackreport(tp);
10917 	KMOD_TCPSTAT_INC(tcps_preddat);
10918 	tp->rcv_nxt += tlen;
10919 	if (tlen &&
10920 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
10921 	    (tp->t_fbyte_in == 0)) {
10922 		tp->t_fbyte_in = ticks;
10923 		if (tp->t_fbyte_in == 0)
10924 			tp->t_fbyte_in = 1;
10925 		if (tp->t_fbyte_out && tp->t_fbyte_in)
10926 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
10927 	}
10928 	/*
10929 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
10930 	 */
10931 	tp->snd_wl1 = th->th_seq;
10932 	/*
10933 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
10934 	 */
10935 	tp->rcv_up = tp->rcv_nxt;
10936 	KMOD_TCPSTAT_ADD(tcps_rcvpack, nsegs);
10937 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
10938 #ifdef TCPDEBUG
10939 	if (so->so_options & SO_DEBUG)
10940 		tcp_trace(TA_INPUT, ostate, tp,
10941 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
10942 #endif
10943 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
10944 
10945 	/* Add data to socket buffer. */
10946 	SOCKBUF_LOCK(&so->so_rcv);
10947 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
10948 		m_freem(m);
10949 	} else {
10950 		/*
10951 		 * Set new socket buffer size. Give up when limit is
10952 		 * reached.
10953 		 */
10954 		if (newsize)
10955 			if (!sbreserve_locked(&so->so_rcv,
10956 			    newsize, so, NULL))
10957 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
10958 		m_adj(m, drop_hdrlen);	/* delayed header drop */
10959 #ifdef NETFLIX_SB_LIMITS
10960 		appended =
10961 #endif
10962 			sbappendstream_locked(&so->so_rcv, m, 0);
10963 		ctf_calc_rwin(so, tp);
10964 	}
10965 	rack_log_wakeup(tp,rack, &so->so_rcv, tlen, 1);
10966 	/* NB: sorwakeup_locked() does an implicit unlock. */
10967 	sorwakeup_locked(so);
10968 #ifdef NETFLIX_SB_LIMITS
10969 	if (so->so_rcv.sb_shlim && mcnt != appended)
10970 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
10971 #endif
10972 	rack_handle_delayed_ack(tp, rack, tlen, 0);
10973 	if (tp->snd_una == tp->snd_max)
10974 		sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
10975 	return (1);
10976 }
10977 
10978 /*
10979  * This subfunction is used to try to highly optimize the
10980  * fast path. We again allow window updates that are
10981  * in sequence to remain in the fast-path. We also add
10982  * in the __predict's to attempt to help the compiler.
10983  * Note that if we return a 0, then we can *not* process
10984  * it and the caller should push the packet into the
10985  * slow-path.
10986  */
10987 static int
10988 rack_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
10989     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
10990     uint32_t tiwin, int32_t nxt_pkt, uint32_t cts)
10991 {
10992 	int32_t acked;
10993 	int32_t nsegs;
10994 #ifdef TCPDEBUG
10995 	/*
10996 	 * The size of tcp_saveipgen must be the size of the max ip header,
10997 	 * now IPv6.
10998 	 */
10999 	u_char tcp_saveipgen[IP6_HDR_LEN];
11000 	struct tcphdr tcp_savetcp;
11001 	short ostate = 0;
11002 #endif
11003 	int32_t under_pacing = 0;
11004 	struct tcp_rack *rack;
11005 
11006 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
11007 		/* Old ack, behind (or duplicate to) the last one rcv'd */
11008 		return (0);
11009 	}
11010 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
11011 		/* Above what we have sent? */
11012 		return (0);
11013 	}
11014 	if (__predict_false(tp->snd_nxt != tp->snd_max)) {
11015 		/* We are retransmitting */
11016 		return (0);
11017 	}
11018 	if (__predict_false(tiwin == 0)) {
11019 		/* zero window */
11020 		return (0);
11021 	}
11022 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
11023 		/* We need a SYN or a FIN, unlikely.. */
11024 		return (0);
11025 	}
11026 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
11027 		/* Timestamp is behind .. old ack with seq wrap? */
11028 		return (0);
11029 	}
11030 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
11031 		/* Still recovering */
11032 		return (0);
11033 	}
11034 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11035 	if (rack->r_ctl.rc_sacked) {
11036 		/* We have sack holes on our scoreboard */
11037 		return (0);
11038 	}
11039 	/* Ok if we reach here, we can process a fast-ack */
11040 	if (rack->gp_ready &&
11041 	    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11042 		under_pacing = 1;
11043 	}
11044 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11045 	rack_log_ack(tp, to, th, 0, 0);
11046 	/* Did the window get updated? */
11047 	if (tiwin != tp->snd_wnd) {
11048 		tp->snd_wnd = tiwin;
11049 		rack_validate_fo_sendwin_up(tp, rack);
11050 		tp->snd_wl1 = th->th_seq;
11051 		if (tp->snd_wnd > tp->max_sndwnd)
11052 			tp->max_sndwnd = tp->snd_wnd;
11053 	}
11054 	/* Do we exit persists? */
11055 	if ((rack->rc_in_persist != 0) &&
11056 	    (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
11057 			       rack->r_ctl.rc_pace_min_segs))) {
11058 		rack_exit_persist(tp, rack, cts);
11059 	}
11060 	/* Do we enter persists? */
11061 	if ((rack->rc_in_persist == 0) &&
11062 	    (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
11063 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
11064 	    (tp->snd_max == tp->snd_una) &&
11065 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
11066 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
11067 		/*
11068 		 * Here the rwnd is less than
11069 		 * the pacing size, we are established,
11070 		 * nothing is outstanding, and there is
11071 		 * data to send. Enter persists.
11072 		 */
11073 		rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
11074 	}
11075 	/*
11076 	 * If last ACK falls within this segment's sequence numbers, record
11077 	 * the timestamp. NOTE that the test is modified according to the
11078 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
11079 	 */
11080 	if ((to->to_flags & TOF_TS) != 0 &&
11081 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
11082 		tp->ts_recent_age = tcp_ts_getticks();
11083 		tp->ts_recent = to->to_tsval;
11084 	}
11085 	/*
11086 	 * This is a pure ack for outstanding data.
11087 	 */
11088 	KMOD_TCPSTAT_INC(tcps_predack);
11089 
11090 	/*
11091 	 * "bad retransmit" recovery.
11092 	 */
11093 	if ((tp->t_flags & TF_PREVVALID) &&
11094 	    ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
11095 		tp->t_flags &= ~TF_PREVVALID;
11096 		if (tp->t_rxtshift == 1 &&
11097 		    (int)(ticks - tp->t_badrxtwin) < 0)
11098 			rack_cong_signal(tp, CC_RTO_ERR, th->th_ack);
11099 	}
11100 	/*
11101 	 * Recalculate the transmit timer / rtt.
11102 	 *
11103 	 * Some boxes send broken timestamp replies during the SYN+ACK
11104 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
11105 	 * and blow up the retransmit timer.
11106 	 */
11107 	acked = BYTES_THIS_ACK(tp, th);
11108 
11109 #ifdef TCP_HHOOK
11110 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
11111 	hhook_run_tcp_est_in(tp, th, to);
11112 #endif
11113 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, nsegs);
11114 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
11115 	if (acked) {
11116 		struct mbuf *mfree;
11117 
11118 		rack_ack_received(tp, rack, th->th_ack, nsegs, CC_ACK, 0);
11119 		SOCKBUF_LOCK(&so->so_snd);
11120 		mfree = sbcut_locked(&so->so_snd, acked);
11121 		tp->snd_una = th->th_ack;
11122 		/* Note we want to hold the sb lock through the sendmap adjust */
11123 		rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
11124 		/* Wake up the socket if we have room to write more */
11125 		rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
11126 		sowwakeup_locked(so);
11127 		m_freem(mfree);
11128 		tp->t_rxtshift = 0;
11129 		RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
11130 			      rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
11131 		rack->rc_tlp_in_progress = 0;
11132 		rack->r_ctl.rc_tlp_cnt_out = 0;
11133 		/*
11134 		 * If it is the RXT timer we want to
11135 		 * stop it, so we can restart a TLP.
11136 		 */
11137 		if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
11138 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
11139 #ifdef NETFLIX_HTTP_LOGGING
11140 		tcp_http_check_for_comp(rack->rc_tp, th->th_ack);
11141 #endif
11142 	}
11143 	/*
11144 	 * Let the congestion control algorithm update congestion control
11145 	 * related information. This typically means increasing the
11146 	 * congestion window.
11147 	 */
11148 	if (tp->snd_wnd < ctf_outstanding(tp)) {
11149 		/* The peer collapsed the window */
11150 		rack_collapsed_window(rack);
11151 	} else if (rack->rc_has_collapsed)
11152 		rack_un_collapse_window(rack);
11153 
11154 	/*
11155 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
11156 	 */
11157 	tp->snd_wl2 = th->th_ack;
11158 	tp->t_dupacks = 0;
11159 	m_freem(m);
11160 	/* ND6_HINT(tp);	 *//* Some progress has been made. */
11161 
11162 	/*
11163 	 * If all outstanding data are acked, stop retransmit timer,
11164 	 * otherwise restart timer using current (possibly backed-off)
11165 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
11166 	 * If data are ready to send, let tcp_output decide between more
11167 	 * output or persist.
11168 	 */
11169 #ifdef TCPDEBUG
11170 	if (so->so_options & SO_DEBUG)
11171 		tcp_trace(TA_INPUT, ostate, tp,
11172 		    (void *)tcp_saveipgen,
11173 		    &tcp_savetcp, 0);
11174 #endif
11175 	if (under_pacing &&
11176 	    (rack->use_fixed_rate == 0) &&
11177 	    (rack->in_probe_rtt == 0) &&
11178 	    rack->rc_gp_dyn_mul &&
11179 	    rack->rc_always_pace) {
11180 		/* Check if we are dragging bottom */
11181 		rack_check_bottom_drag(tp, rack, so, acked);
11182 	}
11183 	if (tp->snd_una == tp->snd_max) {
11184 		tp->t_flags &= ~TF_PREVVALID;
11185 		rack->r_ctl.retran_during_recovery = 0;
11186 		rack->r_ctl.dsack_byte_cnt = 0;
11187 		rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
11188 		if (rack->r_ctl.rc_went_idle_time == 0)
11189 			rack->r_ctl.rc_went_idle_time = 1;
11190 		rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
11191 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
11192 			tp->t_acktime = 0;
11193 		rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
11194 	}
11195 	if (acked && rack->r_fast_output)
11196 		rack_gain_for_fastoutput(rack, tp, so, (uint32_t)acked);
11197 	if (sbavail(&so->so_snd)) {
11198 		rack->r_wanted_output = 1;
11199 	}
11200 	return (1);
11201 }
11202 
11203 /*
11204  * Return value of 1, the TCB is unlocked and most
11205  * likely gone, return value of 0, the TCP is still
11206  * locked.
11207  */
11208 static int
11209 rack_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
11210     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11211     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11212 {
11213 	int32_t ret_val = 0;
11214 	int32_t todrop;
11215 	int32_t ourfinisacked = 0;
11216 	struct tcp_rack *rack;
11217 
11218 	ctf_calc_rwin(so, tp);
11219 	/*
11220 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
11221 	 * SYN, drop the input. if seg contains a RST, then drop the
11222 	 * connection. if seg does not contain SYN, then drop it. Otherwise
11223 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
11224 	 * tp->irs if seg contains ack then advance tp->snd_una if seg
11225 	 * contains an ECE and ECN support is enabled, the stream is ECN
11226 	 * capable. if SYN has been acked change to ESTABLISHED else
11227 	 * SYN_RCVD state arrange for segment to be acked (eventually)
11228 	 * continue processing rest of data/controls.
11229 	 */
11230 	if ((thflags & TH_ACK) &&
11231 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
11232 	    SEQ_GT(th->th_ack, tp->snd_max))) {
11233 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11234 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11235 		return (1);
11236 	}
11237 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
11238 		TCP_PROBE5(connect__refused, NULL, tp,
11239 		    mtod(m, const char *), tp, th);
11240 		tp = tcp_drop(tp, ECONNREFUSED);
11241 		ctf_do_drop(m, tp);
11242 		return (1);
11243 	}
11244 	if (thflags & TH_RST) {
11245 		ctf_do_drop(m, tp);
11246 		return (1);
11247 	}
11248 	if (!(thflags & TH_SYN)) {
11249 		ctf_do_drop(m, tp);
11250 		return (1);
11251 	}
11252 	tp->irs = th->th_seq;
11253 	tcp_rcvseqinit(tp);
11254 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11255 	if (thflags & TH_ACK) {
11256 		int tfo_partial = 0;
11257 
11258 		KMOD_TCPSTAT_INC(tcps_connects);
11259 		soisconnected(so);
11260 #ifdef MAC
11261 		mac_socketpeer_set_from_mbuf(m, so);
11262 #endif
11263 		/* Do window scaling on this connection? */
11264 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
11265 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
11266 			tp->rcv_scale = tp->request_r_scale;
11267 		}
11268 		tp->rcv_adv += min(tp->rcv_wnd,
11269 		    TCP_MAXWIN << tp->rcv_scale);
11270 		/*
11271 		 * If not all the data that was sent in the TFO SYN
11272 		 * has been acked, resend the remainder right away.
11273 		 */
11274 		if (IS_FASTOPEN(tp->t_flags) &&
11275 		    (tp->snd_una != tp->snd_max)) {
11276 			tp->snd_nxt = th->th_ack;
11277 			tfo_partial = 1;
11278 		}
11279 		/*
11280 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
11281 		 * will be turned on later.
11282 		 */
11283 		if (DELAY_ACK(tp, tlen) && tlen != 0 && !tfo_partial) {
11284 			rack_timer_cancel(tp, rack,
11285 					  rack->r_ctl.rc_rcvtime, __LINE__);
11286 			tp->t_flags |= TF_DELACK;
11287 		} else {
11288 			rack->r_wanted_output = 1;
11289 			tp->t_flags |= TF_ACKNOW;
11290 			rack->rc_dack_toggle = 0;
11291 		}
11292 		if (((thflags & (TH_CWR | TH_ECE)) == TH_ECE) &&
11293 		    (V_tcp_do_ecn == 1)) {
11294 			tp->t_flags2 |= TF2_ECN_PERMIT;
11295 			KMOD_TCPSTAT_INC(tcps_ecn_shs);
11296 		}
11297 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
11298 			/*
11299 			 * We advance snd_una for the
11300 			 * fast open case. If th_ack is
11301 			 * acknowledging data beyond
11302 			 * snd_una we can't just call
11303 			 * ack-processing since the
11304 			 * data stream in our send-map
11305 			 * will start at snd_una + 1 (one
11306 			 * beyond the SYN). If its just
11307 			 * equal we don't need to do that
11308 			 * and there is no send_map.
11309 			 */
11310 			tp->snd_una++;
11311 		}
11312 		/*
11313 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
11314 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
11315 		 */
11316 		tp->t_starttime = ticks;
11317 		if (tp->t_flags & TF_NEEDFIN) {
11318 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
11319 			tp->t_flags &= ~TF_NEEDFIN;
11320 			thflags &= ~TH_SYN;
11321 		} else {
11322 			tcp_state_change(tp, TCPS_ESTABLISHED);
11323 			TCP_PROBE5(connect__established, NULL, tp,
11324 			    mtod(m, const char *), tp, th);
11325 			rack_cc_conn_init(tp);
11326 		}
11327 	} else {
11328 		/*
11329 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
11330 		 * open.  If segment contains CC option and there is a
11331 		 * cached CC, apply TAO test. If it succeeds, connection is *
11332 		 * half-synchronized. Otherwise, do 3-way handshake:
11333 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
11334 		 * there was no CC option, clear cached CC value.
11335 		 */
11336 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
11337 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
11338 	}
11339 	INP_WLOCK_ASSERT(tp->t_inpcb);
11340 	/*
11341 	 * Advance th->th_seq to correspond to first data byte. If data,
11342 	 * trim to stay within window, dropping FIN if necessary.
11343 	 */
11344 	th->th_seq++;
11345 	if (tlen > tp->rcv_wnd) {
11346 		todrop = tlen - tp->rcv_wnd;
11347 		m_adj(m, -todrop);
11348 		tlen = tp->rcv_wnd;
11349 		thflags &= ~TH_FIN;
11350 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
11351 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
11352 	}
11353 	tp->snd_wl1 = th->th_seq - 1;
11354 	tp->rcv_up = th->th_seq;
11355 	/*
11356 	 * Client side of transaction: already sent SYN and data. If the
11357 	 * remote host used T/TCP to validate the SYN, our data will be
11358 	 * ACK'd; if so, enter normal data segment processing in the middle
11359 	 * of step 5, ack processing. Otherwise, goto step 6.
11360 	 */
11361 	if (thflags & TH_ACK) {
11362 		/* For syn-sent we need to possibly update the rtt */
11363 		if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
11364 			uint32_t t, mcts;
11365 
11366 			mcts = tcp_ts_getticks();
11367 			t = (mcts - to->to_tsecr) * HPTS_USEC_IN_MSEC;
11368 			if (!tp->t_rttlow || tp->t_rttlow > t)
11369 				tp->t_rttlow = t;
11370 			rack_log_rtt_sample_calc(rack, t, (to->to_tsecr * 1000), (mcts * 1000), 4);
11371 			tcp_rack_xmit_timer(rack, t + 1, 1, t, 0, NULL, 2);
11372 			tcp_rack_xmit_timer_commit(rack, tp);
11373 		}
11374 		if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
11375 			return (ret_val);
11376 		/* We may have changed to FIN_WAIT_1 above */
11377 		if (tp->t_state == TCPS_FIN_WAIT_1) {
11378 			/*
11379 			 * In FIN_WAIT_1 STATE in addition to the processing
11380 			 * for the ESTABLISHED state if our FIN is now
11381 			 * acknowledged then enter FIN_WAIT_2.
11382 			 */
11383 			if (ourfinisacked) {
11384 				/*
11385 				 * If we can't receive any more data, then
11386 				 * closing user can proceed. Starting the
11387 				 * timer is contrary to the specification,
11388 				 * but if we don't get a FIN we'll hang
11389 				 * forever.
11390 				 *
11391 				 * XXXjl: we should release the tp also, and
11392 				 * use a compressed state.
11393 				 */
11394 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11395 					soisdisconnected(so);
11396 					tcp_timer_activate(tp, TT_2MSL,
11397 					    (tcp_fast_finwait2_recycle ?
11398 					    tcp_finwait2_timeout :
11399 					    TP_MAXIDLE(tp)));
11400 				}
11401 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
11402 			}
11403 		}
11404 	}
11405 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11406 	   tiwin, thflags, nxt_pkt));
11407 }
11408 
11409 /*
11410  * Return value of 1, the TCB is unlocked and most
11411  * likely gone, return value of 0, the TCP is still
11412  * locked.
11413  */
11414 static int
11415 rack_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
11416     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11417     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11418 {
11419 	struct tcp_rack *rack;
11420 	int32_t ret_val = 0;
11421 	int32_t ourfinisacked = 0;
11422 
11423 	ctf_calc_rwin(so, tp);
11424 	if ((thflags & TH_ACK) &&
11425 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
11426 	    SEQ_GT(th->th_ack, tp->snd_max))) {
11427 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11428 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11429 		return (1);
11430 	}
11431 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11432 	if (IS_FASTOPEN(tp->t_flags)) {
11433 		/*
11434 		 * When a TFO connection is in SYN_RECEIVED, the
11435 		 * only valid packets are the initial SYN, a
11436 		 * retransmit/copy of the initial SYN (possibly with
11437 		 * a subset of the original data), a valid ACK, a
11438 		 * FIN, or a RST.
11439 		 */
11440 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
11441 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11442 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11443 			return (1);
11444 		} else if (thflags & TH_SYN) {
11445 			/* non-initial SYN is ignored */
11446 			if ((rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
11447 			    (rack->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
11448 			    (rack->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
11449 				ctf_do_drop(m, NULL);
11450 				return (0);
11451 			}
11452 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
11453 			ctf_do_drop(m, NULL);
11454 			return (0);
11455 		}
11456 	}
11457 	if ((thflags & TH_RST) ||
11458 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
11459 		return (ctf_process_rst(m, th, so, tp));
11460 	/*
11461 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11462 	 * it's less than ts_recent, drop it.
11463 	 */
11464 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11465 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11466 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11467 			return (ret_val);
11468 	}
11469 	/*
11470 	 * In the SYN-RECEIVED state, validate that the packet belongs to
11471 	 * this connection before trimming the data to fit the receive
11472 	 * window.  Check the sequence number versus IRS since we know the
11473 	 * sequence numbers haven't wrapped.  This is a partial fix for the
11474 	 * "LAND" DoS attack.
11475 	 */
11476 	if (SEQ_LT(th->th_seq, tp->irs)) {
11477 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11478 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11479 		return (1);
11480 	}
11481 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11482 			      &rack->r_ctl.challenge_ack_ts,
11483 			      &rack->r_ctl.challenge_ack_cnt)) {
11484 		return (ret_val);
11485 	}
11486 	/*
11487 	 * If last ACK falls within this segment's sequence numbers, record
11488 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
11489 	 * from the latest proposal of the tcplw@cray.com list (Braden
11490 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
11491 	 * with our earlier PAWS tests, so this check should be solely
11492 	 * predicated on the sequence space of this segment. 3) That we
11493 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11494 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11495 	 * SEG.Len, This modified check allows us to overcome RFC1323's
11496 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11497 	 * p.869. In such cases, we can still calculate the RTT correctly
11498 	 * when RCV.NXT == Last.ACK.Sent.
11499 	 */
11500 	if ((to->to_flags & TOF_TS) != 0 &&
11501 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11502 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11503 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11504 		tp->ts_recent_age = tcp_ts_getticks();
11505 		tp->ts_recent = to->to_tsval;
11506 	}
11507 	tp->snd_wnd = tiwin;
11508 	rack_validate_fo_sendwin_up(tp, rack);
11509 	/*
11510 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11511 	 * is on (half-synchronized state), then queue data for later
11512 	 * processing; else drop segment and return.
11513 	 */
11514 	if ((thflags & TH_ACK) == 0) {
11515 		if (IS_FASTOPEN(tp->t_flags)) {
11516 			rack_cc_conn_init(tp);
11517 		}
11518 		return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11519 		    tiwin, thflags, nxt_pkt));
11520 	}
11521 	KMOD_TCPSTAT_INC(tcps_connects);
11522 	soisconnected(so);
11523 	/* Do window scaling? */
11524 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
11525 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
11526 		tp->rcv_scale = tp->request_r_scale;
11527 	}
11528 	/*
11529 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
11530 	 * FIN-WAIT-1
11531 	 */
11532 	tp->t_starttime = ticks;
11533 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
11534 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
11535 		tp->t_tfo_pending = NULL;
11536 	}
11537 	if (tp->t_flags & TF_NEEDFIN) {
11538 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
11539 		tp->t_flags &= ~TF_NEEDFIN;
11540 	} else {
11541 		tcp_state_change(tp, TCPS_ESTABLISHED);
11542 		TCP_PROBE5(accept__established, NULL, tp,
11543 		    mtod(m, const char *), tp, th);
11544 		/*
11545 		 * TFO connections call cc_conn_init() during SYN
11546 		 * processing.  Calling it again here for such connections
11547 		 * is not harmless as it would undo the snd_cwnd reduction
11548 		 * that occurs when a TFO SYN|ACK is retransmitted.
11549 		 */
11550 		if (!IS_FASTOPEN(tp->t_flags))
11551 			rack_cc_conn_init(tp);
11552 	}
11553 	/*
11554 	 * Account for the ACK of our SYN prior to
11555 	 * regular ACK processing below, except for
11556 	 * simultaneous SYN, which is handled later.
11557 	 */
11558 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
11559 		tp->snd_una++;
11560 	/*
11561 	 * If segment contains data or ACK, will call tcp_reass() later; if
11562 	 * not, do so now to pass queued data to user.
11563 	 */
11564 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
11565 		(void) tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
11566 		    (struct mbuf *)0);
11567 		if (tp->t_flags & TF_WAKESOR) {
11568 			tp->t_flags &= ~TF_WAKESOR;
11569 			/* NB: sorwakeup_locked() does an implicit unlock. */
11570 			sorwakeup_locked(so);
11571 		}
11572 	}
11573 	tp->snd_wl1 = th->th_seq - 1;
11574 	/* For syn-recv we need to possibly update the rtt */
11575 	if ((to->to_flags & TOF_TS) != 0 && to->to_tsecr) {
11576 		uint32_t t, mcts;
11577 
11578 		mcts = tcp_ts_getticks();
11579 		t = (mcts - to->to_tsecr) * HPTS_USEC_IN_MSEC;
11580 		if (!tp->t_rttlow || tp->t_rttlow > t)
11581 			tp->t_rttlow = t;
11582 		rack_log_rtt_sample_calc(rack, t, (to->to_tsecr * 1000), (mcts * 1000), 5);
11583 		tcp_rack_xmit_timer(rack, t + 1, 1, t, 0, NULL, 2);
11584 		tcp_rack_xmit_timer_commit(rack, tp);
11585 	}
11586 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11587 		return (ret_val);
11588 	}
11589 	if (tp->t_state == TCPS_FIN_WAIT_1) {
11590 		/* We could have went to FIN_WAIT_1 (or EST) above */
11591 		/*
11592 		 * In FIN_WAIT_1 STATE in addition to the processing for the
11593 		 * ESTABLISHED state if our FIN is now acknowledged then
11594 		 * enter FIN_WAIT_2.
11595 		 */
11596 		if (ourfinisacked) {
11597 			/*
11598 			 * If we can't receive any more data, then closing
11599 			 * user can proceed. Starting the timer is contrary
11600 			 * to the specification, but if we don't get a FIN
11601 			 * we'll hang forever.
11602 			 *
11603 			 * XXXjl: we should release the tp also, and use a
11604 			 * compressed state.
11605 			 */
11606 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11607 				soisdisconnected(so);
11608 				tcp_timer_activate(tp, TT_2MSL,
11609 				    (tcp_fast_finwait2_recycle ?
11610 				    tcp_finwait2_timeout :
11611 				    TP_MAXIDLE(tp)));
11612 			}
11613 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
11614 		}
11615 	}
11616 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11617 	    tiwin, thflags, nxt_pkt));
11618 }
11619 
11620 /*
11621  * Return value of 1, the TCB is unlocked and most
11622  * likely gone, return value of 0, the TCP is still
11623  * locked.
11624  */
11625 static int
11626 rack_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
11627     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11628     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11629 {
11630 	int32_t ret_val = 0;
11631 	struct tcp_rack *rack;
11632 
11633 	/*
11634 	 * Header prediction: check for the two common cases of a
11635 	 * uni-directional data xfer.  If the packet has no control flags,
11636 	 * is in-sequence, the window didn't change and we're not
11637 	 * retransmitting, it's a candidate.  If the length is zero and the
11638 	 * ack moved forward, we're the sender side of the xfer.  Just free
11639 	 * the data acked & wake any higher level process that was blocked
11640 	 * waiting for space.  If the length is non-zero and the ack didn't
11641 	 * move, we're the receiver side.  If we're getting packets in-order
11642 	 * (the reassembly queue is empty), add the data toc The socket
11643 	 * buffer and note that we need a delayed ack. Make sure that the
11644 	 * hidden state-flags are also off. Since we check for
11645 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
11646 	 */
11647 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11648 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
11649 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_ACK)) == TH_ACK) &&
11650 	    __predict_true(SEGQ_EMPTY(tp)) &&
11651 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
11652 		if (tlen == 0) {
11653 			if (rack_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
11654 			    tiwin, nxt_pkt, rack->r_ctl.rc_rcvtime)) {
11655 				return (0);
11656 			}
11657 		} else {
11658 			if (rack_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
11659 			    tiwin, nxt_pkt, iptos)) {
11660 				return (0);
11661 			}
11662 		}
11663 	}
11664 	ctf_calc_rwin(so, tp);
11665 
11666 	if ((thflags & TH_RST) ||
11667 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
11668 		return (ctf_process_rst(m, th, so, tp));
11669 
11670 	/*
11671 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11672 	 * synchronized state.
11673 	 */
11674 	if (thflags & TH_SYN) {
11675 		ctf_challenge_ack(m, th, tp, &ret_val);
11676 		return (ret_val);
11677 	}
11678 	/*
11679 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11680 	 * it's less than ts_recent, drop it.
11681 	 */
11682 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11683 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11684 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11685 			return (ret_val);
11686 	}
11687 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11688 			      &rack->r_ctl.challenge_ack_ts,
11689 			      &rack->r_ctl.challenge_ack_cnt)) {
11690 		return (ret_val);
11691 	}
11692 	/*
11693 	 * If last ACK falls within this segment's sequence numbers, record
11694 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
11695 	 * from the latest proposal of the tcplw@cray.com list (Braden
11696 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
11697 	 * with our earlier PAWS tests, so this check should be solely
11698 	 * predicated on the sequence space of this segment. 3) That we
11699 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11700 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11701 	 * SEG.Len, This modified check allows us to overcome RFC1323's
11702 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11703 	 * p.869. In such cases, we can still calculate the RTT correctly
11704 	 * when RCV.NXT == Last.ACK.Sent.
11705 	 */
11706 	if ((to->to_flags & TOF_TS) != 0 &&
11707 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11708 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11709 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11710 		tp->ts_recent_age = tcp_ts_getticks();
11711 		tp->ts_recent = to->to_tsval;
11712 	}
11713 	/*
11714 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11715 	 * is on (half-synchronized state), then queue data for later
11716 	 * processing; else drop segment and return.
11717 	 */
11718 	if ((thflags & TH_ACK) == 0) {
11719 		if (tp->t_flags & TF_NEEDSYN) {
11720 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11721 			    tiwin, thflags, nxt_pkt));
11722 
11723 		} else if (tp->t_flags & TF_ACKNOW) {
11724 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11725 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11726 			return (ret_val);
11727 		} else {
11728 			ctf_do_drop(m, NULL);
11729 			return (0);
11730 		}
11731 	}
11732 	/*
11733 	 * Ack processing.
11734 	 */
11735 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
11736 		return (ret_val);
11737 	}
11738 	if (sbavail(&so->so_snd)) {
11739 		if (ctf_progress_timeout_check(tp, true)) {
11740 			rack_log_progress_event(rack, tp, tick, PROGRESS_DROP, __LINE__);
11741 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11742 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11743 			return (1);
11744 		}
11745 	}
11746 	/* State changes only happen in rack_process_data() */
11747 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11748 	    tiwin, thflags, nxt_pkt));
11749 }
11750 
11751 /*
11752  * Return value of 1, the TCB is unlocked and most
11753  * likely gone, return value of 0, the TCP is still
11754  * locked.
11755  */
11756 static int
11757 rack_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
11758     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11759     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11760 {
11761 	int32_t ret_val = 0;
11762 	struct tcp_rack *rack;
11763 
11764 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11765 	ctf_calc_rwin(so, tp);
11766 	if ((thflags & TH_RST) ||
11767 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
11768 		return (ctf_process_rst(m, th, so, tp));
11769 	/*
11770 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11771 	 * synchronized state.
11772 	 */
11773 	if (thflags & TH_SYN) {
11774 		ctf_challenge_ack(m, th, tp, &ret_val);
11775 		return (ret_val);
11776 	}
11777 	/*
11778 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11779 	 * it's less than ts_recent, drop it.
11780 	 */
11781 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11782 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11783 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11784 			return (ret_val);
11785 	}
11786 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11787 			      &rack->r_ctl.challenge_ack_ts,
11788 			      &rack->r_ctl.challenge_ack_cnt)) {
11789 		return (ret_val);
11790 	}
11791 	/*
11792 	 * If last ACK falls within this segment's sequence numbers, record
11793 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
11794 	 * from the latest proposal of the tcplw@cray.com list (Braden
11795 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
11796 	 * with our earlier PAWS tests, so this check should be solely
11797 	 * predicated on the sequence space of this segment. 3) That we
11798 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11799 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11800 	 * SEG.Len, This modified check allows us to overcome RFC1323's
11801 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11802 	 * p.869. In such cases, we can still calculate the RTT correctly
11803 	 * when RCV.NXT == Last.ACK.Sent.
11804 	 */
11805 	if ((to->to_flags & TOF_TS) != 0 &&
11806 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11807 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11808 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11809 		tp->ts_recent_age = tcp_ts_getticks();
11810 		tp->ts_recent = to->to_tsval;
11811 	}
11812 	/*
11813 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11814 	 * is on (half-synchronized state), then queue data for later
11815 	 * processing; else drop segment and return.
11816 	 */
11817 	if ((thflags & TH_ACK) == 0) {
11818 		if (tp->t_flags & TF_NEEDSYN) {
11819 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11820 			    tiwin, thflags, nxt_pkt));
11821 
11822 		} else if (tp->t_flags & TF_ACKNOW) {
11823 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11824 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11825 			return (ret_val);
11826 		} else {
11827 			ctf_do_drop(m, NULL);
11828 			return (0);
11829 		}
11830 	}
11831 	/*
11832 	 * Ack processing.
11833 	 */
11834 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
11835 		return (ret_val);
11836 	}
11837 	if (sbavail(&so->so_snd)) {
11838 		if (ctf_progress_timeout_check(tp, true)) {
11839 			rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11840 						tp, tick, PROGRESS_DROP, __LINE__);
11841 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11842 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11843 			return (1);
11844 		}
11845 	}
11846 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11847 	    tiwin, thflags, nxt_pkt));
11848 }
11849 
11850 static int
11851 rack_check_data_after_close(struct mbuf *m,
11852     struct tcpcb *tp, int32_t *tlen, struct tcphdr *th, struct socket *so)
11853 {
11854 	struct tcp_rack *rack;
11855 
11856 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11857 	if (rack->rc_allow_data_af_clo == 0) {
11858 	close_now:
11859 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
11860 		/* tcp_close will kill the inp pre-log the Reset */
11861 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
11862 		tp = tcp_close(tp);
11863 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
11864 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
11865 		return (1);
11866 	}
11867 	if (sbavail(&so->so_snd) == 0)
11868 		goto close_now;
11869 	/* Ok we allow data that is ignored and a followup reset */
11870 	tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
11871 	tp->rcv_nxt = th->th_seq + *tlen;
11872 	tp->t_flags2 |= TF2_DROP_AF_DATA;
11873 	rack->r_wanted_output = 1;
11874 	*tlen = 0;
11875 	return (0);
11876 }
11877 
11878 /*
11879  * Return value of 1, the TCB is unlocked and most
11880  * likely gone, return value of 0, the TCP is still
11881  * locked.
11882  */
11883 static int
11884 rack_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
11885     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
11886     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
11887 {
11888 	int32_t ret_val = 0;
11889 	int32_t ourfinisacked = 0;
11890 	struct tcp_rack *rack;
11891 
11892 	rack = (struct tcp_rack *)tp->t_fb_ptr;
11893 	ctf_calc_rwin(so, tp);
11894 
11895 	if ((thflags & TH_RST) ||
11896 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
11897 		return (ctf_process_rst(m, th, so, tp));
11898 	/*
11899 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
11900 	 * synchronized state.
11901 	 */
11902 	if (thflags & TH_SYN) {
11903 		ctf_challenge_ack(m, th, tp, &ret_val);
11904 		return (ret_val);
11905 	}
11906 	/*
11907 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
11908 	 * it's less than ts_recent, drop it.
11909 	 */
11910 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
11911 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
11912 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
11913 			return (ret_val);
11914 	}
11915 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
11916 			      &rack->r_ctl.challenge_ack_ts,
11917 			      &rack->r_ctl.challenge_ack_cnt)) {
11918 		return (ret_val);
11919 	}
11920 	/*
11921 	 * If new data are received on a connection after the user processes
11922 	 * are gone, then RST the other end.
11923 	 */
11924 	if ((so->so_state & SS_NOFDREF) && tlen) {
11925 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
11926 			return (1);
11927 	}
11928 	/*
11929 	 * If last ACK falls within this segment's sequence numbers, record
11930 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
11931 	 * from the latest proposal of the tcplw@cray.com list (Braden
11932 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
11933 	 * with our earlier PAWS tests, so this check should be solely
11934 	 * predicated on the sequence space of this segment. 3) That we
11935 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
11936 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
11937 	 * SEG.Len, This modified check allows us to overcome RFC1323's
11938 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
11939 	 * p.869. In such cases, we can still calculate the RTT correctly
11940 	 * when RCV.NXT == Last.ACK.Sent.
11941 	 */
11942 	if ((to->to_flags & TOF_TS) != 0 &&
11943 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
11944 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
11945 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
11946 		tp->ts_recent_age = tcp_ts_getticks();
11947 		tp->ts_recent = to->to_tsval;
11948 	}
11949 	/*
11950 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
11951 	 * is on (half-synchronized state), then queue data for later
11952 	 * processing; else drop segment and return.
11953 	 */
11954 	if ((thflags & TH_ACK) == 0) {
11955 		if (tp->t_flags & TF_NEEDSYN) {
11956 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
11957 			    tiwin, thflags, nxt_pkt));
11958 		} else if (tp->t_flags & TF_ACKNOW) {
11959 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
11960 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
11961 			return (ret_val);
11962 		} else {
11963 			ctf_do_drop(m, NULL);
11964 			return (0);
11965 		}
11966 	}
11967 	/*
11968 	 * Ack processing.
11969 	 */
11970 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
11971 		return (ret_val);
11972 	}
11973 	if (ourfinisacked) {
11974 		/*
11975 		 * If we can't receive any more data, then closing user can
11976 		 * proceed. Starting the timer is contrary to the
11977 		 * specification, but if we don't get a FIN we'll hang
11978 		 * forever.
11979 		 *
11980 		 * XXXjl: we should release the tp also, and use a
11981 		 * compressed state.
11982 		 */
11983 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
11984 			soisdisconnected(so);
11985 			tcp_timer_activate(tp, TT_2MSL,
11986 			    (tcp_fast_finwait2_recycle ?
11987 			    tcp_finwait2_timeout :
11988 			    TP_MAXIDLE(tp)));
11989 		}
11990 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
11991 	}
11992 	if (sbavail(&so->so_snd)) {
11993 		if (ctf_progress_timeout_check(tp, true)) {
11994 			rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
11995 						tp, tick, PROGRESS_DROP, __LINE__);
11996 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
11997 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11998 			return (1);
11999 		}
12000 	}
12001 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12002 	    tiwin, thflags, nxt_pkt));
12003 }
12004 
12005 /*
12006  * Return value of 1, the TCB is unlocked and most
12007  * likely gone, return value of 0, the TCP is still
12008  * locked.
12009  */
12010 static int
12011 rack_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
12012     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
12013     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
12014 {
12015 	int32_t ret_val = 0;
12016 	int32_t ourfinisacked = 0;
12017 	struct tcp_rack *rack;
12018 
12019 	rack = (struct tcp_rack *)tp->t_fb_ptr;
12020 	ctf_calc_rwin(so, tp);
12021 
12022 	if ((thflags & TH_RST) ||
12023 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
12024 		return (ctf_process_rst(m, th, so, tp));
12025 	/*
12026 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
12027 	 * synchronized state.
12028 	 */
12029 	if (thflags & TH_SYN) {
12030 		ctf_challenge_ack(m, th, tp, &ret_val);
12031 		return (ret_val);
12032 	}
12033 	/*
12034 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
12035 	 * it's less than ts_recent, drop it.
12036 	 */
12037 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
12038 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
12039 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
12040 			return (ret_val);
12041 	}
12042 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
12043 			      &rack->r_ctl.challenge_ack_ts,
12044 			      &rack->r_ctl.challenge_ack_cnt)) {
12045 		return (ret_val);
12046 	}
12047 	/*
12048 	 * If new data are received on a connection after the user processes
12049 	 * are gone, then RST the other end.
12050 	 */
12051 	if ((so->so_state & SS_NOFDREF) && tlen) {
12052 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
12053 			return (1);
12054 	}
12055 	/*
12056 	 * If last ACK falls within this segment's sequence numbers, record
12057 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
12058 	 * from the latest proposal of the tcplw@cray.com list (Braden
12059 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
12060 	 * with our earlier PAWS tests, so this check should be solely
12061 	 * predicated on the sequence space of this segment. 3) That we
12062 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
12063 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
12064 	 * SEG.Len, This modified check allows us to overcome RFC1323's
12065 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
12066 	 * p.869. In such cases, we can still calculate the RTT correctly
12067 	 * when RCV.NXT == Last.ACK.Sent.
12068 	 */
12069 	if ((to->to_flags & TOF_TS) != 0 &&
12070 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
12071 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
12072 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
12073 		tp->ts_recent_age = tcp_ts_getticks();
12074 		tp->ts_recent = to->to_tsval;
12075 	}
12076 	/*
12077 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
12078 	 * is on (half-synchronized state), then queue data for later
12079 	 * processing; else drop segment and return.
12080 	 */
12081 	if ((thflags & TH_ACK) == 0) {
12082 		if (tp->t_flags & TF_NEEDSYN) {
12083 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12084 			    tiwin, thflags, nxt_pkt));
12085 		} else if (tp->t_flags & TF_ACKNOW) {
12086 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
12087 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
12088 			return (ret_val);
12089 		} else {
12090 			ctf_do_drop(m, NULL);
12091 			return (0);
12092 		}
12093 	}
12094 	/*
12095 	 * Ack processing.
12096 	 */
12097 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
12098 		return (ret_val);
12099 	}
12100 	if (ourfinisacked) {
12101 		tcp_twstart(tp);
12102 		m_freem(m);
12103 		return (1);
12104 	}
12105 	if (sbavail(&so->so_snd)) {
12106 		if (ctf_progress_timeout_check(tp, true)) {
12107 			rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
12108 						tp, tick, PROGRESS_DROP, __LINE__);
12109 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
12110 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
12111 			return (1);
12112 		}
12113 	}
12114 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12115 	    tiwin, thflags, nxt_pkt));
12116 }
12117 
12118 /*
12119  * Return value of 1, the TCB is unlocked and most
12120  * likely gone, return value of 0, the TCP is still
12121  * locked.
12122  */
12123 static int
12124 rack_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
12125     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
12126     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
12127 {
12128 	int32_t ret_val = 0;
12129 	int32_t ourfinisacked = 0;
12130 	struct tcp_rack *rack;
12131 
12132 	rack = (struct tcp_rack *)tp->t_fb_ptr;
12133 	ctf_calc_rwin(so, tp);
12134 
12135 	if ((thflags & TH_RST) ||
12136 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
12137 		return (ctf_process_rst(m, th, so, tp));
12138 	/*
12139 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
12140 	 * synchronized state.
12141 	 */
12142 	if (thflags & TH_SYN) {
12143 		ctf_challenge_ack(m, th, tp, &ret_val);
12144 		return (ret_val);
12145 	}
12146 	/*
12147 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
12148 	 * it's less than ts_recent, drop it.
12149 	 */
12150 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
12151 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
12152 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
12153 			return (ret_val);
12154 	}
12155 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
12156 			      &rack->r_ctl.challenge_ack_ts,
12157 			      &rack->r_ctl.challenge_ack_cnt)) {
12158 		return (ret_val);
12159 	}
12160 	/*
12161 	 * If new data are received on a connection after the user processes
12162 	 * are gone, then RST the other end.
12163 	 */
12164 	if ((so->so_state & SS_NOFDREF) && tlen) {
12165 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
12166 			return (1);
12167 	}
12168 	/*
12169 	 * If last ACK falls within this segment's sequence numbers, record
12170 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
12171 	 * from the latest proposal of the tcplw@cray.com list (Braden
12172 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
12173 	 * with our earlier PAWS tests, so this check should be solely
12174 	 * predicated on the sequence space of this segment. 3) That we
12175 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
12176 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
12177 	 * SEG.Len, This modified check allows us to overcome RFC1323's
12178 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
12179 	 * p.869. In such cases, we can still calculate the RTT correctly
12180 	 * when RCV.NXT == Last.ACK.Sent.
12181 	 */
12182 	if ((to->to_flags & TOF_TS) != 0 &&
12183 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
12184 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
12185 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
12186 		tp->ts_recent_age = tcp_ts_getticks();
12187 		tp->ts_recent = to->to_tsval;
12188 	}
12189 	/*
12190 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
12191 	 * is on (half-synchronized state), then queue data for later
12192 	 * processing; else drop segment and return.
12193 	 */
12194 	if ((thflags & TH_ACK) == 0) {
12195 		if (tp->t_flags & TF_NEEDSYN) {
12196 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12197 			    tiwin, thflags, nxt_pkt));
12198 		} else if (tp->t_flags & TF_ACKNOW) {
12199 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
12200 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
12201 			return (ret_val);
12202 		} else {
12203 			ctf_do_drop(m, NULL);
12204 			return (0);
12205 		}
12206 	}
12207 	/*
12208 	 * case TCPS_LAST_ACK: Ack processing.
12209 	 */
12210 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
12211 		return (ret_val);
12212 	}
12213 	if (ourfinisacked) {
12214 		tp = tcp_close(tp);
12215 		ctf_do_drop(m, tp);
12216 		return (1);
12217 	}
12218 	if (sbavail(&so->so_snd)) {
12219 		if (ctf_progress_timeout_check(tp, true)) {
12220 			rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
12221 						tp, tick, PROGRESS_DROP, __LINE__);
12222 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
12223 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
12224 			return (1);
12225 		}
12226 	}
12227 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12228 	    tiwin, thflags, nxt_pkt));
12229 }
12230 
12231 /*
12232  * Return value of 1, the TCB is unlocked and most
12233  * likely gone, return value of 0, the TCP is still
12234  * locked.
12235  */
12236 static int
12237 rack_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
12238     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
12239     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
12240 {
12241 	int32_t ret_val = 0;
12242 	int32_t ourfinisacked = 0;
12243 	struct tcp_rack *rack;
12244 
12245 	rack = (struct tcp_rack *)tp->t_fb_ptr;
12246 	ctf_calc_rwin(so, tp);
12247 
12248 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
12249 	if ((thflags & TH_RST) ||
12250 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
12251 		return (ctf_process_rst(m, th, so, tp));
12252 	/*
12253 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
12254 	 * synchronized state.
12255 	 */
12256 	if (thflags & TH_SYN) {
12257 		ctf_challenge_ack(m, th, tp, &ret_val);
12258 		return (ret_val);
12259 	}
12260 	/*
12261 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
12262 	 * it's less than ts_recent, drop it.
12263 	 */
12264 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
12265 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
12266 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
12267 			return (ret_val);
12268 	}
12269 	if (_ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val,
12270 			      &rack->r_ctl.challenge_ack_ts,
12271 			      &rack->r_ctl.challenge_ack_cnt)) {
12272 		return (ret_val);
12273 	}
12274 	/*
12275 	 * If new data are received on a connection after the user processes
12276 	 * are gone, then RST the other end.
12277 	 */
12278 	if ((so->so_state & SS_NOFDREF) &&
12279 	    tlen) {
12280 		if (rack_check_data_after_close(m, tp, &tlen, th, so))
12281 			return (1);
12282 	}
12283 	/*
12284 	 * If last ACK falls within this segment's sequence numbers, record
12285 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
12286 	 * from the latest proposal of the tcplw@cray.com list (Braden
12287 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
12288 	 * with our earlier PAWS tests, so this check should be solely
12289 	 * predicated on the sequence space of this segment. 3) That we
12290 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
12291 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
12292 	 * SEG.Len, This modified check allows us to overcome RFC1323's
12293 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
12294 	 * p.869. In such cases, we can still calculate the RTT correctly
12295 	 * when RCV.NXT == Last.ACK.Sent.
12296 	 */
12297 	if ((to->to_flags & TOF_TS) != 0 &&
12298 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
12299 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
12300 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
12301 		tp->ts_recent_age = tcp_ts_getticks();
12302 		tp->ts_recent = to->to_tsval;
12303 	}
12304 	/*
12305 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
12306 	 * is on (half-synchronized state), then queue data for later
12307 	 * processing; else drop segment and return.
12308 	 */
12309 	if ((thflags & TH_ACK) == 0) {
12310 		if (tp->t_flags & TF_NEEDSYN) {
12311 			return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12312 			    tiwin, thflags, nxt_pkt));
12313 		} else if (tp->t_flags & TF_ACKNOW) {
12314 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
12315 			((struct tcp_rack *)tp->t_fb_ptr)->r_wanted_output = 1;
12316 			return (ret_val);
12317 		} else {
12318 			ctf_do_drop(m, NULL);
12319 			return (0);
12320 		}
12321 	}
12322 	/*
12323 	 * Ack processing.
12324 	 */
12325 	if (rack_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
12326 		return (ret_val);
12327 	}
12328 	if (sbavail(&so->so_snd)) {
12329 		if (ctf_progress_timeout_check(tp, true)) {
12330 			rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
12331 						tp, tick, PROGRESS_DROP, __LINE__);
12332 			tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
12333 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
12334 			return (1);
12335 		}
12336 	}
12337 	return (rack_process_data(m, th, so, tp, drop_hdrlen, tlen,
12338 	    tiwin, thflags, nxt_pkt));
12339 }
12340 
12341 static void inline
12342 rack_clear_rate_sample(struct tcp_rack *rack)
12343 {
12344 	rack->r_ctl.rack_rs.rs_flags = RACK_RTT_EMPTY;
12345 	rack->r_ctl.rack_rs.rs_rtt_cnt = 0;
12346 	rack->r_ctl.rack_rs.rs_rtt_tot = 0;
12347 }
12348 
12349 static void
12350 rack_set_pace_segments(struct tcpcb *tp, struct tcp_rack *rack, uint32_t line, uint64_t *fill_override)
12351 {
12352 	uint64_t bw_est, rate_wanted;
12353 	int chged = 0;
12354 	uint32_t user_max, orig_min, orig_max;
12355 
12356 	orig_min = rack->r_ctl.rc_pace_min_segs;
12357 	orig_max = rack->r_ctl.rc_pace_max_segs;
12358 	user_max = ctf_fixed_maxseg(tp) * rack->rc_user_set_max_segs;
12359 	if (ctf_fixed_maxseg(tp) != rack->r_ctl.rc_pace_min_segs)
12360 		chged = 1;
12361 	rack->r_ctl.rc_pace_min_segs = ctf_fixed_maxseg(tp);
12362 	if (rack->use_fixed_rate || rack->rc_force_max_seg) {
12363 		if (user_max != rack->r_ctl.rc_pace_max_segs)
12364 			chged = 1;
12365 	}
12366 	if (rack->rc_force_max_seg) {
12367 		rack->r_ctl.rc_pace_max_segs = user_max;
12368 	} else if (rack->use_fixed_rate) {
12369 		bw_est = rack_get_bw(rack);
12370 		if ((rack->r_ctl.crte == NULL) ||
12371 		    (bw_est != rack->r_ctl.crte->rate)) {
12372 			rack->r_ctl.rc_pace_max_segs = user_max;
12373 		} else {
12374 			/* We are pacing right at the hardware rate */
12375 			uint32_t segsiz;
12376 
12377 			segsiz = min(ctf_fixed_maxseg(tp),
12378 				     rack->r_ctl.rc_pace_min_segs);
12379 			rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(
12380 				                           tp, bw_est, segsiz, 0,
12381 							   rack->r_ctl.crte, NULL);
12382 		}
12383 	} else if (rack->rc_always_pace) {
12384 		if (rack->r_ctl.gp_bw ||
12385 #ifdef NETFLIX_PEAKRATE
12386 		    rack->rc_tp->t_maxpeakrate ||
12387 #endif
12388 		    rack->r_ctl.init_rate) {
12389 			/* We have a rate of some sort set */
12390 			uint32_t  orig;
12391 
12392 			bw_est = rack_get_bw(rack);
12393 			orig = rack->r_ctl.rc_pace_max_segs;
12394 			if (fill_override)
12395 				rate_wanted = *fill_override;
12396 			else
12397 				rate_wanted = rack_get_output_bw(rack, bw_est, NULL, NULL);
12398 			if (rate_wanted) {
12399 				/* We have something */
12400 				rack->r_ctl.rc_pace_max_segs = rack_get_pacing_len(rack,
12401 										   rate_wanted,
12402 										   ctf_fixed_maxseg(rack->rc_tp));
12403 			} else
12404 				rack->r_ctl.rc_pace_max_segs = rack->r_ctl.rc_pace_min_segs;
12405 			if (orig != rack->r_ctl.rc_pace_max_segs)
12406 				chged = 1;
12407 		} else if ((rack->r_ctl.gp_bw == 0) &&
12408 			   (rack->r_ctl.rc_pace_max_segs == 0)) {
12409 			/*
12410 			 * If we have nothing limit us to bursting
12411 			 * out IW sized pieces.
12412 			 */
12413 			chged = 1;
12414 			rack->r_ctl.rc_pace_max_segs = rc_init_window(rack);
12415 		}
12416 	}
12417 	if (rack->r_ctl.rc_pace_max_segs > PACE_MAX_IP_BYTES) {
12418 		chged = 1;
12419 		rack->r_ctl.rc_pace_max_segs = PACE_MAX_IP_BYTES;
12420 	}
12421 	if (chged)
12422 		rack_log_type_pacing_sizes(tp, rack, orig_min, orig_max, line, 2);
12423 }
12424 
12425 
12426 static void
12427 rack_init_fsb_block(struct tcpcb *tp, struct tcp_rack *rack)
12428 {
12429 #ifdef INET6
12430 	struct ip6_hdr *ip6 = NULL;
12431 #endif
12432 #ifdef INET
12433 	struct ip *ip = NULL;
12434 #endif
12435 	struct udphdr *udp = NULL;
12436 
12437 	/* Ok lets fill in the fast block, it can only be used with no IP options! */
12438 #ifdef INET6
12439 	if (rack->r_is_v6) {
12440 		rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12441 		ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
12442 		if (tp->t_port) {
12443 			rack->r_ctl.fsb.tcp_ip_hdr_len += sizeof(struct udphdr);
12444 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
12445 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
12446 			udp->uh_dport = tp->t_port;
12447 			rack->r_ctl.fsb.udp = udp;
12448 			rack->r_ctl.fsb.th = (struct tcphdr *)(udp + 1);
12449 		} else
12450 		{
12451 			rack->r_ctl.fsb.th = (struct tcphdr *)(ip6 + 1);
12452 			rack->r_ctl.fsb.udp = NULL;
12453 		}
12454 		tcpip_fillheaders(rack->rc_inp,
12455 				  tp->t_port,
12456 				  ip6, rack->r_ctl.fsb.th);
12457 	} else
12458 #endif				/* INET6 */
12459 	{
12460 		rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct tcpiphdr);
12461 		ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
12462 		if (tp->t_port) {
12463 			rack->r_ctl.fsb.tcp_ip_hdr_len += sizeof(struct udphdr);
12464 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
12465 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
12466 			udp->uh_dport = tp->t_port;
12467 			rack->r_ctl.fsb.udp = udp;
12468 			rack->r_ctl.fsb.th = (struct tcphdr *)(udp + 1);
12469 		} else
12470 		{
12471 			rack->r_ctl.fsb.udp = NULL;
12472 			rack->r_ctl.fsb.th = (struct tcphdr *)(ip + 1);
12473 		}
12474 		tcpip_fillheaders(rack->rc_inp,
12475 				  tp->t_port,
12476 				  ip, rack->r_ctl.fsb.th);
12477 	}
12478 	rack->r_fsb_inited = 1;
12479 }
12480 
12481 static int
12482 rack_init_fsb(struct tcpcb *tp, struct tcp_rack *rack)
12483 {
12484 	/*
12485 	 * Allocate the larger of spaces V6 if available else just
12486 	 * V4 and include udphdr (overbook)
12487 	 */
12488 #ifdef INET6
12489 	rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr) + sizeof(struct udphdr);
12490 #else
12491 	rack->r_ctl.fsb.tcp_ip_hdr_len = sizeof(struct tcpiphdr) + sizeof(struct udphdr);
12492 #endif
12493 	rack->r_ctl.fsb.tcp_ip_hdr = malloc(rack->r_ctl.fsb.tcp_ip_hdr_len,
12494 					    M_TCPFSB, M_NOWAIT|M_ZERO);
12495 	if (rack->r_ctl.fsb.tcp_ip_hdr == NULL) {
12496 		return (ENOMEM);
12497 	}
12498 	rack->r_fsb_inited = 0;
12499 	return (0);
12500 }
12501 
12502 static int
12503 rack_init(struct tcpcb *tp)
12504 {
12505 	struct tcp_rack *rack = NULL;
12506 	struct rack_sendmap *insret;
12507 	uint32_t iwin, snt, us_cts;
12508 	int err;
12509 
12510 	tp->t_fb_ptr = uma_zalloc(rack_pcb_zone, M_NOWAIT);
12511 	if (tp->t_fb_ptr == NULL) {
12512 		/*
12513 		 * We need to allocate memory but cant. The INP and INP_INFO
12514 		 * locks and they are recusive (happens during setup. So a
12515 		 * scheme to drop the locks fails :(
12516 		 *
12517 		 */
12518 		return (ENOMEM);
12519 	}
12520 	memset(tp->t_fb_ptr, 0, sizeof(struct tcp_rack));
12521 
12522 	rack = (struct tcp_rack *)tp->t_fb_ptr;
12523 	RB_INIT(&rack->r_ctl.rc_mtree);
12524 	TAILQ_INIT(&rack->r_ctl.rc_free);
12525 	TAILQ_INIT(&rack->r_ctl.rc_tmap);
12526 	rack->rc_tp = tp;
12527 	rack->rc_inp = tp->t_inpcb;
12528 	/* Set the flag */
12529 	rack->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
12530 	/* Probably not needed but lets be sure */
12531 	rack_clear_rate_sample(rack);
12532 	/*
12533 	 * Save off the default values, socket options will poke
12534 	 * at these if pacing is not on or we have not yet
12535 	 * reached where pacing is on (gp_ready/fixed enabled).
12536 	 * When they get set into the CC module (when gp_ready
12537 	 * is enabled or we enable fixed) then we will set these
12538 	 * values into the CC and place in here the old values
12539 	 * so we have a restoral. Then we will set the flag
12540 	 * rc_pacing_cc_set. That way whenever we turn off pacing
12541 	 * or switch off this stack, we will know to go restore
12542 	 * the saved values.
12543 	 */
12544 	rack->r_ctl.rc_saved_beta.beta = V_newreno_beta_ecn;
12545 	rack->r_ctl.rc_saved_beta.beta_ecn = V_newreno_beta_ecn;
12546 	/* We want abe like behavior as well */
12547 	rack->r_ctl.rc_saved_beta.newreno_flags = CC_NEWRENO_BETA_ECN;
12548 	rack->r_ctl.rc_reorder_fade = rack_reorder_fade;
12549 	rack->rc_allow_data_af_clo = rack_ignore_data_after_close;
12550 	rack->r_ctl.rc_tlp_threshold = rack_tlp_thresh;
12551 	if (use_rack_rr)
12552 		rack->use_rack_rr = 1;
12553 	if (V_tcp_delack_enabled)
12554 		tp->t_delayed_ack = 1;
12555 	else
12556 		tp->t_delayed_ack = 0;
12557 #ifdef TCP_ACCOUNTING
12558 	if (rack_tcp_accounting) {
12559 		tp->t_flags2 |= TF2_TCP_ACCOUNTING;
12560 	}
12561 #endif
12562 	if (rack_enable_shared_cwnd)
12563 		rack->rack_enable_scwnd = 1;
12564 	rack->rc_user_set_max_segs = rack_hptsi_segments;
12565 	rack->rc_force_max_seg = 0;
12566 	if (rack_use_imac_dack)
12567 		rack->rc_dack_mode = 1;
12568 	TAILQ_INIT(&rack->r_ctl.opt_list);
12569 	rack->r_ctl.rc_reorder_shift = rack_reorder_thresh;
12570 	rack->r_ctl.rc_pkt_delay = rack_pkt_delay;
12571 	rack->r_ctl.rc_tlp_cwnd_reduce = rack_lower_cwnd_at_tlp;
12572 	rack->r_ctl.rc_lowest_us_rtt = 0xffffffff;
12573 	rack->r_ctl.rc_highest_us_rtt = 0;
12574 	rack->r_ctl.bw_rate_cap = rack_bw_rate_cap;
12575 	rack->r_ctl.timer_slop = TICKS_2_USEC(tcp_rexmit_slop);
12576 	if (rack_use_cmp_acks)
12577 		rack->r_use_cmp_ack = 1;
12578 	if (rack_disable_prr)
12579 		rack->rack_no_prr = 1;
12580 	if (rack_gp_no_rec_chg)
12581 		rack->rc_gp_no_rec_chg = 1;
12582 	if (rack_pace_every_seg && tcp_can_enable_pacing()) {
12583 		rack->rc_always_pace = 1;
12584 		if (rack->use_fixed_rate || rack->gp_ready)
12585 			rack_set_cc_pacing(rack);
12586 	} else
12587 		rack->rc_always_pace = 0;
12588 	if (rack_enable_mqueue_for_nonpaced || rack->r_use_cmp_ack)
12589 		rack->r_mbuf_queue = 1;
12590 	else
12591 		rack->r_mbuf_queue = 0;
12592 	if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
12593 		tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
12594 	else
12595 		tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
12596 	rack_set_pace_segments(tp, rack, __LINE__, NULL);
12597 	if (rack_limits_scwnd)
12598 		rack->r_limit_scw = 1;
12599 	else
12600 		rack->r_limit_scw = 0;
12601 	rack->rc_labc = V_tcp_abc_l_var;
12602 	rack->r_ctl.rc_high_rwnd = tp->snd_wnd;
12603 	rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
12604 	rack->r_ctl.rc_rate_sample_method = rack_rate_sample_method;
12605 	rack->rack_tlp_threshold_use = rack_tlp_threshold_use;
12606 	rack->r_ctl.rc_prr_sendalot = rack_send_a_lot_in_prr;
12607 	rack->r_ctl.rc_min_to = rack_min_to;
12608 	microuptime(&rack->r_ctl.act_rcv_time);
12609 	rack->r_ctl.rc_last_time_decay = rack->r_ctl.act_rcv_time;
12610 	rack->r_running_late = 0;
12611 	rack->r_running_early = 0;
12612 	rack->rc_init_win = rack_default_init_window;
12613 	rack->r_ctl.rack_per_of_gp_ss = rack_per_of_gp_ss;
12614 	if (rack_hw_up_only)
12615 		rack->r_up_only = 1;
12616 	if (rack_do_dyn_mul) {
12617 		/* When dynamic adjustment is on CA needs to start at 100% */
12618 		rack->rc_gp_dyn_mul = 1;
12619 		if (rack_do_dyn_mul >= 100)
12620 			rack->r_ctl.rack_per_of_gp_ca = rack_do_dyn_mul;
12621 	} else
12622 		rack->r_ctl.rack_per_of_gp_ca = rack_per_of_gp_ca;
12623 	rack->r_ctl.rack_per_of_gp_rec = rack_per_of_gp_rec;
12624 	rack->r_ctl.rack_per_of_gp_probertt = rack_per_of_gp_probertt;
12625 	rack->r_ctl.rc_tlp_rxt_last_time = tcp_tv_to_mssectick(&rack->r_ctl.act_rcv_time);
12626 	setup_time_filter_small(&rack->r_ctl.rc_gp_min_rtt, FILTER_TYPE_MIN,
12627 				rack_probertt_filter_life);
12628 	us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
12629 	rack->r_ctl.rc_lower_rtt_us_cts = us_cts;
12630 	rack->r_ctl.rc_time_of_last_probertt = us_cts;
12631 	rack->r_ctl.challenge_ack_ts = tcp_ts_getticks();
12632 	rack->r_ctl.rc_time_probertt_starts = 0;
12633 	if (rack_dsack_std_based & 0x1) {
12634 		/* Basically this means all rack timers are at least (srtt + 1/4 srtt) */
12635 		rack->rc_rack_tmr_std_based = 1;
12636 	}
12637 	if (rack_dsack_std_based & 0x2) {
12638 		/* Basically this means  rack timers are extended based on dsack by up to (2 * srtt) */
12639 		rack->rc_rack_use_dsack = 1;
12640 	}
12641 	/* We require at least one measurement, even if the sysctl is 0 */
12642 	if (rack_req_measurements)
12643 		rack->r_ctl.req_measurements = rack_req_measurements;
12644 	else
12645 		rack->r_ctl.req_measurements = 1;
12646 	if (rack_enable_hw_pacing)
12647 		rack->rack_hdw_pace_ena = 1;
12648 	if (rack_hw_rate_caps)
12649 		rack->r_rack_hw_rate_caps = 1;
12650 	/* Do we force on detection? */
12651 #ifdef NETFLIX_EXP_DETECTION
12652 	if (tcp_force_detection)
12653 		rack->do_detection = 1;
12654 	else
12655 #endif
12656 		rack->do_detection = 0;
12657 	if (rack_non_rxt_use_cr)
12658 		rack->rack_rec_nonrxt_use_cr = 1;
12659 	err = rack_init_fsb(tp, rack);
12660 	if (err) {
12661 		uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12662 		tp->t_fb_ptr = NULL;
12663 		return (err);
12664 	}
12665 	if (tp->snd_una != tp->snd_max) {
12666 		/* Create a send map for the current outstanding data */
12667 		struct rack_sendmap *rsm;
12668 
12669 		rsm = rack_alloc(rack);
12670 		if (rsm == NULL) {
12671 			uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12672 			tp->t_fb_ptr = NULL;
12673 			return (ENOMEM);
12674 		}
12675 		rsm->r_no_rtt_allowed = 1;
12676 		rsm->r_tim_lastsent[0] = rack_to_usec_ts(&rack->r_ctl.act_rcv_time);
12677 		rsm->r_rtr_cnt = 1;
12678 		rsm->r_rtr_bytes = 0;
12679 		if (tp->t_flags & TF_SENTFIN) {
12680 			rsm->r_end = tp->snd_max - 1;
12681 			rsm->r_flags |= RACK_HAS_FIN;
12682 		} else {
12683 			rsm->r_end = tp->snd_max;
12684 		}
12685 		if (tp->snd_una == tp->iss) {
12686 			/* The data space is one beyond snd_una */
12687 			rsm->r_flags |= RACK_HAS_SYN;
12688 			rsm->r_start = tp->iss;
12689 			rsm->r_end = rsm->r_start + (tp->snd_max - tp->snd_una);
12690 		} else
12691 			rsm->r_start = tp->snd_una;
12692 		rsm->r_dupack = 0;
12693 		if (rack->rc_inp->inp_socket->so_snd.sb_mb != NULL) {
12694 			rsm->m = sbsndmbuf(&rack->rc_inp->inp_socket->so_snd, 0, &rsm->soff);
12695 			if (rsm->m)
12696 				rsm->orig_m_len = rsm->m->m_len;
12697 			else
12698 				rsm->orig_m_len = 0;
12699 		} else {
12700 			/*
12701 			 * This can happen if we have a stand-alone FIN or
12702 			 *  SYN.
12703 			 */
12704 			rsm->m = NULL;
12705 			rsm->orig_m_len = 0;
12706 			rsm->soff = 0;
12707 		}
12708 		insret = RB_INSERT(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12709 #ifdef INVARIANTS
12710 		if (insret != NULL) {
12711 			panic("Insert in rb tree fails ret:%p rack:%p rsm:%p",
12712 			      insret, rack, rsm);
12713 		}
12714 #endif
12715 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_tmap, rsm, r_tnext);
12716 		rsm->r_in_tmap = 1;
12717 	}
12718 	/*
12719 	 * Timers in Rack are kept in microseconds so lets
12720 	 * convert any initial incoming variables
12721 	 * from ticks into usecs. Note that we
12722 	 * also change the values of t_srtt and t_rttvar, if
12723 	 * they are non-zero. They are kept with a 5
12724 	 * bit decimal so we have to carefully convert
12725 	 * these to get the full precision.
12726 	 */
12727 	rack_convert_rtts(tp);
12728 	tp->t_rttlow = TICKS_2_USEC(tp->t_rttlow);
12729 	if (rack_def_profile)
12730 		rack_set_profile(rack, rack_def_profile);
12731 	/* Cancel the GP measurement in progress */
12732 	tp->t_flags &= ~TF_GPUTINPROG;
12733 	if (SEQ_GT(tp->snd_max, tp->iss))
12734 		snt = tp->snd_max - tp->iss;
12735 	else
12736 		snt = 0;
12737 	iwin = rc_init_window(rack);
12738 	if (snt < iwin) {
12739 		/* We are not past the initial window
12740 		 * so we need to make sure cwnd is
12741 		 * correct.
12742 		 */
12743 		if (tp->snd_cwnd < iwin)
12744 			tp->snd_cwnd = iwin;
12745 		/*
12746 		 * If we are within the initial window
12747 		 * we want ssthresh to be unlimited. Setting
12748 		 * it to the rwnd (which the default stack does
12749 		 * and older racks) is not really a good idea
12750 		 * since we want to be in SS and grow both the
12751 		 * cwnd and the rwnd (via dynamic rwnd growth). If
12752 		 * we set it to the rwnd then as the peer grows its
12753 		 * rwnd we will be stuck in CA and never hit SS.
12754 		 *
12755 		 * Its far better to raise it up high (this takes the
12756 		 * risk that there as been a loss already, probably
12757 		 * we should have an indicator in all stacks of loss
12758 		 * but we don't), but considering the normal use this
12759 		 * is a risk worth taking. The consequences of not
12760 		 * hitting SS are far worse than going one more time
12761 		 * into it early on (before we have sent even a IW).
12762 		 * It is highly unlikely that we will have had a loss
12763 		 * before getting the IW out.
12764 		 */
12765 		tp->snd_ssthresh = 0xffffffff;
12766 	}
12767 	rack_stop_all_timers(tp);
12768 	/* Lets setup the fsb block */
12769 	rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
12770 	rack_log_rtt_shrinks(rack,  us_cts,  tp->t_rxtcur,
12771 			     __LINE__, RACK_RTTS_INIT);
12772 	return (0);
12773 }
12774 
12775 static int
12776 rack_handoff_ok(struct tcpcb *tp)
12777 {
12778 	if ((tp->t_state == TCPS_CLOSED) ||
12779 	    (tp->t_state == TCPS_LISTEN)) {
12780 		/* Sure no problem though it may not stick */
12781 		return (0);
12782 	}
12783 	if ((tp->t_state == TCPS_SYN_SENT) ||
12784 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
12785 		/*
12786 		 * We really don't know if you support sack,
12787 		 * you have to get to ESTAB or beyond to tell.
12788 		 */
12789 		return (EAGAIN);
12790 	}
12791 	if ((tp->t_flags & TF_SENTFIN) && ((tp->snd_max - tp->snd_una) > 1)) {
12792 		/*
12793 		 * Rack will only send a FIN after all data is acknowledged.
12794 		 * So in this case we have more data outstanding. We can't
12795 		 * switch stacks until either all data and only the FIN
12796 		 * is left (in which case rack_init() now knows how
12797 		 * to deal with that) <or> all is acknowledged and we
12798 		 * are only left with incoming data, though why you
12799 		 * would want to switch to rack after all data is acknowledged
12800 		 * I have no idea (rrs)!
12801 		 */
12802 		return (EAGAIN);
12803 	}
12804 	if ((tp->t_flags & TF_SACK_PERMIT) || rack_sack_not_required){
12805 		return (0);
12806 	}
12807 	/*
12808 	 * If we reach here we don't do SACK on this connection so we can
12809 	 * never do rack.
12810 	 */
12811 	return (EINVAL);
12812 }
12813 
12814 
12815 static void
12816 rack_fini(struct tcpcb *tp, int32_t tcb_is_purged)
12817 {
12818 	int ack_cmp = 0;
12819 
12820 	if (tp->t_fb_ptr) {
12821 		struct tcp_rack *rack;
12822 		struct rack_sendmap *rsm, *nrsm, *rm;
12823 
12824 		rack = (struct tcp_rack *)tp->t_fb_ptr;
12825 		if (tp->t_in_pkt) {
12826 			/*
12827 			 * It is unsafe to process the packets since a
12828 			 * reset may be lurking in them (its rare but it
12829 			 * can occur). If we were to find a RST, then we
12830 			 * would end up dropping the connection and the
12831 			 * INP lock, so when we return the caller (tcp_usrreq)
12832 			 * will blow up when it trys to unlock the inp.
12833 			 */
12834 			struct mbuf *save, *m;
12835 
12836 			m = tp->t_in_pkt;
12837 			tp->t_in_pkt = NULL;
12838 			tp->t_tail_pkt = NULL;
12839 			while (m) {
12840 				save = m->m_nextpkt;
12841 				m->m_nextpkt = NULL;
12842 				m_freem(m);
12843 				m = save;
12844 			}
12845 			if ((tp->t_inpcb) &&
12846 			    (tp->t_inpcb->inp_flags2 & INP_MBUF_ACKCMP))
12847 				ack_cmp = 1;
12848 			if (ack_cmp) {
12849 				/* Total if we used large or small (if ack-cmp was used). */
12850 				if (rack->rc_inp->inp_flags2 & INP_MBUF_L_ACKS)
12851 					counter_u64_add(rack_large_ackcmp, 1);
12852 				else
12853 					counter_u64_add(rack_small_ackcmp, 1);
12854 			}
12855 		}
12856 		tp->t_flags &= ~TF_FORCEDATA;
12857 #ifdef NETFLIX_SHARED_CWND
12858 		if (rack->r_ctl.rc_scw) {
12859 			uint32_t limit;
12860 
12861 			if (rack->r_limit_scw)
12862 				limit = max(1, rack->r_ctl.rc_lowest_us_rtt);
12863 			else
12864 				limit = 0;
12865 			tcp_shared_cwnd_free_full(tp, rack->r_ctl.rc_scw,
12866 						  rack->r_ctl.rc_scw_index,
12867 						  limit);
12868 			rack->r_ctl.rc_scw = NULL;
12869 		}
12870 #endif
12871 		if (rack->r_ctl.fsb.tcp_ip_hdr) {
12872 			free(rack->r_ctl.fsb.tcp_ip_hdr, M_TCPFSB);
12873 			rack->r_ctl.fsb.tcp_ip_hdr = NULL;
12874 			rack->r_ctl.fsb.th = NULL;
12875 		}
12876 		/* Convert back to ticks, with  */
12877 		if (tp->t_srtt > 1) {
12878 			uint32_t val, frac;
12879 
12880 			val = USEC_2_TICKS(tp->t_srtt);
12881 			frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
12882 			tp->t_srtt = val << TCP_RTT_SHIFT;
12883 			/*
12884 			 * frac is the fractional part here is left
12885 			 * over from converting to hz and shifting.
12886 			 * We need to convert this to the 5 bit
12887 			 * remainder.
12888 			 */
12889 			if (frac) {
12890 				if (hz == 1000) {
12891 					frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
12892 				} else {
12893 					frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
12894 				}
12895 				tp->t_srtt += frac;
12896 			}
12897 		}
12898 		if (tp->t_rttvar) {
12899 			uint32_t val, frac;
12900 
12901 			val = USEC_2_TICKS(tp->t_rttvar);
12902 			frac = tp->t_srtt % (HPTS_USEC_IN_SEC / hz);
12903 			tp->t_rttvar = val <<  TCP_RTTVAR_SHIFT;
12904 			/*
12905 			 * frac is the fractional part here is left
12906 			 * over from converting to hz and shifting.
12907 			 * We need to convert this to the 5 bit
12908 			 * remainder.
12909 			 */
12910 			if (frac) {
12911 				if (hz == 1000) {
12912 					frac = (((uint64_t)frac *  (uint64_t)TCP_RTT_SCALE) / (uint64_t)HPTS_USEC_IN_MSEC);
12913 				} else {
12914 					frac = (((uint64_t)frac * (uint64_t)(hz) * (uint64_t)TCP_RTT_SCALE) /(uint64_t)HPTS_USEC_IN_SEC);
12915 				}
12916 				tp->t_rttvar += frac;
12917 			}
12918 		}
12919 		tp->t_rxtcur = USEC_2_TICKS(tp->t_rxtcur);
12920 		tp->t_rttlow = USEC_2_TICKS(tp->t_rttlow);
12921 		if (rack->rc_always_pace) {
12922 			tcp_decrement_paced_conn();
12923 			rack_undo_cc_pacing(rack);
12924 			rack->rc_always_pace = 0;
12925 		}
12926 		/* Clean up any options if they were not applied */
12927 		while (!TAILQ_EMPTY(&rack->r_ctl.opt_list)) {
12928 			struct deferred_opt_list *dol;
12929 
12930 			dol = TAILQ_FIRST(&rack->r_ctl.opt_list);
12931 			TAILQ_REMOVE(&rack->r_ctl.opt_list, dol, next);
12932 			free(dol, M_TCPDO);
12933 		}
12934 		/* rack does not use force data but other stacks may clear it */
12935 		if (rack->r_ctl.crte != NULL) {
12936 			tcp_rel_pacing_rate(rack->r_ctl.crte, tp);
12937 			rack->rack_hdrw_pacing = 0;
12938 			rack->r_ctl.crte = NULL;
12939 		}
12940 #ifdef TCP_BLACKBOX
12941 		tcp_log_flowend(tp);
12942 #endif
12943 		RB_FOREACH_SAFE(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree, nrsm) {
12944 			rm = RB_REMOVE(rack_rb_tree_head, &rack->r_ctl.rc_mtree, rsm);
12945 #ifdef INVARIANTS
12946 			if (rm != rsm) {
12947 				panic("At fini, rack:%p rsm:%p rm:%p",
12948 				      rack, rsm, rm);
12949 			}
12950 #endif
12951 			uma_zfree(rack_zone, rsm);
12952 		}
12953 		rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
12954 		while (rsm) {
12955 			TAILQ_REMOVE(&rack->r_ctl.rc_free, rsm, r_tnext);
12956 			uma_zfree(rack_zone, rsm);
12957 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_free);
12958 		}
12959 		rack->rc_free_cnt = 0;
12960 		uma_zfree(rack_pcb_zone, tp->t_fb_ptr);
12961 		tp->t_fb_ptr = NULL;
12962 	}
12963 	if (tp->t_inpcb) {
12964 		tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
12965 		tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12966 		tp->t_inpcb->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
12967 		tp->t_inpcb->inp_flags2 &= ~INP_MBUF_ACKCMP;
12968 		/* Cancel the GP measurement in progress */
12969 		tp->t_flags &= ~TF_GPUTINPROG;
12970 		tp->t_inpcb->inp_flags2 &= ~INP_MBUF_L_ACKS;
12971 	}
12972 	/* Make sure snd_nxt is correctly set */
12973 	tp->snd_nxt = tp->snd_max;
12974 }
12975 
12976 static void
12977 rack_set_state(struct tcpcb *tp, struct tcp_rack *rack)
12978 {
12979 	if ((rack->r_state == TCPS_CLOSED) && (tp->t_state != TCPS_CLOSED)) {
12980 		rack->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
12981 	}
12982 	switch (tp->t_state) {
12983 	case TCPS_SYN_SENT:
12984 		rack->r_state = TCPS_SYN_SENT;
12985 		rack->r_substate = rack_do_syn_sent;
12986 		break;
12987 	case TCPS_SYN_RECEIVED:
12988 		rack->r_state = TCPS_SYN_RECEIVED;
12989 		rack->r_substate = rack_do_syn_recv;
12990 		break;
12991 	case TCPS_ESTABLISHED:
12992 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
12993 		rack->r_state = TCPS_ESTABLISHED;
12994 		rack->r_substate = rack_do_established;
12995 		break;
12996 	case TCPS_CLOSE_WAIT:
12997 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
12998 		rack->r_state = TCPS_CLOSE_WAIT;
12999 		rack->r_substate = rack_do_close_wait;
13000 		break;
13001 	case TCPS_FIN_WAIT_1:
13002 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
13003 		rack->r_state = TCPS_FIN_WAIT_1;
13004 		rack->r_substate = rack_do_fin_wait_1;
13005 		break;
13006 	case TCPS_CLOSING:
13007 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
13008 		rack->r_state = TCPS_CLOSING;
13009 		rack->r_substate = rack_do_closing;
13010 		break;
13011 	case TCPS_LAST_ACK:
13012 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
13013 		rack->r_state = TCPS_LAST_ACK;
13014 		rack->r_substate = rack_do_lastack;
13015 		break;
13016 	case TCPS_FIN_WAIT_2:
13017 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
13018 		rack->r_state = TCPS_FIN_WAIT_2;
13019 		rack->r_substate = rack_do_fin_wait_2;
13020 		break;
13021 	case TCPS_LISTEN:
13022 	case TCPS_CLOSED:
13023 	case TCPS_TIME_WAIT:
13024 	default:
13025 		break;
13026 	};
13027 	if (rack->r_use_cmp_ack && TCPS_HAVEESTABLISHED(tp->t_state))
13028 		rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
13029 
13030 }
13031 
13032 static void
13033 rack_timer_audit(struct tcpcb *tp, struct tcp_rack *rack, struct sockbuf *sb)
13034 {
13035 	/*
13036 	 * We received an ack, and then did not
13037 	 * call send or were bounced out due to the
13038 	 * hpts was running. Now a timer is up as well, is
13039 	 * it the right timer?
13040 	 */
13041 	struct rack_sendmap *rsm;
13042 	int tmr_up;
13043 
13044 	tmr_up = rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
13045 	if (rack->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
13046 		return;
13047 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
13048 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
13049 	    (tmr_up == PACE_TMR_RXT)) {
13050 		/* Should be an RXT */
13051 		return;
13052 	}
13053 	if (rsm == NULL) {
13054 		/* Nothing outstanding? */
13055 		if (tp->t_flags & TF_DELACK) {
13056 			if (tmr_up == PACE_TMR_DELACK)
13057 				/* We are supposed to have delayed ack up and we do */
13058 				return;
13059 		} else if (sbavail(&tp->t_inpcb->inp_socket->so_snd) && (tmr_up == PACE_TMR_RXT)) {
13060 			/*
13061 			 * if we hit enobufs then we would expect the possiblity
13062 			 * of nothing outstanding and the RXT up (and the hptsi timer).
13063 			 */
13064 			return;
13065 		} else if (((V_tcp_always_keepalive ||
13066 			     rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
13067 			    (tp->t_state <= TCPS_CLOSING)) &&
13068 			   (tmr_up == PACE_TMR_KEEP) &&
13069 			   (tp->snd_max == tp->snd_una)) {
13070 			/* We should have keep alive up and we do */
13071 			return;
13072 		}
13073 	}
13074 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
13075 		   ((tmr_up == PACE_TMR_TLP) ||
13076 		    (tmr_up == PACE_TMR_RACK) ||
13077 		    (tmr_up == PACE_TMR_RXT))) {
13078 		/*
13079 		 * Either a Rack, TLP or RXT is fine if  we
13080 		 * have outstanding data.
13081 		 */
13082 		return;
13083 	} else if (tmr_up == PACE_TMR_DELACK) {
13084 		/*
13085 		 * If the delayed ack was going to go off
13086 		 * before the rtx/tlp/rack timer were going to
13087 		 * expire, then that would be the timer in control.
13088 		 * Note we don't check the time here trusting the
13089 		 * code is correct.
13090 		 */
13091 		return;
13092 	}
13093 	/*
13094 	 * Ok the timer originally started is not what we want now.
13095 	 * We will force the hpts to be stopped if any, and restart
13096 	 * with the slot set to what was in the saved slot.
13097 	 */
13098 	if (rack->rc_inp->inp_in_hpts) {
13099 		if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
13100 			uint32_t us_cts;
13101 
13102 			us_cts = tcp_get_usecs(NULL);
13103 			if (TSTMP_GT(rack->r_ctl.rc_last_output_to, us_cts)) {
13104 				rack->r_early = 1;
13105 				rack->r_ctl.rc_agg_early += (rack->r_ctl.rc_last_output_to - us_cts);
13106 			}
13107 			rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
13108 		}
13109 		tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_OUTPUT);
13110 	}
13111 	rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13112 	rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
13113 }
13114 
13115 
13116 static void
13117 rack_do_win_updates(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tiwin, uint32_t seq, uint32_t ack, uint32_t cts, uint32_t high_seq)
13118 {
13119 	if ((SEQ_LT(tp->snd_wl1, seq) ||
13120 	    (tp->snd_wl1 == seq && (SEQ_LT(tp->snd_wl2, ack) ||
13121 	    (tp->snd_wl2 == ack && tiwin > tp->snd_wnd))))) {
13122 		/* keep track of pure window updates */
13123 		if ((tp->snd_wl2 == ack) && (tiwin > tp->snd_wnd))
13124 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
13125 		tp->snd_wnd = tiwin;
13126 		rack_validate_fo_sendwin_up(tp, rack);
13127 		tp->snd_wl1 = seq;
13128 		tp->snd_wl2 = ack;
13129 		if (tp->snd_wnd > tp->max_sndwnd)
13130 			tp->max_sndwnd = tp->snd_wnd;
13131 	    rack->r_wanted_output = 1;
13132 	} else if ((tp->snd_wl2 == ack) && (tiwin < tp->snd_wnd)) {
13133 		tp->snd_wnd = tiwin;
13134 		rack_validate_fo_sendwin_up(tp, rack);
13135 		tp->snd_wl1 = seq;
13136 		tp->snd_wl2 = ack;
13137 	} else {
13138 		/* Not a valid win update */
13139 		return;
13140 	}
13141 	if (tp->snd_wnd > tp->max_sndwnd)
13142 		tp->max_sndwnd = tp->snd_wnd;
13143 	if (tp->snd_wnd < (tp->snd_max - high_seq)) {
13144 		/* The peer collapsed the window */
13145 		rack_collapsed_window(rack);
13146 	} else if (rack->rc_has_collapsed)
13147 		rack_un_collapse_window(rack);
13148 	/* Do we exit persists? */
13149 	if ((rack->rc_in_persist != 0) &&
13150 	    (tp->snd_wnd >= min((rack->r_ctl.rc_high_rwnd/2),
13151 				rack->r_ctl.rc_pace_min_segs))) {
13152 		rack_exit_persist(tp, rack, cts);
13153 	}
13154 	/* Do we enter persists? */
13155 	if ((rack->rc_in_persist == 0) &&
13156 	    (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), rack->r_ctl.rc_pace_min_segs)) &&
13157 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
13158 	    (tp->snd_max == tp->snd_una) &&
13159 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
13160 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
13161 		/*
13162 		 * Here the rwnd is less than
13163 		 * the pacing size, we are established,
13164 		 * nothing is outstanding, and there is
13165 		 * data to send. Enter persists.
13166 		 */
13167 		rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
13168 	}
13169 }
13170 
13171 static void
13172 rack_log_input_packet(struct tcpcb *tp, struct tcp_rack *rack, struct tcp_ackent *ae, int ackval, uint32_t high_seq)
13173 {
13174 
13175 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13176 		union tcp_log_stackspecific log;
13177 		struct timeval ltv;
13178 		char tcp_hdr_buf[60];
13179 		struct tcphdr *th;
13180 		struct timespec ts;
13181 		uint32_t orig_snd_una;
13182 		uint8_t xx = 0;
13183 
13184 #ifdef NETFLIX_HTTP_LOGGING
13185 		struct http_sendfile_track *http_req;
13186 
13187 		if (SEQ_GT(ae->ack, tp->snd_una)) {
13188 			http_req = tcp_http_find_req_for_seq(tp, (ae->ack-1));
13189 		} else {
13190 			http_req = tcp_http_find_req_for_seq(tp, ae->ack);
13191 		}
13192 #endif
13193 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
13194 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
13195 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
13196 		if (rack->rack_no_prr == 0)
13197 			log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
13198 		else
13199 			log.u_bbr.flex1 = 0;
13200 		log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
13201 		log.u_bbr.use_lt_bw <<= 1;
13202 		log.u_bbr.use_lt_bw |= rack->r_might_revert;
13203 		log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
13204 		log.u_bbr.inflight = ctf_flight_size(tp, rack->r_ctl.rc_sacked);
13205 		log.u_bbr.pkts_out = tp->t_maxseg;
13206 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
13207 		log.u_bbr.flex7 = 1;
13208 		log.u_bbr.lost = ae->flags;
13209 		log.u_bbr.cwnd_gain = ackval;
13210 		log.u_bbr.pacing_gain = 0x2;
13211 		if (ae->flags & TSTMP_HDWR) {
13212 			/* Record the hardware timestamp if present */
13213 			log.u_bbr.flex3 = M_TSTMP;
13214 			ts.tv_sec = ae->timestamp / 1000000000;
13215 			ts.tv_nsec = ae->timestamp % 1000000000;
13216 			ltv.tv_sec = ts.tv_sec;
13217 			ltv.tv_usec = ts.tv_nsec / 1000;
13218 			log.u_bbr.lt_epoch = tcp_tv_to_usectick(&ltv);
13219 		} else if (ae->flags & TSTMP_LRO) {
13220 			/* Record the LRO the arrival timestamp */
13221 			log.u_bbr.flex3 = M_TSTMP_LRO;
13222 			ts.tv_sec = ae->timestamp / 1000000000;
13223 			ts.tv_nsec = ae->timestamp % 1000000000;
13224 			ltv.tv_sec = ts.tv_sec;
13225 			ltv.tv_usec = ts.tv_nsec / 1000;
13226 			log.u_bbr.flex5 = tcp_tv_to_usectick(&ltv);
13227 		}
13228 		log.u_bbr.timeStamp = tcp_get_usecs(&ltv);
13229 		/* Log the rcv time */
13230 		log.u_bbr.delRate = ae->timestamp;
13231 #ifdef NETFLIX_HTTP_LOGGING
13232 		log.u_bbr.applimited = tp->t_http_closed;
13233 		log.u_bbr.applimited <<= 8;
13234 		log.u_bbr.applimited |= tp->t_http_open;
13235 		log.u_bbr.applimited <<= 8;
13236 		log.u_bbr.applimited |= tp->t_http_req;
13237 		if (http_req) {
13238 			/* Copy out any client req info */
13239 			/* seconds */
13240 			log.u_bbr.pkt_epoch = (http_req->localtime / HPTS_USEC_IN_SEC);
13241 			/* useconds */
13242 			log.u_bbr.delivered = (http_req->localtime % HPTS_USEC_IN_SEC);
13243 			log.u_bbr.rttProp = http_req->timestamp;
13244 			log.u_bbr.cur_del_rate = http_req->start;
13245 			if (http_req->flags & TCP_HTTP_TRACK_FLG_OPEN) {
13246 				log.u_bbr.flex8 |= 1;
13247 			} else {
13248 				log.u_bbr.flex8 |= 2;
13249 				log.u_bbr.bw_inuse = http_req->end;
13250 			}
13251 			log.u_bbr.flex6 = http_req->start_seq;
13252 			if (http_req->flags & TCP_HTTP_TRACK_FLG_COMP) {
13253 				log.u_bbr.flex8 |= 4;
13254 				log.u_bbr.epoch = http_req->end_seq;
13255 			}
13256 		}
13257 #endif
13258 		memset(tcp_hdr_buf, 0, sizeof(tcp_hdr_buf));
13259 		th = (struct tcphdr *)tcp_hdr_buf;
13260 		th->th_seq = ae->seq;
13261 		th->th_ack = ae->ack;
13262 		th->th_win = ae->win;
13263 		/* Now fill in the ports */
13264 		th->th_sport = tp->t_inpcb->inp_fport;
13265 		th->th_dport = tp->t_inpcb->inp_lport;
13266 		th->th_flags = ae->flags & 0xff;
13267 		/* Now do we have a timestamp option? */
13268 		if (ae->flags & HAS_TSTMP) {
13269 			u_char *cp;
13270 			uint32_t val;
13271 
13272 			th->th_off = ((sizeof(struct tcphdr) + TCPOLEN_TSTAMP_APPA) >> 2);
13273 			cp = (u_char *)(th + 1);
13274 			*cp = TCPOPT_NOP;
13275 			cp++;
13276 			*cp = TCPOPT_NOP;
13277 			cp++;
13278 			*cp = TCPOPT_TIMESTAMP;
13279 			cp++;
13280 			*cp = TCPOLEN_TIMESTAMP;
13281 			cp++;
13282 			val = htonl(ae->ts_value);
13283 			bcopy((char *)&val,
13284 			      (char *)cp, sizeof(uint32_t));
13285 			val = htonl(ae->ts_echo);
13286 			bcopy((char *)&val,
13287 			      (char *)(cp + 4), sizeof(uint32_t));
13288 		} else
13289 			th->th_off = (sizeof(struct tcphdr) >> 2);
13290 
13291 		/*
13292 		 * For sane logging we need to play a little trick.
13293 		 * If the ack were fully processed we would have moved
13294 		 * snd_una to high_seq, but since compressed acks are
13295 		 * processed in two phases, at this point (logging) snd_una
13296 		 * won't be advanced. So we would see multiple acks showing
13297 		 * the advancement. We can prevent that by "pretending" that
13298 		 * snd_una was advanced and then un-advancing it so that the
13299 		 * logging code has the right value for tlb_snd_una.
13300 		 */
13301 		if (tp->snd_una != high_seq) {
13302 			orig_snd_una = tp->snd_una;
13303 			tp->snd_una = high_seq;
13304 			xx = 1;
13305 		} else
13306 			xx = 0;
13307 		TCP_LOG_EVENTP(tp, th,
13308 			       &tp->t_inpcb->inp_socket->so_rcv,
13309 			       &tp->t_inpcb->inp_socket->so_snd, TCP_LOG_IN, 0,
13310 			       0, &log, true, &ltv);
13311 		if (xx) {
13312 			tp->snd_una = orig_snd_una;
13313 		}
13314 	}
13315 
13316 }
13317 
13318 static int
13319 rack_do_compressed_ack_processing(struct tcpcb *tp, struct socket *so, struct mbuf *m, int nxt_pkt, struct timeval *tv)
13320 {
13321 	/*
13322 	 * Handle a "special" compressed ack mbuf. Each incoming
13323 	 * ack has only four possible dispositions:
13324 	 *
13325 	 * A) It moves the cum-ack forward
13326 	 * B) It is behind the cum-ack.
13327 	 * C) It is a window-update ack.
13328 	 * D) It is a dup-ack.
13329 	 *
13330 	 * Note that we can have between 1 -> TCP_COMP_ACK_ENTRIES
13331 	 * in the incoming mbuf. We also need to still pay attention
13332 	 * to nxt_pkt since there may be another packet after this
13333 	 * one.
13334 	 */
13335 #ifdef TCP_ACCOUNTING
13336 	uint64_t ts_val;
13337 	uint64_t rdstc;
13338 #endif
13339 	int segsiz;
13340 	struct timespec ts;
13341 	struct tcp_rack *rack;
13342 	struct tcp_ackent *ae;
13343 	uint32_t tiwin, ms_cts, cts, acked, acked_amount, high_seq, win_seq, the_win, win_upd_ack;
13344 	int cnt, i, did_out, ourfinisacked = 0;
13345 	struct tcpopt to_holder, *to = NULL;
13346 	int win_up_req = 0;
13347 	int nsegs = 0;
13348 	int under_pacing = 1;
13349 	int recovery = 0;
13350 	int idx;
13351 #ifdef TCP_ACCOUNTING
13352 	sched_pin();
13353 #endif
13354 	rack = (struct tcp_rack *)tp->t_fb_ptr;
13355 	if (rack->gp_ready &&
13356 	    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT))
13357 		under_pacing = 0;
13358 	else
13359 		under_pacing = 1;
13360 
13361 	if (rack->r_state != tp->t_state)
13362 		rack_set_state(tp, rack);
13363 	if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
13364 	    (tp->t_flags & TF_GPUTINPROG)) {
13365 		/*
13366 		 * We have a goodput in progress
13367 		 * and we have entered a late state.
13368 		 * Do we have enough data in the sb
13369 		 * to handle the GPUT request?
13370 		 */
13371 		uint32_t bytes;
13372 
13373 		bytes = tp->gput_ack - tp->gput_seq;
13374 		if (SEQ_GT(tp->gput_seq, tp->snd_una))
13375 			bytes += tp->gput_seq - tp->snd_una;
13376 		if (bytes > sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
13377 			/*
13378 			 * There are not enough bytes in the socket
13379 			 * buffer that have been sent to cover this
13380 			 * measurement. Cancel it.
13381 			 */
13382 			rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
13383 						   rack->r_ctl.rc_gp_srtt /*flex1*/,
13384 						   tp->gput_seq,
13385 						   0, 0, 18, __LINE__, NULL, 0);
13386 			tp->t_flags &= ~TF_GPUTINPROG;
13387 		}
13388 	}
13389 	to = &to_holder;
13390 	to->to_flags = 0;
13391 	KASSERT((m->m_len >= sizeof(struct tcp_ackent)),
13392 		("tp:%p m_cmpack:%p with invalid len:%u", tp, m, m->m_len));
13393 	cnt = m->m_len / sizeof(struct tcp_ackent);
13394 	idx = cnt / 5;
13395 	if (idx >= MAX_NUM_OF_CNTS)
13396 		idx = MAX_NUM_OF_CNTS - 1;
13397 	counter_u64_add(rack_proc_comp_ack[idx], 1);
13398 	counter_u64_add(rack_multi_single_eq, cnt);
13399 	high_seq = tp->snd_una;
13400 	the_win = tp->snd_wnd;
13401 	win_seq = tp->snd_wl1;
13402 	win_upd_ack = tp->snd_wl2;
13403 	cts = tcp_tv_to_usectick(tv);
13404 	ms_cts = tcp_tv_to_mssectick(tv);
13405 	segsiz = ctf_fixed_maxseg(tp);
13406 	if ((rack->rc_gp_dyn_mul) &&
13407 	    (rack->use_fixed_rate == 0) &&
13408 	    (rack->rc_always_pace)) {
13409 		/* Check in on probertt */
13410 		rack_check_probe_rtt(rack, cts);
13411 	}
13412 	for (i = 0; i < cnt; i++) {
13413 #ifdef TCP_ACCOUNTING
13414 		ts_val = get_cyclecount();
13415 #endif
13416 		rack_clear_rate_sample(rack);
13417 		ae = ((mtod(m, struct tcp_ackent *)) + i);
13418 		/* Setup the window */
13419 		tiwin = ae->win << tp->snd_scale;
13420 		/* figure out the type of ack */
13421 		if (SEQ_LT(ae->ack, high_seq)) {
13422 			/* Case B*/
13423 			ae->ack_val_set = ACK_BEHIND;
13424 		} else if (SEQ_GT(ae->ack, high_seq)) {
13425 			/* Case A */
13426 			ae->ack_val_set = ACK_CUMACK;
13427 		} else if (tiwin == the_win) {
13428 			/* Case D */
13429 			ae->ack_val_set = ACK_DUPACK;
13430 		} else {
13431 			/* Case C */
13432 			ae->ack_val_set = ACK_RWND;
13433 		}
13434 		rack_log_input_packet(tp, rack, ae, ae->ack_val_set, high_seq);
13435 		/* Validate timestamp */
13436 		if (ae->flags & HAS_TSTMP) {
13437 			/* Setup for a timestamp */
13438 			to->to_flags = TOF_TS;
13439 			ae->ts_echo -= tp->ts_offset;
13440 			to->to_tsecr = ae->ts_echo;
13441 			to->to_tsval = ae->ts_value;
13442 			/*
13443 			 * If echoed timestamp is later than the current time, fall back to
13444 			 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
13445 			 * were used when this connection was established.
13446 			 */
13447 			if (TSTMP_GT(ae->ts_echo, ms_cts))
13448 				to->to_tsecr = 0;
13449 			if (tp->ts_recent &&
13450 			    TSTMP_LT(ae->ts_value, tp->ts_recent)) {
13451 				if (ctf_ts_check_ac(tp, (ae->flags & 0xff))) {
13452 #ifdef TCP_ACCOUNTING
13453 					rdstc = get_cyclecount();
13454 					if (rdstc > ts_val) {
13455 						counter_u64_add(tcp_proc_time[ae->ack_val_set] ,
13456 								(rdstc - ts_val));
13457 						if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13458 							tp->tcp_proc_time[ae->ack_val_set] += (rdstc - ts_val);
13459 						}
13460 					}
13461 #endif
13462 					continue;
13463 				}
13464 			}
13465 			if (SEQ_LEQ(ae->seq, tp->last_ack_sent) &&
13466 			    SEQ_LEQ(tp->last_ack_sent, ae->seq)) {
13467 				tp->ts_recent_age = tcp_ts_getticks();
13468 				tp->ts_recent = ae->ts_value;
13469 			}
13470 		} else {
13471 			/* Setup for a no options */
13472 			to->to_flags = 0;
13473 		}
13474 		/* Update the rcv time and perform idle reduction possibly */
13475 		if  (tp->t_idle_reduce &&
13476 		     (tp->snd_max == tp->snd_una) &&
13477 		     ((ticks - tp->t_rcvtime) >= tp->t_rxtcur)) {
13478 			counter_u64_add(rack_input_idle_reduces, 1);
13479 			rack_cc_after_idle(rack, tp);
13480 		}
13481 		tp->t_rcvtime = ticks;
13482 		/* Now what about ECN? */
13483 		if (tp->t_flags2 & TF2_ECN_PERMIT) {
13484 			if (ae->flags & TH_CWR) {
13485 				tp->t_flags2 &= ~TF2_ECN_SND_ECE;
13486 				tp->t_flags |= TF_ACKNOW;
13487 			}
13488 			switch (ae->codepoint & IPTOS_ECN_MASK) {
13489 			case IPTOS_ECN_CE:
13490 				tp->t_flags2 |= TF2_ECN_SND_ECE;
13491 				KMOD_TCPSTAT_INC(tcps_ecn_ce);
13492 				break;
13493 			case IPTOS_ECN_ECT0:
13494 				KMOD_TCPSTAT_INC(tcps_ecn_ect0);
13495 				break;
13496 			case IPTOS_ECN_ECT1:
13497 				KMOD_TCPSTAT_INC(tcps_ecn_ect1);
13498 				break;
13499 			}
13500 
13501 			/* Process a packet differently from RFC3168. */
13502 			cc_ecnpkt_handler_flags(tp, ae->flags, ae->codepoint);
13503 			/* Congestion experienced. */
13504 			if (ae->flags & TH_ECE) {
13505 				rack_cong_signal(tp,  CC_ECN, ae->ack);
13506 			}
13507 		}
13508 #ifdef TCP_ACCOUNTING
13509 		/* Count for the specific type of ack in */
13510 		counter_u64_add(tcp_cnt_counters[ae->ack_val_set], 1);
13511 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13512 			tp->tcp_cnt_counters[ae->ack_val_set]++;
13513 		}
13514 #endif
13515 		/*
13516 		 * Note how we could move up these in the determination
13517 		 * above, but we don't so that way the timestamp checks (and ECN)
13518 		 * is done first before we do any processing on the ACK.
13519 		 * The non-compressed path through the code has this
13520 		 * weakness (noted by @jtl) that it actually does some
13521 		 * processing before verifying the timestamp information.
13522 		 * We don't take that path here which is why we set
13523 		 * the ack_val_set first, do the timestamp and ecn
13524 		 * processing, and then look at what we have setup.
13525 		 */
13526 		if (ae->ack_val_set == ACK_BEHIND) {
13527 			/*
13528 			 * Case B flag reordering, if window is not closed
13529 			 * or it could be a keep-alive or persists
13530 			 */
13531 			if (SEQ_LT(ae->ack, tp->snd_una) && (sbspace(&so->so_rcv) > segsiz)) {
13532 				counter_u64_add(rack_reorder_seen, 1);
13533 				rack->r_ctl.rc_reorder_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
13534 			}
13535 		} else if (ae->ack_val_set == ACK_DUPACK) {
13536 			/* Case D */
13537 			rack_strike_dupack(rack);
13538 		} else if (ae->ack_val_set == ACK_RWND) {
13539 			/* Case C */
13540 			win_up_req = 1;
13541 			win_upd_ack = ae->ack;
13542 			win_seq = ae->seq;
13543 			the_win = tiwin;
13544 			rack_do_win_updates(tp, rack, the_win, win_seq, win_upd_ack, cts, high_seq);
13545 		} else {
13546 			/* Case A */
13547 			if (SEQ_GT(ae->ack, tp->snd_max)) {
13548 				/*
13549 				 * We just send an ack since the incoming
13550 				 * ack is beyond the largest seq we sent.
13551 				 */
13552 				if ((tp->t_flags & TF_ACKNOW) == 0) {
13553 					ctf_ack_war_checks(tp, &rack->r_ctl.challenge_ack_ts, &rack->r_ctl.challenge_ack_cnt);
13554 					if (tp->t_flags && TF_ACKNOW)
13555 						rack->r_wanted_output = 1;
13556 				}
13557 			} else {
13558 				nsegs++;
13559 				/* If the window changed setup to update */
13560 				if (tiwin != tp->snd_wnd) {
13561 					win_upd_ack = ae->ack;
13562 					win_seq = ae->seq;
13563 					the_win = tiwin;
13564 					rack_do_win_updates(tp, rack, the_win, win_seq, win_upd_ack, cts, high_seq);
13565 				}
13566 #ifdef TCP_ACCOUNTING
13567 				/* Account for the acks */
13568 				if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13569 					tp->tcp_cnt_counters[CNT_OF_ACKS_IN] += (((ae->ack - high_seq) + segsiz - 1) / segsiz);
13570 				}
13571 				counter_u64_add(tcp_cnt_counters[CNT_OF_ACKS_IN],
13572 						(((ae->ack - high_seq) + segsiz - 1) / segsiz));
13573 #endif
13574 				high_seq = ae->ack;
13575 				/* Setup our act_rcv_time */
13576 				if ((ae->flags & TSTMP_LRO) || (ae->flags & TSTMP_HDWR)) {
13577 					ts.tv_sec = ae->timestamp / 1000000000;
13578 					ts.tv_nsec = ae->timestamp % 1000000000;
13579 					rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
13580 					rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
13581 				} else {
13582 					rack->r_ctl.act_rcv_time = *tv;
13583 				}
13584 				rack_process_to_cumack(tp, rack, ae->ack, cts, to);
13585 				if (rack->rc_dsack_round_seen) {
13586 					/* Is the dsack round over? */
13587 					if (SEQ_GEQ(ae->ack, rack->r_ctl.dsack_round_end)) {
13588 						/* Yes it is */
13589 						rack->rc_dsack_round_seen = 0;
13590 						rack_log_dsack_event(rack, 3, __LINE__, 0, 0);
13591 					}
13592 				}
13593 			}
13594 		}
13595 		/* And lets be sure to commit the rtt measurements for this ack */
13596 		tcp_rack_xmit_timer_commit(rack, tp);
13597 #ifdef TCP_ACCOUNTING
13598 		rdstc = get_cyclecount();
13599 		if (rdstc > ts_val) {
13600 			counter_u64_add(tcp_proc_time[ae->ack_val_set] , (rdstc - ts_val));
13601 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13602 				tp->tcp_proc_time[ae->ack_val_set] += (rdstc - ts_val);
13603 				if (ae->ack_val_set == ACK_CUMACK)
13604 					tp->tcp_proc_time[CYC_HANDLE_MAP] += (rdstc - ts_val);
13605 			}
13606 		}
13607 #endif
13608 	}
13609 #ifdef TCP_ACCOUNTING
13610 	ts_val = get_cyclecount();
13611 #endif
13612 	acked_amount = acked = (high_seq - tp->snd_una);
13613 	if (acked) {
13614 		if (rack->sack_attack_disable == 0)
13615 			rack_do_decay(rack);
13616 		if (acked >= segsiz) {
13617 			/*
13618 			 * You only get credit for
13619 			 * MSS and greater (and you get extra
13620 			 * credit for larger cum-ack moves).
13621 			 */
13622 			int ac;
13623 
13624 			ac = acked / segsiz;
13625 			rack->r_ctl.ack_count += ac;
13626 			counter_u64_add(rack_ack_total, ac);
13627 		}
13628 		if (rack->r_ctl.ack_count > 0xfff00000) {
13629 			/*
13630 			 * reduce the number to keep us under
13631 			 * a uint32_t.
13632 			 */
13633 			rack->r_ctl.ack_count /= 2;
13634 			rack->r_ctl.sack_count /= 2;
13635 		}
13636 		if (tp->t_flags & TF_NEEDSYN) {
13637 			/*
13638 			 * T/TCP: Connection was half-synchronized, and our SYN has
13639 			 * been ACK'd (so connection is now fully synchronized).  Go
13640 			 * to non-starred state, increment snd_una for ACK of SYN,
13641 			 * and check if we can do window scaling.
13642 			 */
13643 			tp->t_flags &= ~TF_NEEDSYN;
13644 			tp->snd_una++;
13645 			acked_amount = acked = (high_seq - tp->snd_una);
13646 		}
13647 		if (acked > sbavail(&so->so_snd))
13648 			acked_amount = sbavail(&so->so_snd);
13649 #ifdef NETFLIX_EXP_DETECTION
13650 		/*
13651 		 * We only care on a cum-ack move if we are in a sack-disabled
13652 		 * state. We have already added in to the ack_count, and we never
13653 		 * would disable on a cum-ack move, so we only care to do the
13654 		 * detection if it may "undo" it, i.e. we were in disabled already.
13655 		 */
13656 		if (rack->sack_attack_disable)
13657 			rack_do_detection(tp, rack, acked_amount, segsiz);
13658 #endif
13659 		if (IN_FASTRECOVERY(tp->t_flags) &&
13660 		    (rack->rack_no_prr == 0))
13661 			rack_update_prr(tp, rack, acked_amount, high_seq);
13662 		if (IN_RECOVERY(tp->t_flags)) {
13663 			if (SEQ_LT(high_seq, tp->snd_recover) &&
13664 			    (SEQ_LT(high_seq, tp->snd_max))) {
13665 				tcp_rack_partialack(tp);
13666 			} else {
13667 				rack_post_recovery(tp, high_seq);
13668 				recovery = 1;
13669 			}
13670 		}
13671 		/* Handle the rack-log-ack part (sendmap) */
13672 		if ((sbused(&so->so_snd) == 0) &&
13673 		    (acked > acked_amount) &&
13674 		    (tp->t_state >= TCPS_FIN_WAIT_1) &&
13675 		    (tp->t_flags & TF_SENTFIN)) {
13676 			/*
13677 			 * We must be sure our fin
13678 			 * was sent and acked (we can be
13679 			 * in FIN_WAIT_1 without having
13680 			 * sent the fin).
13681 			 */
13682 			ourfinisacked = 1;
13683 			/*
13684 			 * Lets make sure snd_una is updated
13685 			 * since most likely acked_amount = 0 (it
13686 			 * should be).
13687 			 */
13688 			tp->snd_una = high_seq;
13689 		}
13690 		/* Did we make a RTO error? */
13691 		if ((tp->t_flags & TF_PREVVALID) &&
13692 		    ((tp->t_flags & TF_RCVD_TSTMP) == 0)) {
13693 			tp->t_flags &= ~TF_PREVVALID;
13694 			if (tp->t_rxtshift == 1 &&
13695 			    (int)(ticks - tp->t_badrxtwin) < 0)
13696 				rack_cong_signal(tp, CC_RTO_ERR, high_seq);
13697 		}
13698 		/* Handle the data in the socket buffer */
13699 		KMOD_TCPSTAT_ADD(tcps_rcvackpack, 1);
13700 		KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
13701 		if (acked_amount > 0) {
13702 			struct mbuf *mfree;
13703 
13704 			rack_ack_received(tp, rack, high_seq, nsegs, CC_ACK, recovery);
13705 			SOCKBUF_LOCK(&so->so_snd);
13706 			mfree = sbcut_locked(&so->so_snd, acked_amount);
13707 			tp->snd_una = high_seq;
13708 			/* Note we want to hold the sb lock through the sendmap adjust */
13709 			rack_adjust_sendmap(rack, &so->so_snd, tp->snd_una);
13710 			/* Wake up the socket if we have room to write more */
13711 			rack_log_wakeup(tp,rack, &so->so_snd, acked, 2);
13712 			sowwakeup_locked(so);
13713 			m_freem(mfree);
13714 		}
13715 		/* update progress */
13716 		tp->t_acktime = ticks;
13717 		rack_log_progress_event(rack, tp, tp->t_acktime,
13718 					PROGRESS_UPDATE, __LINE__);
13719 		/* Clear out shifts and such */
13720 		tp->t_rxtshift = 0;
13721 		RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
13722 				   rack_rto_min, rack_rto_max, rack->r_ctl.timer_slop);
13723 		rack->rc_tlp_in_progress = 0;
13724 		rack->r_ctl.rc_tlp_cnt_out = 0;
13725 		/* Send recover and snd_nxt must be dragged along */
13726 		if (SEQ_GT(tp->snd_una, tp->snd_recover))
13727 			tp->snd_recover = tp->snd_una;
13728 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
13729 			tp->snd_nxt = tp->snd_una;
13730 		/*
13731 		 * If the RXT timer is running we want to
13732 		 * stop it, so we can restart a TLP (or new RXT).
13733 		 */
13734 		if (rack->r_ctl.rc_hpts_flags & PACE_TMR_RXT)
13735 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13736 #ifdef NETFLIX_HTTP_LOGGING
13737 		tcp_http_check_for_comp(rack->rc_tp, high_seq);
13738 #endif
13739 		tp->snd_wl2 = high_seq;
13740 		tp->t_dupacks = 0;
13741 		if (under_pacing &&
13742 		    (rack->use_fixed_rate == 0) &&
13743 		    (rack->in_probe_rtt == 0) &&
13744 		    rack->rc_gp_dyn_mul &&
13745 		    rack->rc_always_pace) {
13746 			/* Check if we are dragging bottom */
13747 			rack_check_bottom_drag(tp, rack, so, acked);
13748 		}
13749 		if (tp->snd_una == tp->snd_max) {
13750 			tp->t_flags &= ~TF_PREVVALID;
13751 			rack->r_ctl.retran_during_recovery = 0;
13752 			rack->r_ctl.dsack_byte_cnt = 0;
13753 			rack->r_ctl.rc_went_idle_time = tcp_get_usecs(NULL);
13754 			if (rack->r_ctl.rc_went_idle_time == 0)
13755 				rack->r_ctl.rc_went_idle_time = 1;
13756 			rack_log_progress_event(rack, tp, 0, PROGRESS_CLEAR, __LINE__);
13757 			if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
13758 				tp->t_acktime = 0;
13759 			/* Set so we might enter persists... */
13760 			rack->r_wanted_output = 1;
13761 			rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13762 			sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
13763 			if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
13764 			    (sbavail(&so->so_snd) == 0) &&
13765 			    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
13766 				/*
13767 				 * The socket was gone and the
13768 				 * peer sent data (not now in the past), time to
13769 				 * reset him.
13770 				 */
13771 				rack_timer_cancel(tp, rack, rack->r_ctl.rc_rcvtime, __LINE__);
13772 				/* tcp_close will kill the inp pre-log the Reset */
13773 				tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13774 #ifdef TCP_ACCOUNTING
13775 				rdstc = get_cyclecount();
13776 				if (rdstc > ts_val) {
13777 					counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13778 					if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13779 						tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13780 						tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13781 					}
13782 				}
13783 #endif
13784 				m_freem(m);
13785 				tp = tcp_close(tp);
13786 				if (tp == NULL) {
13787 #ifdef TCP_ACCOUNTING
13788 					sched_unpin();
13789 #endif
13790 					return (1);
13791 				}
13792 				/*
13793 				 * We would normally do drop-with-reset which would
13794 				 * send back a reset. We can't since we don't have
13795 				 * all the needed bits. Instead lets arrange for
13796 				 * a call to tcp_output(). That way since we
13797 				 * are in the closed state we will generate a reset.
13798 				 *
13799 				 * Note if tcp_accounting is on we don't unpin since
13800 				 * we do that after the goto label.
13801 				 */
13802 				goto send_out_a_rst;
13803 			}
13804 			if ((sbused(&so->so_snd) == 0) &&
13805 			    (tp->t_state >= TCPS_FIN_WAIT_1) &&
13806 			    (tp->t_flags & TF_SENTFIN)) {
13807 				/*
13808 				 * If we can't receive any more data, then closing user can
13809 				 * proceed. Starting the timer is contrary to the
13810 				 * specification, but if we don't get a FIN we'll hang
13811 				 * forever.
13812 				 *
13813 				 */
13814 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
13815 					soisdisconnected(so);
13816 					tcp_timer_activate(tp, TT_2MSL,
13817 							   (tcp_fast_finwait2_recycle ?
13818 							    tcp_finwait2_timeout :
13819 							    TP_MAXIDLE(tp)));
13820 				}
13821 				if (ourfinisacked == 0) {
13822 					/*
13823 					 * We don't change to fin-wait-2 if we have our fin acked
13824 					 * which means we are probably in TCPS_CLOSING.
13825 					 */
13826 					tcp_state_change(tp, TCPS_FIN_WAIT_2);
13827 				}
13828 			}
13829 		}
13830 		/* Wake up the socket if we have room to write more */
13831 		if (sbavail(&so->so_snd)) {
13832 			rack->r_wanted_output = 1;
13833 			if (ctf_progress_timeout_check(tp, true)) {
13834 				rack_log_progress_event((struct tcp_rack *)tp->t_fb_ptr,
13835 							tp, tick, PROGRESS_DROP, __LINE__);
13836 				tcp_set_inp_to_drop(tp->t_inpcb, ETIMEDOUT);
13837 				/*
13838 				 * We cheat here and don't send a RST, we should send one
13839 				 * when the pacer drops the connection.
13840 				 */
13841 #ifdef TCP_ACCOUNTING
13842 				rdstc = get_cyclecount();
13843 				if (rdstc > ts_val) {
13844 					counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13845 					if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13846 						tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13847 						tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13848 					}
13849 				}
13850 				sched_unpin();
13851 #endif
13852 				INP_WUNLOCK(rack->rc_inp);
13853 				m_freem(m);
13854 				return (1);
13855 			}
13856 		}
13857 		if (ourfinisacked) {
13858 			switch(tp->t_state) {
13859 			case TCPS_CLOSING:
13860 #ifdef TCP_ACCOUNTING
13861 				rdstc = get_cyclecount();
13862 				if (rdstc > ts_val) {
13863 					counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13864 							(rdstc - ts_val));
13865 					if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13866 						tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13867 						tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13868 					}
13869 				}
13870 				sched_unpin();
13871 #endif
13872 				tcp_twstart(tp);
13873 				m_freem(m);
13874 				return (1);
13875 				break;
13876 			case TCPS_LAST_ACK:
13877 #ifdef TCP_ACCOUNTING
13878 				rdstc = get_cyclecount();
13879 				if (rdstc > ts_val) {
13880 					counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13881 							(rdstc - ts_val));
13882 					if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13883 						tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13884 						tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13885 					}
13886 				}
13887 				sched_unpin();
13888 #endif
13889 				tp = tcp_close(tp);
13890 				ctf_do_drop(m, tp);
13891 				return (1);
13892 				break;
13893 			case TCPS_FIN_WAIT_1:
13894 #ifdef TCP_ACCOUNTING
13895 				rdstc = get_cyclecount();
13896 				if (rdstc > ts_val) {
13897 					counter_u64_add(tcp_proc_time[ACK_CUMACK] ,
13898 							(rdstc - ts_val));
13899 					if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13900 						tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13901 						tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13902 					}
13903 				}
13904 #endif
13905 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
13906 					soisdisconnected(so);
13907 					tcp_timer_activate(tp, TT_2MSL,
13908 							   (tcp_fast_finwait2_recycle ?
13909 							    tcp_finwait2_timeout :
13910 							    TP_MAXIDLE(tp)));
13911 				}
13912 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
13913 				break;
13914 			default:
13915 				break;
13916 			}
13917 		}
13918 		if (rack->r_fast_output) {
13919 			/*
13920 			 * We re doing fast output.. can we expand that?
13921 			 */
13922 			rack_gain_for_fastoutput(rack, tp, so, acked_amount);
13923 		}
13924 #ifdef TCP_ACCOUNTING
13925 		rdstc = get_cyclecount();
13926 		if (rdstc > ts_val) {
13927 			counter_u64_add(tcp_proc_time[ACK_CUMACK] , (rdstc - ts_val));
13928 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13929 				tp->tcp_proc_time[ACK_CUMACK] += (rdstc - ts_val);
13930 				tp->tcp_proc_time[CYC_HANDLE_ACK] += (rdstc - ts_val);
13931 			}
13932 		}
13933 
13934 	} else if (win_up_req) {
13935 		rdstc = get_cyclecount();
13936 		if (rdstc > ts_val) {
13937 			counter_u64_add(tcp_proc_time[ACK_RWND] , (rdstc - ts_val));
13938 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
13939 				tp->tcp_proc_time[ACK_RWND] += (rdstc - ts_val);
13940 			}
13941 		}
13942 #endif
13943 	}
13944 	/* Now is there a next packet, if so we are done */
13945 	m_freem(m);
13946 	did_out = 0;
13947 	if (nxt_pkt) {
13948 #ifdef TCP_ACCOUNTING
13949 		sched_unpin();
13950 #endif
13951 		rack_log_doseg_done(rack, cts, nxt_pkt, did_out, 5, nsegs);
13952 		return (0);
13953 	}
13954 	rack_handle_might_revert(tp, rack);
13955 	ctf_calc_rwin(so, tp);
13956 	if ((rack->r_wanted_output != 0) || (rack->r_fast_output != 0)) {
13957 	send_out_a_rst:
13958 		(void)tp->t_fb->tfb_tcp_output(tp);
13959 		did_out = 1;
13960 	}
13961 	rack_free_trim(rack);
13962 #ifdef TCP_ACCOUNTING
13963 	sched_unpin();
13964 #endif
13965 	rack_timer_audit(tp, rack, &so->so_snd);
13966 	rack_log_doseg_done(rack, cts, nxt_pkt, did_out, 6, nsegs);
13967 	return (0);
13968 }
13969 
13970 
13971 static int
13972 rack_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
13973     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
13974     int32_t nxt_pkt, struct timeval *tv)
13975 {
13976 #ifdef TCP_ACCOUNTING
13977 	uint64_t ts_val;
13978 #endif
13979 	int32_t thflags, retval, did_out = 0;
13980 	int32_t way_out = 0;
13981 	/*
13982 	 * cts - is the current time from tv (caller gets ts) in microseconds.
13983 	 * ms_cts - is the current time from tv in milliseconds.
13984 	 * us_cts - is the time that LRO or hardware actually got the packet in microseconds.
13985 	 */
13986 	uint32_t cts, us_cts, ms_cts;
13987 	uint32_t tiwin;
13988 	struct timespec ts;
13989 	struct tcpopt to;
13990 	struct tcp_rack *rack;
13991 	struct rack_sendmap *rsm;
13992 	int32_t prev_state = 0;
13993 #ifdef TCP_ACCOUNTING
13994 	int ack_val_set = 0xf;
13995 #endif
13996 	int nsegs;
13997 	/*
13998 	 * tv passed from common code is from either M_TSTMP_LRO or
13999 	 * tcp_get_usecs() if no LRO m_pkthdr timestamp is present.
14000 	 */
14001 	rack = (struct tcp_rack *)tp->t_fb_ptr;
14002 	if (m->m_flags & M_ACKCMP) {
14003 		return (rack_do_compressed_ack_processing(tp, so, m, nxt_pkt, tv));
14004 	}
14005 	if (m->m_flags & M_ACKCMP) {
14006 		panic("Impossible reach m has ackcmp? m:%p tp:%p", m, tp);
14007 	}
14008 	cts = tcp_tv_to_usectick(tv);
14009 	ms_cts =  tcp_tv_to_mssectick(tv);
14010 	nsegs = m->m_pkthdr.lro_nsegs;
14011 	counter_u64_add(rack_proc_non_comp_ack, 1);
14012 	thflags = th->th_flags;
14013 #ifdef TCP_ACCOUNTING
14014 	sched_pin();
14015 	if (thflags & TH_ACK)
14016 		ts_val = get_cyclecount();
14017 #endif
14018 	if ((m->m_flags & M_TSTMP) ||
14019 	    (m->m_flags & M_TSTMP_LRO)) {
14020 		mbuf_tstmp2timespec(m, &ts);
14021 		rack->r_ctl.act_rcv_time.tv_sec = ts.tv_sec;
14022 		rack->r_ctl.act_rcv_time.tv_usec = ts.tv_nsec/1000;
14023 	} else
14024 		rack->r_ctl.act_rcv_time = *tv;
14025 	kern_prefetch(rack, &prev_state);
14026 	prev_state = 0;
14027 	/*
14028 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
14029 	 * the scale is zero.
14030 	 */
14031 	tiwin = th->th_win << tp->snd_scale;
14032 #ifdef TCP_ACCOUNTING
14033 	if (thflags & TH_ACK) {
14034 		/*
14035 		 * We have a tradeoff here. We can either do what we are
14036 		 * doing i.e. pinning to this CPU and then doing the accounting
14037 		 * <or> we could do a critical enter, setup the rdtsc and cpu
14038 		 * as in below, and then validate we are on the same CPU on
14039 		 * exit. I have choosen to not do the critical enter since
14040 		 * that often will gain you a context switch, and instead lock
14041 		 * us (line above this if) to the same CPU with sched_pin(). This
14042 		 * means we may be context switched out for a higher priority
14043 		 * interupt but we won't be moved to another CPU.
14044 		 *
14045 		 * If this occurs (which it won't very often since we most likely
14046 		 * are running this code in interupt context and only a higher
14047 		 * priority will bump us ... clock?) we will falsely add in
14048 		 * to the time the interupt processing time plus the ack processing
14049 		 * time. This is ok since its a rare event.
14050 		 */
14051 		ack_val_set = tcp_do_ack_accounting(tp, th, &to, tiwin,
14052 						    ctf_fixed_maxseg(tp));
14053 	}
14054 #endif
14055 	/*
14056 	 * Parse options on any incoming segment.
14057 	 */
14058 	memset(&to, 0, sizeof(to));
14059 	tcp_dooptions(&to, (u_char *)(th + 1),
14060 	    (th->th_off << 2) - sizeof(struct tcphdr),
14061 	    (thflags & TH_SYN) ? TO_SYN : 0);
14062 	NET_EPOCH_ASSERT();
14063 	INP_WLOCK_ASSERT(tp->t_inpcb);
14064 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
14065 	    __func__));
14066 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
14067 	    __func__));
14068 	if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
14069 	    (tp->t_flags & TF_GPUTINPROG)) {
14070 		/*
14071 		 * We have a goodput in progress
14072 		 * and we have entered a late state.
14073 		 * Do we have enough data in the sb
14074 		 * to handle the GPUT request?
14075 		 */
14076 		uint32_t bytes;
14077 
14078 		bytes = tp->gput_ack - tp->gput_seq;
14079 		if (SEQ_GT(tp->gput_seq, tp->snd_una))
14080 			bytes += tp->gput_seq - tp->snd_una;
14081 		if (bytes > sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
14082 			/*
14083 			 * There are not enough bytes in the socket
14084 			 * buffer that have been sent to cover this
14085 			 * measurement. Cancel it.
14086 			 */
14087 			rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
14088 						   rack->r_ctl.rc_gp_srtt /*flex1*/,
14089 						   tp->gput_seq,
14090 						   0, 0, 18, __LINE__, NULL, 0);
14091 			tp->t_flags &= ~TF_GPUTINPROG;
14092 		}
14093 	}
14094 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
14095 		union tcp_log_stackspecific log;
14096 		struct timeval ltv;
14097 #ifdef NETFLIX_HTTP_LOGGING
14098 		struct http_sendfile_track *http_req;
14099 
14100 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
14101 			http_req = tcp_http_find_req_for_seq(tp, (th->th_ack-1));
14102 		} else {
14103 			http_req = tcp_http_find_req_for_seq(tp, th->th_ack);
14104 		}
14105 #endif
14106 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
14107 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
14108 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
14109 		if (rack->rack_no_prr == 0)
14110 			log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
14111 		else
14112 			log.u_bbr.flex1 = 0;
14113 		log.u_bbr.use_lt_bw = rack->r_ent_rec_ns;
14114 		log.u_bbr.use_lt_bw <<= 1;
14115 		log.u_bbr.use_lt_bw |= rack->r_might_revert;
14116 		log.u_bbr.flex2 = rack->r_ctl.rc_num_maps_alloced;
14117 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14118 		log.u_bbr.pkts_out = rack->rc_tp->t_maxseg;
14119 		log.u_bbr.flex3 = m->m_flags;
14120 		log.u_bbr.flex4 = rack->r_ctl.rc_hpts_flags;
14121 		log.u_bbr.lost = thflags;
14122 		log.u_bbr.pacing_gain = 0x1;
14123 #ifdef TCP_ACCOUNTING
14124 		log.u_bbr.cwnd_gain = ack_val_set;
14125 #endif
14126 		log.u_bbr.flex7 = 2;
14127 		if (m->m_flags & M_TSTMP) {
14128 			/* Record the hardware timestamp if present */
14129 			mbuf_tstmp2timespec(m, &ts);
14130 			ltv.tv_sec = ts.tv_sec;
14131 			ltv.tv_usec = ts.tv_nsec / 1000;
14132 			log.u_bbr.lt_epoch = tcp_tv_to_usectick(&ltv);
14133 		} else if (m->m_flags & M_TSTMP_LRO) {
14134 			/* Record the LRO the arrival timestamp */
14135 			mbuf_tstmp2timespec(m, &ts);
14136 			ltv.tv_sec = ts.tv_sec;
14137 			ltv.tv_usec = ts.tv_nsec / 1000;
14138 			log.u_bbr.flex5 = tcp_tv_to_usectick(&ltv);
14139 		}
14140 		log.u_bbr.timeStamp = tcp_get_usecs(&ltv);
14141 		/* Log the rcv time */
14142 		log.u_bbr.delRate = m->m_pkthdr.rcv_tstmp;
14143 #ifdef NETFLIX_HTTP_LOGGING
14144 		log.u_bbr.applimited = tp->t_http_closed;
14145 		log.u_bbr.applimited <<= 8;
14146 		log.u_bbr.applimited |= tp->t_http_open;
14147 		log.u_bbr.applimited <<= 8;
14148 		log.u_bbr.applimited |= tp->t_http_req;
14149 		if (http_req) {
14150 			/* Copy out any client req info */
14151 			/* seconds */
14152 			log.u_bbr.pkt_epoch = (http_req->localtime / HPTS_USEC_IN_SEC);
14153 			/* useconds */
14154 			log.u_bbr.delivered = (http_req->localtime % HPTS_USEC_IN_SEC);
14155 			log.u_bbr.rttProp = http_req->timestamp;
14156 			log.u_bbr.cur_del_rate = http_req->start;
14157 			if (http_req->flags & TCP_HTTP_TRACK_FLG_OPEN) {
14158 				log.u_bbr.flex8 |= 1;
14159 			} else {
14160 				log.u_bbr.flex8 |= 2;
14161 				log.u_bbr.bw_inuse = http_req->end;
14162 			}
14163 			log.u_bbr.flex6 = http_req->start_seq;
14164 			if (http_req->flags & TCP_HTTP_TRACK_FLG_COMP) {
14165 				log.u_bbr.flex8 |= 4;
14166 				log.u_bbr.epoch = http_req->end_seq;
14167 			}
14168 		}
14169 #endif
14170 		TCP_LOG_EVENTP(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_IN, 0,
14171 		    tlen, &log, true, &ltv);
14172 	}
14173 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
14174 		way_out = 4;
14175 		retval = 0;
14176 		m_freem(m);
14177 		goto done_with_input;
14178 	}
14179 	/*
14180 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
14181 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
14182 	 */
14183 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
14184 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
14185 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
14186 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
14187 #ifdef TCP_ACCOUNTING
14188 		sched_unpin();
14189 #endif
14190 		return (1);
14191 	}
14192 	/*
14193 	 * If timestamps were negotiated during SYN/ACK and a
14194 	 * segment without a timestamp is received, silently drop
14195 	 * the segment, unless it is a RST segment or missing timestamps are
14196 	 * tolerated.
14197 	 * See section 3.2 of RFC 7323.
14198 	 */
14199 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
14200 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
14201 		way_out = 5;
14202 		retval = 0;
14203 		m_freem(m);
14204 		goto done_with_input;
14205 	}
14206 
14207 	/*
14208 	 * Segment received on connection. Reset idle time and keep-alive
14209 	 * timer. XXX: This should be done after segment validation to
14210 	 * ignore broken/spoofed segs.
14211 	 */
14212 	if  (tp->t_idle_reduce &&
14213 	     (tp->snd_max == tp->snd_una) &&
14214 	     ((ticks - tp->t_rcvtime) >= tp->t_rxtcur)) {
14215 		counter_u64_add(rack_input_idle_reduces, 1);
14216 		rack_cc_after_idle(rack, tp);
14217 	}
14218 	tp->t_rcvtime = ticks;
14219 #ifdef STATS
14220 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
14221 #endif
14222 	if (tiwin > rack->r_ctl.rc_high_rwnd)
14223 		rack->r_ctl.rc_high_rwnd = tiwin;
14224 	/*
14225 	 * TCP ECN processing. XXXJTL: If we ever use ECN, we need to move
14226 	 * this to occur after we've validated the segment.
14227 	 */
14228 	if (tp->t_flags2 & TF2_ECN_PERMIT) {
14229 		if (thflags & TH_CWR) {
14230 			tp->t_flags2 &= ~TF2_ECN_SND_ECE;
14231 			tp->t_flags |= TF_ACKNOW;
14232 		}
14233 		switch (iptos & IPTOS_ECN_MASK) {
14234 		case IPTOS_ECN_CE:
14235 			tp->t_flags2 |= TF2_ECN_SND_ECE;
14236 			KMOD_TCPSTAT_INC(tcps_ecn_ce);
14237 			break;
14238 		case IPTOS_ECN_ECT0:
14239 			KMOD_TCPSTAT_INC(tcps_ecn_ect0);
14240 			break;
14241 		case IPTOS_ECN_ECT1:
14242 			KMOD_TCPSTAT_INC(tcps_ecn_ect1);
14243 			break;
14244 		}
14245 
14246 		/* Process a packet differently from RFC3168. */
14247 		cc_ecnpkt_handler(tp, th, iptos);
14248 
14249 		/* Congestion experienced. */
14250 		if (thflags & TH_ECE) {
14251 			rack_cong_signal(tp, CC_ECN, th->th_ack);
14252 		}
14253 	}
14254 
14255 	/*
14256 	 * If echoed timestamp is later than the current time, fall back to
14257 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
14258 	 * were used when this connection was established.
14259 	 */
14260 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
14261 		to.to_tsecr -= tp->ts_offset;
14262 		if (TSTMP_GT(to.to_tsecr, ms_cts))
14263 			to.to_tsecr = 0;
14264 	}
14265 
14266 	/*
14267 	 * If its the first time in we need to take care of options and
14268 	 * verify we can do SACK for rack!
14269 	 */
14270 	if (rack->r_state == 0) {
14271 		/* Should be init'd by rack_init() */
14272 		KASSERT(rack->rc_inp != NULL,
14273 		    ("%s: rack->rc_inp unexpectedly NULL", __func__));
14274 		if (rack->rc_inp == NULL) {
14275 			rack->rc_inp = tp->t_inpcb;
14276 		}
14277 
14278 		/*
14279 		 * Process options only when we get SYN/ACK back. The SYN
14280 		 * case for incoming connections is handled in tcp_syncache.
14281 		 * According to RFC1323 the window field in a SYN (i.e., a
14282 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
14283 		 * this is traditional behavior, may need to be cleaned up.
14284 		 */
14285 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
14286 			/* Handle parallel SYN for ECN */
14287 			if (!(thflags & TH_ACK) &&
14288 			    ((thflags & (TH_CWR | TH_ECE)) == (TH_CWR | TH_ECE)) &&
14289 			    ((V_tcp_do_ecn == 1) || (V_tcp_do_ecn == 2))) {
14290 				tp->t_flags2 |= TF2_ECN_PERMIT;
14291 				tp->t_flags2 |= TF2_ECN_SND_ECE;
14292 				TCPSTAT_INC(tcps_ecn_shs);
14293 			}
14294 			if ((to.to_flags & TOF_SCALE) &&
14295 			    (tp->t_flags & TF_REQ_SCALE)) {
14296 				tp->t_flags |= TF_RCVD_SCALE;
14297 				tp->snd_scale = to.to_wscale;
14298 			} else
14299 				tp->t_flags &= ~TF_REQ_SCALE;
14300 			/*
14301 			 * Initial send window.  It will be updated with the
14302 			 * next incoming segment to the scaled value.
14303 			 */
14304 			tp->snd_wnd = th->th_win;
14305 			rack_validate_fo_sendwin_up(tp, rack);
14306 			if ((to.to_flags & TOF_TS) &&
14307 			    (tp->t_flags & TF_REQ_TSTMP)) {
14308 				tp->t_flags |= TF_RCVD_TSTMP;
14309 				tp->ts_recent = to.to_tsval;
14310 				tp->ts_recent_age = cts;
14311 			} else
14312 				tp->t_flags &= ~TF_REQ_TSTMP;
14313 			if (to.to_flags & TOF_MSS) {
14314 				tcp_mss(tp, to.to_mss);
14315 			}
14316 			if ((tp->t_flags & TF_SACK_PERMIT) &&
14317 			    (to.to_flags & TOF_SACKPERM) == 0)
14318 				tp->t_flags &= ~TF_SACK_PERMIT;
14319 			if (IS_FASTOPEN(tp->t_flags)) {
14320 				if (to.to_flags & TOF_FASTOPEN) {
14321 					uint16_t mss;
14322 
14323 					if (to.to_flags & TOF_MSS)
14324 						mss = to.to_mss;
14325 					else
14326 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
14327 							mss = TCP6_MSS;
14328 						else
14329 							mss = TCP_MSS;
14330 					tcp_fastopen_update_cache(tp, mss,
14331 					    to.to_tfo_len, to.to_tfo_cookie);
14332 				} else
14333 					tcp_fastopen_disable_path(tp);
14334 			}
14335 		}
14336 		/*
14337 		 * At this point we are at the initial call. Here we decide
14338 		 * if we are doing RACK or not. We do this by seeing if
14339 		 * TF_SACK_PERMIT is set and the sack-not-required is clear.
14340 		 * The code now does do dup-ack counting so if you don't
14341 		 * switch back you won't get rack & TLP, but you will still
14342 		 * get this stack.
14343 		 */
14344 
14345 		if ((rack_sack_not_required == 0) &&
14346 		    ((tp->t_flags & TF_SACK_PERMIT) == 0)) {
14347 			tcp_switch_back_to_default(tp);
14348 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
14349 			    tlen, iptos);
14350 #ifdef TCP_ACCOUNTING
14351 			sched_unpin();
14352 #endif
14353 			return (1);
14354 		}
14355 		tcp_set_hpts(tp->t_inpcb);
14356 		sack_filter_clear(&rack->r_ctl.rack_sf, th->th_ack);
14357 	}
14358 	if (thflags & TH_FIN)
14359 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
14360 	us_cts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
14361 	if ((rack->rc_gp_dyn_mul) &&
14362 	    (rack->use_fixed_rate == 0) &&
14363 	    (rack->rc_always_pace)) {
14364 		/* Check in on probertt */
14365 		rack_check_probe_rtt(rack, us_cts);
14366 	}
14367 	rack_clear_rate_sample(rack);
14368 	if (rack->forced_ack) {
14369 		uint32_t us_rtt;
14370 
14371 		/*
14372 		 * A persist or keep-alive was forced out, update our
14373 		 * min rtt time. Note we do not worry about lost
14374 		 * retransmissions since KEEP-ALIVES and persists
14375 		 * are usually way long on times of sending (though
14376 		 * if we were really paranoid or worried we could
14377 		 * at least use timestamps if available to validate).
14378 		 */
14379 		rack->forced_ack = 0;
14380 		us_rtt = us_cts - rack->r_ctl.forced_ack_ts;
14381 		if (us_rtt == 0)
14382 			us_rtt = 1;
14383 		rack_apply_updated_usrtt(rack, us_rtt, us_cts);
14384 		tcp_rack_xmit_timer(rack, us_rtt, 0, us_rtt, 3, NULL, 1);
14385 	}
14386 	/*
14387 	 * This is the one exception case where we set the rack state
14388 	 * always. All other times (timers etc) we must have a rack-state
14389 	 * set (so we assure we have done the checks above for SACK).
14390 	 */
14391 	rack->r_ctl.rc_rcvtime = cts;
14392 	if (rack->r_state != tp->t_state)
14393 		rack_set_state(tp, rack);
14394 	if (SEQ_GT(th->th_ack, tp->snd_una) &&
14395 	    (rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree)) != NULL)
14396 		kern_prefetch(rsm, &prev_state);
14397 	prev_state = rack->r_state;
14398 	retval = (*rack->r_substate) (m, th, so,
14399 	    tp, &to, drop_hdrlen,
14400 	    tlen, tiwin, thflags, nxt_pkt, iptos);
14401 #ifdef INVARIANTS
14402 	if ((retval == 0) &&
14403 	    (tp->t_inpcb == NULL)) {
14404 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
14405 		    retval, tp, prev_state);
14406 	}
14407 #endif
14408 	if (retval == 0) {
14409 		/*
14410 		 * If retval is 1 the tcb is unlocked and most likely the tp
14411 		 * is gone.
14412 		 */
14413 		INP_WLOCK_ASSERT(tp->t_inpcb);
14414 		if ((rack->rc_gp_dyn_mul) &&
14415 		    (rack->rc_always_pace) &&
14416 		    (rack->use_fixed_rate == 0) &&
14417 		    rack->in_probe_rtt &&
14418 		    (rack->r_ctl.rc_time_probertt_starts == 0)) {
14419 			/*
14420 			 * If we are going for target, lets recheck before
14421 			 * we output.
14422 			 */
14423 			rack_check_probe_rtt(rack, us_cts);
14424 		}
14425 		if (rack->set_pacing_done_a_iw == 0) {
14426 			/* How much has been acked? */
14427 			if ((tp->snd_una - tp->iss) > (ctf_fixed_maxseg(tp) * 10)) {
14428 				/* We have enough to set in the pacing segment size */
14429 				rack->set_pacing_done_a_iw = 1;
14430 				rack_set_pace_segments(tp, rack, __LINE__, NULL);
14431 			}
14432 		}
14433 		tcp_rack_xmit_timer_commit(rack, tp);
14434 #ifdef TCP_ACCOUNTING
14435 		/*
14436 		 * If we set the ack_val_se to what ack processing we are doing
14437 		 * we also want to track how many cycles we burned. Note
14438 		 * the bits after tcp_output we let be "free". This is because
14439 		 * we are also tracking the tcp_output times as well. Note the
14440 		 * use of 0xf here since we only have 11 counter (0 - 0xa) and
14441 		 * 0xf cannot be returned and is what we initialize it too to
14442 		 * indicate we are not doing the tabulations.
14443 		 */
14444 		if (ack_val_set != 0xf) {
14445 			uint64_t crtsc;
14446 
14447 			crtsc = get_cyclecount();
14448 			counter_u64_add(tcp_proc_time[ack_val_set] , (crtsc - ts_val));
14449 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
14450 				tp->tcp_proc_time[ack_val_set] += (crtsc - ts_val);
14451 			}
14452 		}
14453 #endif
14454 		if (nxt_pkt == 0) {
14455 			if ((rack->r_wanted_output != 0) || (rack->r_fast_output != 0)) {
14456 do_output_now:
14457 				did_out = 1;
14458 				(void)tp->t_fb->tfb_tcp_output(tp);
14459 			}
14460 			rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
14461 			rack_free_trim(rack);
14462 		}
14463 		if ((nxt_pkt == 0) &&
14464 		    ((rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
14465 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
14466 		     (tp->t_flags & TF_DELACK) ||
14467 		     ((V_tcp_always_keepalive || rack->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
14468 		      (tp->t_state <= TCPS_CLOSING)))) {
14469 			/* We could not send (probably in the hpts but stopped the timer earlier)? */
14470 			if ((tp->snd_max == tp->snd_una) &&
14471 			    ((tp->t_flags & TF_DELACK) == 0) &&
14472 			    (rack->rc_inp->inp_in_hpts) &&
14473 			    (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
14474 				/* keep alive not needed if we are hptsi output yet */
14475 				;
14476 			} else {
14477 				int late = 0;
14478 				if (rack->rc_inp->inp_in_hpts) {
14479 					if (rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14480 						us_cts = tcp_get_usecs(NULL);
14481 						if (TSTMP_GT(rack->r_ctl.rc_last_output_to, us_cts)) {
14482 							rack->r_early = 1;
14483 							rack->r_ctl.rc_agg_early += (rack->r_ctl.rc_last_output_to - us_cts);
14484 						} else
14485 							late = 1;
14486 						rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
14487 					}
14488 					tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_OUTPUT);
14489 				}
14490 				if (late && (did_out == 0)) {
14491 					/*
14492 					 * We are late in the sending
14493 					 * and we did not call the output
14494 					 * (this probably should not happen).
14495 					 */
14496 					goto do_output_now;
14497 				}
14498 				rack_start_hpts_timer(rack, tp, tcp_get_usecs(NULL), 0, 0, 0);
14499 			}
14500 			way_out = 1;
14501 		} else if (nxt_pkt == 0) {
14502 			/* Do we have the correct timer running? */
14503 			rack_timer_audit(tp, rack, &so->so_snd);
14504 			way_out = 2;
14505 		}
14506 	done_with_input:
14507 		rack_log_doseg_done(rack, cts, nxt_pkt, did_out, way_out, max(1, nsegs));
14508 		if (did_out)
14509 			rack->r_wanted_output = 0;
14510 #ifdef INVARIANTS
14511 		if (tp->t_inpcb == NULL) {
14512 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
14513 			      did_out,
14514 			      retval, tp, prev_state);
14515 		}
14516 #endif
14517 #ifdef TCP_ACCOUNTING
14518 	} else {
14519 		/*
14520 		 * Track the time (see above).
14521 		 */
14522 		if (ack_val_set != 0xf) {
14523 			uint64_t crtsc;
14524 
14525 			crtsc = get_cyclecount();
14526 			counter_u64_add(tcp_proc_time[ack_val_set] , (crtsc - ts_val));
14527 			/*
14528 			 * Note we *DO NOT* increment the per-tcb counters since
14529 			 * in the else the TP may be gone!!
14530 			 */
14531 		}
14532 #endif
14533 	}
14534 #ifdef TCP_ACCOUNTING
14535 	sched_unpin();
14536 #endif
14537 	return (retval);
14538 }
14539 
14540 void
14541 rack_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
14542     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
14543 {
14544 	struct timeval tv;
14545 
14546 	/* First lets see if we have old packets */
14547 	if (tp->t_in_pkt) {
14548 		if (ctf_do_queued_segments(so, tp, 1)) {
14549 			m_freem(m);
14550 			return;
14551 		}
14552 	}
14553 	if (m->m_flags & M_TSTMP_LRO) {
14554 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
14555 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
14556 	} else {
14557 		/* Should not be should we kassert instead? */
14558 		tcp_get_usecs(&tv);
14559 	}
14560 	if (rack_do_segment_nounlock(m, th, so, tp,
14561 				     drop_hdrlen, tlen, iptos, 0, &tv) == 0) {
14562 		INP_WUNLOCK(tp->t_inpcb);
14563 	}
14564 }
14565 
14566 struct rack_sendmap *
14567 tcp_rack_output(struct tcpcb *tp, struct tcp_rack *rack, uint32_t tsused)
14568 {
14569 	struct rack_sendmap *rsm = NULL;
14570 	int32_t idx;
14571 	uint32_t srtt = 0, thresh = 0, ts_low = 0;
14572 
14573 	/* Return the next guy to be re-transmitted */
14574 	if (RB_EMPTY(&rack->r_ctl.rc_mtree)) {
14575 		return (NULL);
14576 	}
14577 	if (tp->t_flags & TF_SENTFIN) {
14578 		/* retran the end FIN? */
14579 		return (NULL);
14580 	}
14581 	/* ok lets look at this one */
14582 	rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
14583 	if (rsm && ((rsm->r_flags & RACK_ACKED) == 0)) {
14584 		goto check_it;
14585 	}
14586 	rsm = rack_find_lowest_rsm(rack);
14587 	if (rsm == NULL) {
14588 		return (NULL);
14589 	}
14590 check_it:
14591 	if (((rack->rc_tp->t_flags & TF_SACK_PERMIT) == 0) &&
14592 	    (rsm->r_dupack >= DUP_ACK_THRESHOLD)) {
14593 		/*
14594 		 * No sack so we automatically do the 3 strikes and
14595 		 * retransmit (no rack timer would be started).
14596 		 */
14597 
14598 		return (rsm);
14599 	}
14600 	if (rsm->r_flags & RACK_ACKED) {
14601 		return (NULL);
14602 	}
14603 	if (((rsm->r_flags & RACK_SACK_PASSED) == 0) &&
14604 	    (rsm->r_dupack < DUP_ACK_THRESHOLD)) {
14605 		/* Its not yet ready */
14606 		return (NULL);
14607 	}
14608 	srtt = rack_grab_rtt(tp, rack);
14609 	idx = rsm->r_rtr_cnt - 1;
14610 	ts_low = (uint32_t)rsm->r_tim_lastsent[idx];
14611 	thresh = rack_calc_thresh_rack(rack, srtt, tsused);
14612 	if ((tsused == ts_low) ||
14613 	    (TSTMP_LT(tsused, ts_low))) {
14614 		/* No time since sending */
14615 		return (NULL);
14616 	}
14617 	if ((tsused - ts_low) < thresh) {
14618 		/* It has not been long enough yet */
14619 		return (NULL);
14620 	}
14621 	if ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
14622 	    ((rsm->r_flags & RACK_SACK_PASSED) &&
14623 	     (rack->sack_attack_disable == 0))) {
14624 		/*
14625 		 * We have passed the dup-ack threshold <or>
14626 		 * a SACK has indicated this is missing.
14627 		 * Note that if you are a declared attacker
14628 		 * it is only the dup-ack threshold that
14629 		 * will cause retransmits.
14630 		 */
14631 		/* log retransmit reason */
14632 		rack_log_retran_reason(rack, rsm, (tsused - ts_low), thresh, 1);
14633 		rack->r_fast_output = 0;
14634 		return (rsm);
14635 	}
14636 	return (NULL);
14637 }
14638 
14639 static void
14640 rack_log_pacing_delay_calc(struct tcp_rack *rack, uint32_t len, uint32_t slot,
14641 			   uint64_t bw_est, uint64_t bw, uint64_t len_time, int method,
14642 			   int line, struct rack_sendmap *rsm, uint8_t quality)
14643 {
14644 	if (rack->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
14645 		union tcp_log_stackspecific log;
14646 		struct timeval tv;
14647 
14648 		memset(&log, 0, sizeof(log));
14649 		log.u_bbr.flex1 = slot;
14650 		log.u_bbr.flex2 = len;
14651 		log.u_bbr.flex3 = rack->r_ctl.rc_pace_min_segs;
14652 		log.u_bbr.flex4 = rack->r_ctl.rc_pace_max_segs;
14653 		log.u_bbr.flex5 = rack->r_ctl.rack_per_of_gp_ss;
14654 		log.u_bbr.flex6 = rack->r_ctl.rack_per_of_gp_ca;
14655 		log.u_bbr.use_lt_bw = rack->rc_ack_can_sendout_data;
14656 		log.u_bbr.use_lt_bw <<= 1;
14657 		log.u_bbr.use_lt_bw |= rack->r_late;
14658 		log.u_bbr.use_lt_bw <<= 1;
14659 		log.u_bbr.use_lt_bw |= rack->r_early;
14660 		log.u_bbr.use_lt_bw <<= 1;
14661 		log.u_bbr.use_lt_bw |= rack->app_limited_needs_set;
14662 		log.u_bbr.use_lt_bw <<= 1;
14663 		log.u_bbr.use_lt_bw |= rack->rc_gp_filled;
14664 		log.u_bbr.use_lt_bw <<= 1;
14665 		log.u_bbr.use_lt_bw |= rack->measure_saw_probe_rtt;
14666 		log.u_bbr.use_lt_bw <<= 1;
14667 		log.u_bbr.use_lt_bw |= rack->in_probe_rtt;
14668 		log.u_bbr.use_lt_bw <<= 1;
14669 		log.u_bbr.use_lt_bw |= rack->gp_ready;
14670 		log.u_bbr.pkt_epoch = line;
14671 		log.u_bbr.epoch = rack->r_ctl.rc_agg_delayed;
14672 		log.u_bbr.lt_epoch = rack->r_ctl.rc_agg_early;
14673 		log.u_bbr.applimited = rack->r_ctl.rack_per_of_gp_rec;
14674 		log.u_bbr.bw_inuse = bw_est;
14675 		log.u_bbr.delRate = bw;
14676 		if (rack->r_ctl.gp_bw == 0)
14677 			log.u_bbr.cur_del_rate = 0;
14678 		else
14679 			log.u_bbr.cur_del_rate = rack_get_bw(rack);
14680 		log.u_bbr.rttProp = len_time;
14681 		log.u_bbr.pkts_out = rack->r_ctl.rc_rack_min_rtt;
14682 		log.u_bbr.lost = rack->r_ctl.rc_probertt_sndmax_atexit;
14683 		log.u_bbr.pacing_gain = rack_get_output_gain(rack, rsm);
14684 		if (rack->r_ctl.cwnd_to_use < rack->rc_tp->snd_ssthresh) {
14685 			/* We are in slow start */
14686 			log.u_bbr.flex7 = 1;
14687 		} else {
14688 			/* we are on congestion avoidance */
14689 			log.u_bbr.flex7 = 0;
14690 		}
14691 		log.u_bbr.flex8 = method;
14692 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
14693 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14694 		log.u_bbr.cwnd_gain = rack->rc_gp_saw_rec;
14695 		log.u_bbr.cwnd_gain <<= 1;
14696 		log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ss;
14697 		log.u_bbr.cwnd_gain <<= 1;
14698 		log.u_bbr.cwnd_gain |= rack->rc_gp_saw_ca;
14699 		log.u_bbr.bbr_substate = quality;
14700 		TCP_LOG_EVENTP(rack->rc_tp, NULL,
14701 		    &rack->rc_inp->inp_socket->so_rcv,
14702 		    &rack->rc_inp->inp_socket->so_snd,
14703 		    BBR_LOG_HPTSI_CALC, 0,
14704 		    0, &log, false, &tv);
14705 	}
14706 }
14707 
14708 static uint32_t
14709 rack_get_pacing_len(struct tcp_rack *rack, uint64_t bw, uint32_t mss)
14710 {
14711 	uint32_t new_tso, user_max;
14712 
14713 	user_max = rack->rc_user_set_max_segs * mss;
14714 	if (rack->rc_force_max_seg) {
14715 		return (user_max);
14716 	}
14717 	if (rack->use_fixed_rate &&
14718 	    ((rack->r_ctl.crte == NULL) ||
14719 	     (bw != rack->r_ctl.crte->rate))) {
14720 		/* Use the user mss since we are not exactly matched */
14721 		return (user_max);
14722 	}
14723 	new_tso = tcp_get_pacing_burst_size(rack->rc_tp, bw, mss, rack_pace_one_seg, rack->r_ctl.crte, NULL);
14724 	if (new_tso > user_max)
14725 		new_tso = user_max;
14726 	return (new_tso);
14727 }
14728 
14729 static int32_t
14730 pace_to_fill_cwnd(struct tcp_rack *rack, int32_t slot, uint32_t len, uint32_t segsiz, int *capped, uint64_t *rate_wanted, uint8_t non_paced)
14731 {
14732 	uint64_t lentim, fill_bw;
14733 
14734 	/* Lets first see if we are full, if so continue with normal rate */
14735 	rack->r_via_fill_cw = 0;
14736 	if (ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked) > rack->r_ctl.cwnd_to_use)
14737 		return (slot);
14738 	if ((ctf_outstanding(rack->rc_tp) + (segsiz-1)) > rack->rc_tp->snd_wnd)
14739 		return (slot);
14740 	if (rack->r_ctl.rc_last_us_rtt == 0)
14741 		return (slot);
14742 	if (rack->rc_pace_fill_if_rttin_range &&
14743 	    (rack->r_ctl.rc_last_us_rtt >=
14744 	     (get_filter_value_small(&rack->r_ctl.rc_gp_min_rtt) * rack->rtt_limit_mul))) {
14745 		/* The rtt is huge, N * smallest, lets not fill */
14746 		return (slot);
14747 	}
14748 	/*
14749 	 * first lets calculate the b/w based on the last us-rtt
14750 	 * and the sndwnd.
14751 	 */
14752 	fill_bw = rack->r_ctl.cwnd_to_use;
14753 	/* Take the rwnd if its smaller */
14754 	if (fill_bw > rack->rc_tp->snd_wnd)
14755 		fill_bw = rack->rc_tp->snd_wnd;
14756 	if (rack->r_fill_less_agg) {
14757 		/*
14758 		 * Now take away the inflight (this will reduce our
14759 		 * aggressiveness and yeah, if we get that much out in 1RTT
14760 		 * we will have had acks come back and still be behind).
14761 		 */
14762 		fill_bw -= ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
14763 	}
14764 	/* Now lets make it into a b/w */
14765 	fill_bw *= (uint64_t)HPTS_USEC_IN_SEC;
14766 	fill_bw /= (uint64_t)rack->r_ctl.rc_last_us_rtt;
14767 	/* We are below the min b/w */
14768 	if (non_paced)
14769 		*rate_wanted = fill_bw;
14770 	if ((fill_bw < RACK_MIN_BW) || (fill_bw < *rate_wanted))
14771 		return (slot);
14772 	if (rack->r_ctl.bw_rate_cap && (fill_bw > rack->r_ctl.bw_rate_cap))
14773 		fill_bw = rack->r_ctl.bw_rate_cap;
14774 	rack->r_via_fill_cw = 1;
14775 	if (rack->r_rack_hw_rate_caps &&
14776 	    (rack->r_ctl.crte != NULL)) {
14777 		uint64_t high_rate;
14778 
14779 		high_rate = tcp_hw_highest_rate(rack->r_ctl.crte);
14780 		if (fill_bw > high_rate) {
14781 			/* We are capping bw at the highest rate table entry */
14782 			if (*rate_wanted > high_rate) {
14783 				/* The original rate was also capped */
14784 				rack->r_via_fill_cw = 0;
14785 			}
14786 			rack_log_hdwr_pacing(rack,
14787 					     fill_bw, high_rate, __LINE__,
14788 					     0, 3);
14789 			fill_bw = high_rate;
14790 			if (capped)
14791 				*capped = 1;
14792 		}
14793 	} else if ((rack->r_ctl.crte == NULL) &&
14794 		   (rack->rack_hdrw_pacing == 0) &&
14795 		   (rack->rack_hdw_pace_ena) &&
14796 		   rack->r_rack_hw_rate_caps &&
14797 		   (rack->rack_attempt_hdwr_pace == 0) &&
14798 		   (rack->rc_inp->inp_route.ro_nh != NULL) &&
14799 		   (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
14800 		/*
14801 		 * Ok we may have a first attempt that is greater than our top rate
14802 		 * lets check.
14803 		 */
14804 		uint64_t high_rate;
14805 
14806 		high_rate = tcp_hw_highest_rate_ifp(rack->rc_inp->inp_route.ro_nh->nh_ifp, rack->rc_inp);
14807 		if (high_rate) {
14808 			if (fill_bw > high_rate) {
14809 				fill_bw = high_rate;
14810 				if (capped)
14811 					*capped = 1;
14812 			}
14813 		}
14814 	}
14815 	/*
14816 	 * Ok fill_bw holds our mythical b/w to fill the cwnd
14817 	 * in a rtt, what does that time wise equate too?
14818 	 */
14819 	lentim = (uint64_t)(len) * (uint64_t)HPTS_USEC_IN_SEC;
14820 	lentim /= fill_bw;
14821 	*rate_wanted = fill_bw;
14822 	if (non_paced || (lentim < slot)) {
14823 		rack_log_pacing_delay_calc(rack, len, slot, fill_bw,
14824 					   0, lentim, 12, __LINE__, NULL, 0);
14825 		return ((int32_t)lentim);
14826 	} else
14827 		return (slot);
14828 }
14829 
14830 static int32_t
14831 rack_get_pacing_delay(struct tcp_rack *rack, struct tcpcb *tp, uint32_t len, struct rack_sendmap *rsm, uint32_t segsiz)
14832 {
14833 	int32_t slot = 0;
14834 	int can_start_hw_pacing = 1;
14835 	int err;
14836 
14837 	if (rack->rc_always_pace == 0) {
14838 		/*
14839 		 * We use the most optimistic possible cwnd/srtt for
14840 		 * sending calculations. This will make our
14841 		 * calculation anticipate getting more through
14842 		 * quicker then possible. But thats ok we don't want
14843 		 * the peer to have a gap in data sending.
14844 		 */
14845 		uint32_t srtt, cwnd, tr_perms = 0;
14846 		int32_t reduce = 0;
14847 
14848 	old_method:
14849 		/*
14850 		 * We keep no precise pacing with the old method
14851 		 * instead we use the pacer to mitigate bursts.
14852 		 */
14853 		if (rack->r_ctl.rc_rack_min_rtt)
14854 			srtt = rack->r_ctl.rc_rack_min_rtt;
14855 		else
14856 			srtt = max(tp->t_srtt, 1);
14857 		if (rack->r_ctl.rc_rack_largest_cwnd)
14858 			cwnd = rack->r_ctl.rc_rack_largest_cwnd;
14859 		else
14860 			cwnd = rack->r_ctl.cwnd_to_use;
14861 		/* Inflate cwnd by 1000 so srtt of usecs is in ms */
14862 		tr_perms = (cwnd * 1000) / srtt;
14863 		if (tr_perms == 0) {
14864 			tr_perms = ctf_fixed_maxseg(tp);
14865 		}
14866 		/*
14867 		 * Calculate how long this will take to drain, if
14868 		 * the calculation comes out to zero, thats ok we
14869 		 * will use send_a_lot to possibly spin around for
14870 		 * more increasing tot_len_this_send to the point
14871 		 * that its going to require a pace, or we hit the
14872 		 * cwnd. Which in that case we are just waiting for
14873 		 * a ACK.
14874 		 */
14875 		slot = len / tr_perms;
14876 		/* Now do we reduce the time so we don't run dry? */
14877 		if (slot && rack_slot_reduction) {
14878 			reduce = (slot / rack_slot_reduction);
14879 			if (reduce < slot) {
14880 				slot -= reduce;
14881 			} else
14882 				slot = 0;
14883 		}
14884 		slot *= HPTS_USEC_IN_MSEC;
14885 		if (rack->rc_pace_to_cwnd) {
14886 			uint64_t rate_wanted = 0;
14887 
14888 			slot = pace_to_fill_cwnd(rack, slot, len, segsiz, NULL, &rate_wanted, 1);
14889 			rack->rc_ack_can_sendout_data = 1;
14890 			rack_log_pacing_delay_calc(rack, len, slot, rate_wanted, 0, 0, 14, __LINE__, NULL, 0);
14891 		} else
14892 			rack_log_pacing_delay_calc(rack, len, slot, tr_perms, reduce, 0, 7, __LINE__, NULL, 0);
14893 	} else {
14894 		uint64_t bw_est, res, lentim, rate_wanted;
14895 		uint32_t orig_val, srtt, segs, oh;
14896 		int capped = 0;
14897 		int prev_fill;
14898 
14899 		if ((rack->r_rr_config == 1) && rsm) {
14900 			return (rack->r_ctl.rc_min_to);
14901 		}
14902 		if (rack->use_fixed_rate) {
14903 			rate_wanted = bw_est = rack_get_fixed_pacing_bw(rack);
14904 		} else if ((rack->r_ctl.init_rate == 0) &&
14905 #ifdef NETFLIX_PEAKRATE
14906 			   (rack->rc_tp->t_maxpeakrate == 0) &&
14907 #endif
14908 			   (rack->r_ctl.gp_bw == 0)) {
14909 			/* no way to yet do an estimate */
14910 			bw_est = rate_wanted = 0;
14911 		} else {
14912 			bw_est = rack_get_bw(rack);
14913 			rate_wanted = rack_get_output_bw(rack, bw_est, rsm, &capped);
14914 		}
14915 		if ((bw_est == 0) || (rate_wanted == 0) ||
14916 		    ((rack->gp_ready == 0) && (rack->use_fixed_rate == 0))) {
14917 			/*
14918 			 * No way yet to make a b/w estimate or
14919 			 * our raise is set incorrectly.
14920 			 */
14921 			goto old_method;
14922 		}
14923 		/* We need to account for all the overheads */
14924 		segs = (len + segsiz - 1) / segsiz;
14925 		/*
14926 		 * We need the diff between 1514 bytes (e-mtu with e-hdr)
14927 		 * and how much data we put in each packet. Yes this
14928 		 * means we may be off if we are larger than 1500 bytes
14929 		 * or smaller. But this just makes us more conservative.
14930 		 */
14931 		if (rack_hw_rate_min &&
14932 		    (bw_est < rack_hw_rate_min))
14933 			can_start_hw_pacing = 0;
14934 		if (ETHERNET_SEGMENT_SIZE > segsiz)
14935 			oh = ETHERNET_SEGMENT_SIZE - segsiz;
14936 		else
14937 			oh = 0;
14938 		segs *= oh;
14939 		lentim = (uint64_t)(len + segs) * (uint64_t)HPTS_USEC_IN_SEC;
14940 		res = lentim / rate_wanted;
14941 		slot = (uint32_t)res;
14942 		orig_val = rack->r_ctl.rc_pace_max_segs;
14943 		if (rack->r_ctl.crte == NULL) {
14944 			/*
14945 			 * Only do this if we are not hardware pacing
14946 			 * since if we are doing hw-pacing below we will
14947 			 * set make a call after setting up or changing
14948 			 * the rate.
14949 			 */
14950 			rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
14951 		} else if (rack->rc_inp->inp_snd_tag == NULL) {
14952 			/*
14953 			 * We lost our rate somehow, this can happen
14954 			 * if the interface changed underneath us.
14955 			 */
14956 			tcp_rel_pacing_rate(rack->r_ctl.crte, rack->rc_tp);
14957 			rack->r_ctl.crte = NULL;
14958 			/* Lets re-allow attempting to setup pacing */
14959 			rack->rack_hdrw_pacing = 0;
14960 			rack->rack_attempt_hdwr_pace = 0;
14961 			rack_log_hdwr_pacing(rack,
14962 					     rate_wanted, bw_est, __LINE__,
14963 					     0, 6);
14964 		}
14965 		/* Did we change the TSO size, if so log it */
14966 		if (rack->r_ctl.rc_pace_max_segs != orig_val)
14967 			rack_log_pacing_delay_calc(rack, len, slot, orig_val, 0, 0, 15, __LINE__, NULL, 0);
14968 		prev_fill = rack->r_via_fill_cw;
14969 		if ((rack->rc_pace_to_cwnd) &&
14970 		    (capped == 0) &&
14971 		    (rack->use_fixed_rate == 0) &&
14972 		    (rack->in_probe_rtt == 0) &&
14973 		    (IN_FASTRECOVERY(rack->rc_tp->t_flags) == 0)) {
14974 			/*
14975 			 * We want to pace at our rate *or* faster to
14976 			 * fill the cwnd to the max if its not full.
14977 			 */
14978 			slot = pace_to_fill_cwnd(rack, slot, (len+segs), segsiz, &capped, &rate_wanted, 0);
14979 		}
14980 		if ((rack->rc_inp->inp_route.ro_nh != NULL) &&
14981 		    (rack->rc_inp->inp_route.ro_nh->nh_ifp != NULL)) {
14982 			if ((rack->rack_hdw_pace_ena) &&
14983 			    (can_start_hw_pacing > 0) &&
14984 			    (rack->rack_hdrw_pacing == 0) &&
14985 			    (rack->rack_attempt_hdwr_pace == 0)) {
14986 				/*
14987 				 * Lets attempt to turn on hardware pacing
14988 				 * if we can.
14989 				 */
14990 				rack->rack_attempt_hdwr_pace = 1;
14991 				rack->r_ctl.crte = tcp_set_pacing_rate(rack->rc_tp,
14992 								       rack->rc_inp->inp_route.ro_nh->nh_ifp,
14993 								       rate_wanted,
14994 								       RS_PACING_GEQ,
14995 								       &err, &rack->r_ctl.crte_prev_rate);
14996 				if (rack->r_ctl.crte) {
14997 					rack->rack_hdrw_pacing = 1;
14998 					rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(tp, rate_wanted, segsiz,
14999 												 0, rack->r_ctl.crte,
15000 												 NULL);
15001 					rack_log_hdwr_pacing(rack,
15002 							     rate_wanted, rack->r_ctl.crte->rate, __LINE__,
15003 							     err, 0);
15004 					rack->r_ctl.last_hw_bw_req = rate_wanted;
15005 				} else {
15006 					counter_u64_add(rack_hw_pace_init_fail, 1);
15007 				}
15008 			} else if (rack->rack_hdrw_pacing &&
15009 				   (rack->r_ctl.last_hw_bw_req != rate_wanted)) {
15010 				/* Do we need to adjust our rate? */
15011 				const struct tcp_hwrate_limit_table *nrte;
15012 
15013 				if (rack->r_up_only &&
15014 				    (rate_wanted < rack->r_ctl.crte->rate)) {
15015 					/**
15016 					 * We have four possible states here
15017 					 * having to do with the previous time
15018 					 * and this time.
15019 					 *   previous  |  this-time
15020 					 * A)     0      |     0   -- fill_cw not in the picture
15021 					 * B)     1      |     0   -- we were doing a fill-cw but now are not
15022 					 * C)     1      |     1   -- all rates from fill_cw
15023 					 * D)     0      |     1   -- we were doing non-fill and now we are filling
15024 					 *
15025 					 * For case A, C and D we don't allow a drop. But for
15026 					 * case B where we now our on our steady rate we do
15027 					 * allow a drop.
15028 					 *
15029 					 */
15030 					if (!((prev_fill == 1) && (rack->r_via_fill_cw == 0)))
15031 						goto done_w_hdwr;
15032 				}
15033 				if ((rate_wanted > rack->r_ctl.crte->rate) ||
15034 				    (rate_wanted <= rack->r_ctl.crte_prev_rate)) {
15035 					if (rack_hw_rate_to_low &&
15036 					    (bw_est < rack_hw_rate_to_low)) {
15037 						/*
15038 						 * The pacing rate is too low for hardware, but
15039 						 * do allow hardware pacing to be restarted.
15040 						 */
15041 						rack_log_hdwr_pacing(rack,
15042 							     bw_est, rack->r_ctl.crte->rate, __LINE__,
15043 							     0, 5);
15044 						tcp_rel_pacing_rate(rack->r_ctl.crte, rack->rc_tp);
15045 						rack->r_ctl.crte = NULL;
15046 						rack->rack_attempt_hdwr_pace = 0;
15047 						rack->rack_hdrw_pacing = 0;
15048 						rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
15049 						goto done_w_hdwr;
15050 					}
15051 					nrte = tcp_chg_pacing_rate(rack->r_ctl.crte,
15052 								   rack->rc_tp,
15053 								   rack->rc_inp->inp_route.ro_nh->nh_ifp,
15054 								   rate_wanted,
15055 								   RS_PACING_GEQ,
15056 								   &err, &rack->r_ctl.crte_prev_rate);
15057 					if (nrte == NULL) {
15058 						/* Lost the rate */
15059 						rack->rack_hdrw_pacing = 0;
15060 						rack->r_ctl.crte = NULL;
15061 						rack_log_hdwr_pacing(rack,
15062 								     rate_wanted, 0, __LINE__,
15063 								     err, 1);
15064 						rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
15065 						counter_u64_add(rack_hw_pace_lost, 1);
15066 					} else if (nrte != rack->r_ctl.crte) {
15067 						rack->r_ctl.crte = nrte;
15068 						rack->r_ctl.rc_pace_max_segs = tcp_get_pacing_burst_size(tp, rate_wanted,
15069 													 segsiz, 0,
15070 													 rack->r_ctl.crte,
15071 													 NULL);
15072 						rack_log_hdwr_pacing(rack,
15073 								     rate_wanted, rack->r_ctl.crte->rate, __LINE__,
15074 								     err, 2);
15075 						rack->r_ctl.last_hw_bw_req = rate_wanted;
15076 					}
15077 				} else {
15078 					/* We just need to adjust the segment size */
15079 					rack_set_pace_segments(rack->rc_tp, rack, __LINE__, &rate_wanted);
15080 					rack_log_hdwr_pacing(rack,
15081 							     rate_wanted, rack->r_ctl.crte->rate, __LINE__,
15082 							     0, 4);
15083 					rack->r_ctl.last_hw_bw_req = rate_wanted;
15084 				}
15085 			}
15086 		}
15087 		if ((rack->r_ctl.crte != NULL) &&
15088 		    (rack->r_ctl.crte->rate == rate_wanted)) {
15089 			/*
15090 			 * We need to add a extra if the rates
15091 			 * are exactly matched. The idea is
15092 			 * we want the software to make sure the
15093 			 * queue is empty before adding more, this
15094 			 * gives us N MSS extra pace times where
15095 			 * N is our sysctl
15096 			 */
15097 			slot += (rack->r_ctl.crte->time_between * rack_hw_pace_extra_slots);
15098 		}
15099 done_w_hdwr:
15100 		if (rack_limit_time_with_srtt &&
15101 		    (rack->use_fixed_rate == 0) &&
15102 #ifdef NETFLIX_PEAKRATE
15103 		    (rack->rc_tp->t_maxpeakrate == 0) &&
15104 #endif
15105 		    (rack->rack_hdrw_pacing == 0)) {
15106 			/*
15107 			 * Sanity check, we do not allow the pacing delay
15108 			 * to be longer than the SRTT of the path. If it is
15109 			 * a slow path, then adding a packet should increase
15110 			 * the RTT and compensate for this i.e. the srtt will
15111 			 * be greater so the allowed pacing time will be greater.
15112 			 *
15113 			 * Note this restriction is not for where a peak rate
15114 			 * is set, we are doing fixed pacing or hardware pacing.
15115 			 */
15116 			if (rack->rc_tp->t_srtt)
15117 				srtt = rack->rc_tp->t_srtt;
15118 			else
15119 				srtt = RACK_INITIAL_RTO * HPTS_USEC_IN_MSEC;	/* its in ms convert */
15120 			if (srtt < slot) {
15121 				rack_log_pacing_delay_calc(rack, srtt, slot, rate_wanted, bw_est, lentim, 99, __LINE__, NULL, 0);
15122 				slot = srtt;
15123 			}
15124 		}
15125 		rack_log_pacing_delay_calc(rack, len, slot, rate_wanted, bw_est, lentim, 2, __LINE__, rsm, 0);
15126 	}
15127 	if (rack->r_ctl.crte && (rack->r_ctl.crte->rs_num_enobufs > 0)) {
15128 		/*
15129 		 * If this rate is seeing enobufs when it
15130 		 * goes to send then either the nic is out
15131 		 * of gas or we are mis-estimating the time
15132 		 * somehow and not letting the queue empty
15133 		 * completely. Lets add to the pacing time.
15134 		 */
15135 		int hw_boost_delay;
15136 
15137 		hw_boost_delay = rack->r_ctl.crte->time_between * rack_enobuf_hw_boost_mult;
15138 		if (hw_boost_delay > rack_enobuf_hw_max)
15139 			hw_boost_delay = rack_enobuf_hw_max;
15140 		else if (hw_boost_delay < rack_enobuf_hw_min)
15141 			hw_boost_delay = rack_enobuf_hw_min;
15142 		slot += hw_boost_delay;
15143 	}
15144 	if (slot)
15145 		counter_u64_add(rack_calc_nonzero, 1);
15146 	else
15147 		counter_u64_add(rack_calc_zero, 1);
15148 	return (slot);
15149 }
15150 
15151 static void
15152 rack_start_gp_measurement(struct tcpcb *tp, struct tcp_rack *rack,
15153     tcp_seq startseq, uint32_t sb_offset)
15154 {
15155 	struct rack_sendmap *my_rsm = NULL;
15156 	struct rack_sendmap fe;
15157 
15158 	if (tp->t_state < TCPS_ESTABLISHED) {
15159 		/*
15160 		 * We don't start any measurements if we are
15161 		 * not at least established.
15162 		 */
15163 		return;
15164 	}
15165 	if (tp->t_state >= TCPS_FIN_WAIT_1) {
15166 		/*
15167 		 * We will get no more data into the SB
15168 		 * this means we need to have the data available
15169 		 * before we start a measurement.
15170 		 */
15171 
15172 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) <
15173 		    max(rc_init_window(rack),
15174 			(MIN_GP_WIN * ctf_fixed_maxseg(tp)))) {
15175 			/* Nope not enough data */
15176 			return;
15177 		}
15178 	}
15179 	tp->t_flags |= TF_GPUTINPROG;
15180 	rack->r_ctl.rc_gp_lowrtt = 0xffffffff;
15181 	rack->r_ctl.rc_gp_high_rwnd = rack->rc_tp->snd_wnd;
15182 	tp->gput_seq = startseq;
15183 	rack->app_limited_needs_set = 0;
15184 	if (rack->in_probe_rtt)
15185 		rack->measure_saw_probe_rtt = 1;
15186 	else if ((rack->measure_saw_probe_rtt) &&
15187 		 (SEQ_GEQ(tp->gput_seq, rack->r_ctl.rc_probertt_sndmax_atexit)))
15188 		rack->measure_saw_probe_rtt = 0;
15189 	if (rack->rc_gp_filled)
15190 		tp->gput_ts = tcp_tv_to_usectick(&rack->r_ctl.act_rcv_time);
15191 	else {
15192 		/* Special case initial measurement */
15193 		struct timeval tv;
15194 
15195 		tp->gput_ts = tcp_get_usecs(&tv);
15196 		rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
15197 	}
15198 	/*
15199 	 * We take a guess out into the future,
15200 	 * if we have no measurement and no
15201 	 * initial rate, we measure the first
15202 	 * initial-windows worth of data to
15203 	 * speed up getting some GP measurement and
15204 	 * thus start pacing.
15205 	 */
15206 	if ((rack->rc_gp_filled == 0) && (rack->r_ctl.init_rate == 0)) {
15207 		rack->app_limited_needs_set = 1;
15208 		tp->gput_ack = startseq + max(rc_init_window(rack),
15209 					      (MIN_GP_WIN * ctf_fixed_maxseg(tp)));
15210 		rack_log_pacing_delay_calc(rack,
15211 					   tp->gput_seq,
15212 					   tp->gput_ack,
15213 					   0,
15214 					   tp->gput_ts,
15215 					   rack->r_ctl.rc_app_limited_cnt,
15216 					   9,
15217 					   __LINE__, NULL, 0);
15218 		return;
15219 	}
15220 	if (sb_offset) {
15221 		/*
15222 		 * We are out somewhere in the sb
15223 		 * can we use the already outstanding data?
15224 		 */
15225 		if (rack->r_ctl.rc_app_limited_cnt == 0) {
15226 			/*
15227 			 * Yes first one is good and in this case
15228 			 * the tp->gput_ts is correctly set based on
15229 			 * the last ack that arrived (no need to
15230 			 * set things up when an ack comes in).
15231 			 */
15232 			my_rsm = RB_MIN(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
15233 			if ((my_rsm == NULL) ||
15234 			    (my_rsm->r_rtr_cnt != 1)) {
15235 				/* retransmission? */
15236 				goto use_latest;
15237 			}
15238 		} else {
15239 			if (rack->r_ctl.rc_first_appl == NULL) {
15240 				/*
15241 				 * If rc_first_appl is NULL
15242 				 * then the cnt should be 0.
15243 				 * This is probably an error, maybe
15244 				 * a KASSERT would be approprate.
15245 				 */
15246 				goto use_latest;
15247 			}
15248 			/*
15249 			 * If we have a marker pointer to the last one that is
15250 			 * app limited we can use that, but we need to set
15251 			 * things up so that when it gets ack'ed we record
15252 			 * the ack time (if its not already acked).
15253 			 */
15254 			rack->app_limited_needs_set = 1;
15255 			/*
15256 			 * We want to get to the rsm that is either
15257 			 * next with space i.e. over 1 MSS or the one
15258 			 * after that (after the app-limited).
15259 			 */
15260 			my_rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
15261 					 rack->r_ctl.rc_first_appl);
15262 			if (my_rsm) {
15263 				if ((my_rsm->r_end - my_rsm->r_start) <= ctf_fixed_maxseg(tp))
15264 					/* Have to use the next one */
15265 					my_rsm = RB_NEXT(rack_rb_tree_head, &rack->r_ctl.rc_mtree,
15266 							 my_rsm);
15267 				else {
15268 					/* Use after the first MSS of it is acked */
15269 					tp->gput_seq = my_rsm->r_start + ctf_fixed_maxseg(tp);
15270 					goto start_set;
15271 				}
15272 			}
15273 			if ((my_rsm == NULL) ||
15274 			    (my_rsm->r_rtr_cnt != 1)) {
15275 				/*
15276 				 * Either its a retransmit or
15277 				 * the last is the app-limited one.
15278 				 */
15279 				goto use_latest;
15280 			}
15281 		}
15282 		tp->gput_seq = my_rsm->r_start;
15283 start_set:
15284 		if (my_rsm->r_flags & RACK_ACKED) {
15285 			/*
15286 			 * This one has been acked use the arrival ack time
15287 			 */
15288 			tp->gput_ts = (uint32_t)my_rsm->r_ack_arrival;
15289 			rack->app_limited_needs_set = 0;
15290 		}
15291 		rack->r_ctl.rc_gp_output_ts = my_rsm->r_tim_lastsent[(my_rsm->r_rtr_cnt-1)];
15292 		tp->gput_ack = tp->gput_seq + rack_get_measure_window(tp, rack);
15293 		rack_log_pacing_delay_calc(rack,
15294 					   tp->gput_seq,
15295 					   tp->gput_ack,
15296 					   (uint64_t)my_rsm,
15297 					   tp->gput_ts,
15298 					   rack->r_ctl.rc_app_limited_cnt,
15299 					   9,
15300 					   __LINE__, NULL, 0);
15301 		return;
15302 	}
15303 
15304 use_latest:
15305 	/*
15306 	 * We don't know how long we may have been
15307 	 * idle or if this is the first-send. Lets
15308 	 * setup the flag so we will trim off
15309 	 * the first ack'd data so we get a true
15310 	 * measurement.
15311 	 */
15312 	rack->app_limited_needs_set = 1;
15313 	tp->gput_ack = startseq + rack_get_measure_window(tp, rack);
15314 	/* Find this guy so we can pull the send time */
15315 	fe.r_start = startseq;
15316 	my_rsm = RB_FIND(rack_rb_tree_head, &rack->r_ctl.rc_mtree, &fe);
15317 	if (my_rsm) {
15318 		rack->r_ctl.rc_gp_output_ts = my_rsm->r_tim_lastsent[(my_rsm->r_rtr_cnt-1)];
15319 		if (my_rsm->r_flags & RACK_ACKED) {
15320 			/*
15321 			 * Unlikely since its probably what was
15322 			 * just transmitted (but I am paranoid).
15323 			 */
15324 			tp->gput_ts = (uint32_t)my_rsm->r_ack_arrival;
15325 			rack->app_limited_needs_set = 0;
15326 		}
15327 		if (SEQ_LT(my_rsm->r_start, tp->gput_seq)) {
15328 			/* This also is unlikely */
15329 			tp->gput_seq = my_rsm->r_start;
15330 		}
15331 	} else {
15332 		/*
15333 		 * TSNH unless we have some send-map limit,
15334 		 * and even at that it should not be hitting
15335 		 * that limit (we should have stopped sending).
15336 		 */
15337 		struct timeval tv;
15338 
15339 		microuptime(&tv);
15340 		rack->r_ctl.rc_gp_output_ts = rack_to_usec_ts(&tv);
15341 	}
15342 	rack_log_pacing_delay_calc(rack,
15343 				   tp->gput_seq,
15344 				   tp->gput_ack,
15345 				   (uint64_t)my_rsm,
15346 				   tp->gput_ts,
15347 				   rack->r_ctl.rc_app_limited_cnt,
15348 				   9, __LINE__, NULL, 0);
15349 }
15350 
15351 static inline uint32_t
15352 rack_what_can_we_send(struct tcpcb *tp, struct tcp_rack *rack,  uint32_t cwnd_to_use,
15353     uint32_t avail, int32_t sb_offset)
15354 {
15355 	uint32_t len;
15356 	uint32_t sendwin;
15357 
15358 	if (tp->snd_wnd > cwnd_to_use)
15359 		sendwin = cwnd_to_use;
15360 	else
15361 		sendwin = tp->snd_wnd;
15362 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
15363 		/* We never want to go over our peers rcv-window */
15364 		len = 0;
15365 	} else {
15366 		uint32_t flight;
15367 
15368 		flight = ctf_flight_size(tp, rack->r_ctl.rc_sacked);
15369 		if (flight >= sendwin) {
15370 			/*
15371 			 * We have in flight what we are allowed by cwnd (if
15372 			 * it was rwnd blocking it would have hit above out
15373 			 * >= tp->snd_wnd).
15374 			 */
15375 			return (0);
15376 		}
15377 		len = sendwin - flight;
15378 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
15379 			/* We would send too much (beyond the rwnd) */
15380 			len = tp->snd_wnd - ctf_outstanding(tp);
15381 		}
15382 		if ((len + sb_offset) > avail) {
15383 			/*
15384 			 * We don't have that much in the SB, how much is
15385 			 * there?
15386 			 */
15387 			len = avail - sb_offset;
15388 		}
15389 	}
15390 	return (len);
15391 }
15392 
15393 static void
15394 rack_log_fsb(struct tcp_rack *rack, struct tcpcb *tp, struct socket *so, uint32_t flags,
15395 	     unsigned ipoptlen, int32_t orig_len, int32_t len, int error,
15396 	     int rsm_is_null, int optlen, int line, uint16_t mode)
15397 {
15398 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
15399 		union tcp_log_stackspecific log;
15400 		struct timeval tv;
15401 
15402 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
15403 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
15404 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
15405 		log.u_bbr.flex1 = error;
15406 		log.u_bbr.flex2 = flags;
15407 		log.u_bbr.flex3 = rsm_is_null;
15408 		log.u_bbr.flex4 = ipoptlen;
15409 		log.u_bbr.flex5 = tp->rcv_numsacks;
15410 		log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
15411 		log.u_bbr.flex7 = optlen;
15412 		log.u_bbr.flex8 = rack->r_fsb_inited;
15413 		log.u_bbr.applimited = rack->r_fast_output;
15414 		log.u_bbr.bw_inuse = rack_get_bw(rack);
15415 		log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
15416 		log.u_bbr.cwnd_gain = mode;
15417 		log.u_bbr.pkts_out = orig_len;
15418 		log.u_bbr.lt_epoch = len;
15419 		log.u_bbr.delivered = line;
15420 		log.u_bbr.timeStamp = tcp_get_usecs(&tv);
15421 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
15422 		tcp_log_event_(tp, NULL, &so->so_rcv, &so->so_snd, TCP_LOG_FSB, 0,
15423 			       len, &log, false, NULL, NULL, 0, &tv);
15424 	}
15425 }
15426 
15427 
15428 static struct mbuf *
15429 rack_fo_base_copym(struct mbuf *the_m, uint32_t the_off, int32_t *plen,
15430 		   struct rack_fast_send_blk *fsb,
15431 		   int32_t seglimit, int32_t segsize, int hw_tls)
15432 {
15433 #ifdef KERN_TLS
15434 	struct ktls_session *tls, *ntls;
15435 	struct mbuf *start;
15436 #endif
15437 	struct mbuf *m, *n, **np, *smb;
15438 	struct mbuf *top;
15439 	int32_t off, soff;
15440 	int32_t len = *plen;
15441 	int32_t fragsize;
15442 	int32_t len_cp = 0;
15443 	uint32_t mlen, frags;
15444 
15445 	soff = off = the_off;
15446 	smb = m = the_m;
15447 	np = &top;
15448 	top = NULL;
15449 #ifdef KERN_TLS
15450 	if (hw_tls && (m->m_flags & M_EXTPG))
15451 		tls = m->m_epg_tls;
15452 	else
15453 		tls = NULL;
15454 	start = m;
15455 #endif
15456 	while (len > 0) {
15457 		if (m == NULL) {
15458 			*plen = len_cp;
15459 			break;
15460 		}
15461 #ifdef KERN_TLS
15462 		if (hw_tls) {
15463 			if (m->m_flags & M_EXTPG)
15464 				ntls = m->m_epg_tls;
15465 			else
15466 				ntls = NULL;
15467 
15468 			/*
15469 			 * Avoid mixing TLS records with handshake
15470 			 * data or TLS records from different
15471 			 * sessions.
15472 			 */
15473 			if (tls != ntls) {
15474 				MPASS(m != start);
15475 				*plen = len_cp;
15476 				break;
15477 			}
15478 		}
15479 #endif
15480 		mlen = min(len, m->m_len - off);
15481 		if (seglimit) {
15482 			/*
15483 			 * For M_EXTPG mbufs, add 3 segments
15484 			 * + 1 in case we are crossing page boundaries
15485 			 * + 2 in case the TLS hdr/trailer are used
15486 			 * It is cheaper to just add the segments
15487 			 * than it is to take the cache miss to look
15488 			 * at the mbuf ext_pgs state in detail.
15489 			 */
15490 			if (m->m_flags & M_EXTPG) {
15491 				fragsize = min(segsize, PAGE_SIZE);
15492 				frags = 3;
15493 			} else {
15494 				fragsize = segsize;
15495 				frags = 0;
15496 			}
15497 
15498 			/* Break if we really can't fit anymore. */
15499 			if ((frags + 1) >= seglimit) {
15500 				*plen =	len_cp;
15501 				break;
15502 			}
15503 
15504 			/*
15505 			 * Reduce size if you can't copy the whole
15506 			 * mbuf. If we can't copy the whole mbuf, also
15507 			 * adjust len so the loop will end after this
15508 			 * mbuf.
15509 			 */
15510 			if ((frags + howmany(mlen, fragsize)) >= seglimit) {
15511 				mlen = (seglimit - frags - 1) * fragsize;
15512 				len = mlen;
15513 				*plen = len_cp + len;
15514 			}
15515 			frags += howmany(mlen, fragsize);
15516 			if (frags == 0)
15517 				frags++;
15518 			seglimit -= frags;
15519 			KASSERT(seglimit > 0,
15520 			    ("%s: seglimit went too low", __func__));
15521 		}
15522 		n = m_get(M_NOWAIT, m->m_type);
15523 		*np = n;
15524 		if (n == NULL)
15525 			goto nospace;
15526 		n->m_len = mlen;
15527 		soff += mlen;
15528 		len_cp += n->m_len;
15529 		if (m->m_flags & (M_EXT|M_EXTPG)) {
15530 			n->m_data = m->m_data + off;
15531 			mb_dupcl(n, m);
15532 		} else {
15533 			bcopy(mtod(m, caddr_t)+off, mtod(n, caddr_t),
15534 			    (u_int)n->m_len);
15535 		}
15536 		len -= n->m_len;
15537 		off = 0;
15538 		m = m->m_next;
15539 		np = &n->m_next;
15540 		if (len || (soff == smb->m_len)) {
15541 			/*
15542 			 * We have more so we move forward  or
15543 			 * we have consumed the entire mbuf and
15544 			 * len has fell to 0.
15545 			 */
15546 			soff = 0;
15547 			smb = m;
15548 		}
15549 
15550 	}
15551 	if (fsb != NULL) {
15552 		fsb->m = smb;
15553 		fsb->off = soff;
15554 		if (smb) {
15555 			/*
15556 			 * Save off the size of the mbuf. We do
15557 			 * this so that we can recognize when it
15558 			 * has been trimmed by sbcut() as acks
15559 			 * come in.
15560 			 */
15561 			fsb->o_m_len = smb->m_len;
15562 		} else {
15563 			/*
15564 			 * This is the case where the next mbuf went to NULL. This
15565 			 * means with this copy we have sent everything in the sb.
15566 			 * In theory we could clear the fast_output flag, but lets
15567 			 * not since its possible that we could get more added
15568 			 * and acks that call the extend function which would let
15569 			 * us send more.
15570 			 */
15571 			fsb->o_m_len = 0;
15572 		}
15573 	}
15574 	return (top);
15575 nospace:
15576 	if (top)
15577 		m_freem(top);
15578 	return (NULL);
15579 
15580 }
15581 
15582 /*
15583  * This is a copy of m_copym(), taking the TSO segment size/limit
15584  * constraints into account, and advancing the sndptr as it goes.
15585  */
15586 static struct mbuf *
15587 rack_fo_m_copym(struct tcp_rack *rack, int32_t *plen,
15588 		int32_t seglimit, int32_t segsize, struct mbuf **s_mb, int *s_soff)
15589 {
15590 	struct mbuf *m, *n;
15591 	int32_t soff;
15592 
15593 	soff = rack->r_ctl.fsb.off;
15594 	m = rack->r_ctl.fsb.m;
15595 	if (rack->r_ctl.fsb.o_m_len > m->m_len) {
15596 		/*
15597 		 * The mbuf had the front of it chopped off by an ack
15598 		 * we need to adjust the soff/off by that difference.
15599 		 */
15600 		uint32_t delta;
15601 
15602 		delta = rack->r_ctl.fsb.o_m_len - m->m_len;
15603 		soff -= delta;
15604 	} else if (rack->r_ctl.fsb.o_m_len < m->m_len) {
15605 		/*
15606 		 * The mbuf was expanded probably by
15607 		 * a m_compress. Just update o_m_len.
15608 		 */
15609 		rack->r_ctl.fsb.o_m_len = m->m_len;
15610 	}
15611 	KASSERT(soff >= 0, ("%s, negative off %d", __FUNCTION__, soff));
15612 	KASSERT(*plen >= 0, ("%s, negative len %d", __FUNCTION__, *plen));
15613 	KASSERT(soff < m->m_len, ("%s rack:%p len:%u m:%p m->m_len:%u < off?",
15614 				 __FUNCTION__,
15615 				 rack, *plen, m, m->m_len));
15616 	/* Save off the right location before we copy and advance */
15617 	*s_soff = soff;
15618 	*s_mb = rack->r_ctl.fsb.m;
15619 	n = rack_fo_base_copym(m, soff, plen,
15620 			       &rack->r_ctl.fsb,
15621 			       seglimit, segsize, rack->r_ctl.fsb.hw_tls);
15622 	return (n);
15623 }
15624 
15625 static int
15626 rack_fast_rsm_output(struct tcpcb *tp, struct tcp_rack *rack, struct rack_sendmap *rsm,
15627 		     uint64_t ts_val, uint32_t cts, uint32_t ms_cts, struct timeval *tv, int len, uint8_t doing_tlp)
15628 {
15629 	/*
15630 	 * Enter the fast retransmit path. We are given that a sched_pin is
15631 	 * in place (if accounting is compliled in) and the cycle count taken
15632 	 * at the entry is in the ts_val. The concept her is that the rsm
15633 	 * now holds the mbuf offsets and such so we can directly transmit
15634 	 * without a lot of overhead, the len field is already set for
15635 	 * us to prohibit us from sending too much (usually its 1MSS).
15636 	 */
15637 	struct ip *ip = NULL;
15638 	struct udphdr *udp = NULL;
15639 	struct tcphdr *th = NULL;
15640 	struct mbuf *m = NULL;
15641 	struct inpcb *inp;
15642 	uint8_t *cpto;
15643 	struct tcp_log_buffer *lgb;
15644 #ifdef TCP_ACCOUNTING
15645 	uint64_t crtsc;
15646 	int cnt_thru = 1;
15647 #endif
15648 	struct tcpopt to;
15649 	u_char opt[TCP_MAXOLEN];
15650 	uint32_t hdrlen, optlen;
15651 	int32_t slot, segsiz, max_val, tso = 0, error, flags, ulen = 0;
15652 	uint32_t us_cts;
15653 	uint32_t if_hw_tsomaxsegcount = 0, startseq;
15654 	uint32_t if_hw_tsomaxsegsize;
15655 
15656 #ifdef INET6
15657 	struct ip6_hdr *ip6 = NULL;
15658 
15659 	if (rack->r_is_v6) {
15660 		ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
15661 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
15662 	} else
15663 #endif				/* INET6 */
15664 	{
15665 		ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
15666 		hdrlen = sizeof(struct tcpiphdr);
15667 	}
15668 	if (tp->t_port && (V_tcp_udp_tunneling_port == 0)) {
15669 		goto failed;
15670 	}
15671 	if (doing_tlp) {
15672 		/* Its a TLP add the flag, it may already be there but be sure */
15673 		rsm->r_flags |= RACK_TLP;
15674 	} else {
15675 		/* If it was a TLP it is not not on this retransmit */
15676 		rsm->r_flags &= ~RACK_TLP;
15677 	}
15678 	startseq = rsm->r_start;
15679 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
15680 	inp = rack->rc_inp;
15681 	to.to_flags = 0;
15682 	flags = tcp_outflags[tp->t_state];
15683 	if (flags & (TH_SYN|TH_RST)) {
15684 		goto failed;
15685 	}
15686 	if (rsm->r_flags & RACK_HAS_FIN) {
15687 		/* We can't send a FIN here */
15688 		goto failed;
15689 	}
15690 	if (flags & TH_FIN) {
15691 		/* We never send a FIN */
15692 		flags &= ~TH_FIN;
15693 	}
15694 	if (tp->t_flags & TF_RCVD_TSTMP) {
15695 		to.to_tsval = ms_cts + tp->ts_offset;
15696 		to.to_tsecr = tp->ts_recent;
15697 		to.to_flags = TOF_TS;
15698 	}
15699 	optlen = tcp_addoptions(&to, opt);
15700 	hdrlen += optlen;
15701 	udp = rack->r_ctl.fsb.udp;
15702 	if (udp)
15703 		hdrlen += sizeof(struct udphdr);
15704 	if (rack->r_ctl.rc_pace_max_segs)
15705 		max_val = rack->r_ctl.rc_pace_max_segs;
15706 	else if (rack->rc_user_set_max_segs)
15707 		max_val = rack->rc_user_set_max_segs * segsiz;
15708 	else
15709 		max_val = len;
15710 	if ((tp->t_flags & TF_TSO) &&
15711 	    V_tcp_do_tso &&
15712 	    (len > segsiz) &&
15713 	    (tp->t_port == 0))
15714 		tso = 1;
15715 #ifdef INET6
15716 	if (MHLEN < hdrlen + max_linkhdr)
15717 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
15718 	else
15719 #endif
15720 		m = m_gethdr(M_NOWAIT, MT_DATA);
15721 	if (m == NULL)
15722 		goto failed;
15723 	m->m_data += max_linkhdr;
15724 	m->m_len = hdrlen;
15725 	th = rack->r_ctl.fsb.th;
15726 	/* Establish the len to send */
15727 	if (len > max_val)
15728 		len = max_val;
15729 	if ((tso) && (len + optlen > tp->t_maxseg)) {
15730 		uint32_t if_hw_tsomax;
15731 		int32_t max_len;
15732 
15733 		/* extract TSO information */
15734 		if_hw_tsomax = tp->t_tsomax;
15735 		if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
15736 		if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
15737 		/*
15738 		 * Check if we should limit by maximum payload
15739 		 * length:
15740 		 */
15741 		if (if_hw_tsomax != 0) {
15742 			/* compute maximum TSO length */
15743 			max_len = (if_hw_tsomax - hdrlen -
15744 				   max_linkhdr);
15745 			if (max_len <= 0) {
15746 				goto failed;
15747 			} else if (len > max_len) {
15748 				len = max_len;
15749 			}
15750 		}
15751 		if (len <= segsiz) {
15752 			/*
15753 			 * In case there are too many small fragments don't
15754 			 * use TSO:
15755 			 */
15756 			tso = 0;
15757 		}
15758 	} else {
15759 		tso = 0;
15760 	}
15761 	if ((tso == 0) && (len > segsiz))
15762 		len = segsiz;
15763 	us_cts = tcp_get_usecs(tv);
15764 	if ((len == 0) ||
15765 	    (len <= MHLEN - hdrlen - max_linkhdr)) {
15766 		goto failed;
15767 	}
15768 	th->th_seq = htonl(rsm->r_start);
15769 	th->th_ack = htonl(tp->rcv_nxt);
15770 	/*
15771 	 * The PUSH bit should only be applied
15772 	 * if the full retransmission is made. If
15773 	 * we are sending less than this is the
15774 	 * left hand edge and should not have
15775 	 * the PUSH bit.
15776 	 */
15777 	if ((rsm->r_flags & RACK_HAD_PUSH) &&
15778 	    (len == (rsm->r_end - rsm->r_start)))
15779 		flags |= TH_PUSH;
15780 	th->th_flags = flags;
15781 	th->th_win = htons((u_short)(rack->r_ctl.fsb.recwin >> tp->rcv_scale));
15782 	if (th->th_win == 0) {
15783 		tp->t_sndzerowin++;
15784 		tp->t_flags |= TF_RXWIN0SENT;
15785 	} else
15786 		tp->t_flags &= ~TF_RXWIN0SENT;
15787 	if (rsm->r_flags & RACK_TLP) {
15788 		/*
15789 		 * TLP should not count in retran count, but
15790 		 * in its own bin
15791 		 */
15792 		counter_u64_add(rack_tlp_retran, 1);
15793 		counter_u64_add(rack_tlp_retran_bytes, len);
15794 	} else {
15795 		tp->t_sndrexmitpack++;
15796 		KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
15797 		KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
15798 	}
15799 #ifdef STATS
15800 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
15801 				 len);
15802 #endif
15803 	if (rsm->m == NULL)
15804 		goto failed;
15805 	if (rsm->orig_m_len != rsm->m->m_len) {
15806 		/* Fix up the orig_m_len and possibly the mbuf offset */
15807 		rack_adjust_orig_mlen(rsm);
15808 	}
15809 	m->m_next = rack_fo_base_copym(rsm->m, rsm->soff, &len, NULL, if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, rsm->r_hw_tls);
15810 	if (len <= segsiz) {
15811 		/*
15812 		 * Must have ran out of mbufs for the copy
15813 		 * shorten it to no longer need tso. Lets
15814 		 * not put on sendalot since we are low on
15815 		 * mbufs.
15816 		 */
15817 		tso = 0;
15818 	}
15819 	if ((m->m_next == NULL) || (len <= 0)){
15820 		goto failed;
15821 	}
15822 	if (udp) {
15823 		if (rack->r_is_v6)
15824 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
15825 		else
15826 			ulen = hdrlen + len - sizeof(struct ip);
15827 		udp->uh_ulen = htons(ulen);
15828 	}
15829 	m->m_pkthdr.rcvif = (struct ifnet *)0;
15830 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
15831 #ifdef INET6
15832 	if (rack->r_is_v6) {
15833 		if (tp->t_port) {
15834 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
15835 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15836 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
15837 			th->th_sum = htons(0);
15838 			UDPSTAT_INC(udps_opackets);
15839 		} else {
15840 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
15841 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15842 			th->th_sum = in6_cksum_pseudo(ip6,
15843 						      sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
15844 						      0);
15845 		}
15846 	}
15847 #endif
15848 #if defined(INET6) && defined(INET)
15849 	else
15850 #endif
15851 #ifdef INET
15852 	{
15853 		if (tp->t_port) {
15854 			m->m_pkthdr.csum_flags = CSUM_UDP;
15855 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
15856 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
15857 						ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
15858 			th->th_sum = htons(0);
15859 			UDPSTAT_INC(udps_opackets);
15860 		} else {
15861 			m->m_pkthdr.csum_flags = CSUM_TCP;
15862 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
15863 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
15864 					       ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
15865 									IPPROTO_TCP + len + optlen));
15866 		}
15867 		/* IP version must be set here for ipv4/ipv6 checking later */
15868 		KASSERT(ip->ip_v == IPVERSION,
15869 			("%s: IP version incorrect: %d", __func__, ip->ip_v));
15870 	}
15871 #endif
15872 	if (tso) {
15873 		KASSERT(len > tp->t_maxseg - optlen,
15874 			("%s: len <= tso_segsz tp:%p", __func__, tp));
15875 		m->m_pkthdr.csum_flags |= CSUM_TSO;
15876 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
15877 	}
15878 #ifdef INET6
15879 	if (rack->r_is_v6) {
15880 		ip6->ip6_hlim = rack->r_ctl.fsb.hoplimit;
15881 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
15882 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
15883 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15884 		else
15885 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15886 	}
15887 #endif
15888 #if defined(INET) && defined(INET6)
15889 	else
15890 #endif
15891 #ifdef INET
15892 	{
15893 		ip->ip_len = htons(m->m_pkthdr.len);
15894 		ip->ip_ttl = rack->r_ctl.fsb.hoplimit;
15895 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
15896 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
15897 			if (tp->t_port == 0 || len < V_tcp_minmss) {
15898 				ip->ip_off |= htons(IP_DF);
15899 			}
15900 		} else {
15901 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
15902 		}
15903 	}
15904 #endif
15905 	/* Time to copy in our header */
15906 	cpto = mtod(m, uint8_t *);
15907 	memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
15908 	th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
15909 	if (optlen) {
15910 		bcopy(opt, th + 1, optlen);
15911 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
15912 	} else {
15913 		th->th_off = sizeof(struct tcphdr) >> 2;
15914 	}
15915 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
15916 		union tcp_log_stackspecific log;
15917 
15918 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
15919 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
15920 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
15921 		if (rack->rack_no_prr)
15922 			log.u_bbr.flex1 = 0;
15923 		else
15924 			log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
15925 		log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
15926 		log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
15927 		log.u_bbr.flex4 = max_val;
15928 		log.u_bbr.flex5 = 0;
15929 		/* Save off the early/late values */
15930 		log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
15931 		log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
15932 		log.u_bbr.bw_inuse = rack_get_bw(rack);
15933 		if (doing_tlp == 0)
15934 			log.u_bbr.flex8 = 1;
15935 		else
15936 			log.u_bbr.flex8 = 2;
15937 		log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
15938 		log.u_bbr.flex7 = 55;
15939 		log.u_bbr.pkts_out = tp->t_maxseg;
15940 		log.u_bbr.timeStamp = cts;
15941 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
15942 		log.u_bbr.lt_epoch = rack->r_ctl.cwnd_to_use;
15943 		log.u_bbr.delivered = 0;
15944 		lgb = tcp_log_event_(tp, th, NULL, NULL, TCP_LOG_OUT, ERRNO_UNK,
15945 				     len, &log, false, NULL, NULL, 0, tv);
15946 	} else
15947 		lgb = NULL;
15948 #ifdef INET6
15949 	if (rack->r_is_v6) {
15950 		error = ip6_output(m, NULL,
15951 				   &inp->inp_route6,
15952 				   0, NULL, NULL, inp);
15953 	}
15954 #endif
15955 #if defined(INET) && defined(INET6)
15956 	else
15957 #endif
15958 #ifdef INET
15959 	{
15960 		error = ip_output(m, NULL,
15961 				  &inp->inp_route,
15962 				  0, 0, inp);
15963 	}
15964 #endif
15965 	m = NULL;
15966 	if (lgb) {
15967 		lgb->tlb_errno = error;
15968 		lgb = NULL;
15969 	}
15970 	if (error) {
15971 		goto failed;
15972 	}
15973 	rack_log_output(tp, &to, len, rsm->r_start, flags, error, rack_to_usec_ts(tv),
15974 			rsm, RACK_SENT_FP, rsm->m, rsm->soff, rsm->r_hw_tls);
15975 	if (doing_tlp && (rack->fast_rsm_hack == 0)) {
15976 		rack->rc_tlp_in_progress = 1;
15977 		rack->r_ctl.rc_tlp_cnt_out++;
15978 	}
15979 	if (error == 0) {
15980 		tcp_account_for_send(tp, len, 1, doing_tlp, rsm->r_hw_tls);
15981 		if (doing_tlp) {
15982 			rack->rc_last_sent_tlp_past_cumack = 0;
15983 			rack->rc_last_sent_tlp_seq_valid = 1;
15984 			rack->r_ctl.last_sent_tlp_seq = rsm->r_start;
15985 			rack->r_ctl.last_sent_tlp_len = rsm->r_end - rsm->r_start;
15986 		}
15987 	}
15988 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
15989 	rack->forced_ack = 0;	/* If we send something zap the FA flag */
15990 	if (IN_FASTRECOVERY(tp->t_flags) && rsm)
15991 		rack->r_ctl.retran_during_recovery += len;
15992 	{
15993 		int idx;
15994 
15995 		idx = (len / segsiz) + 3;
15996 		if (idx >= TCP_MSS_ACCT_ATIMER)
15997 			counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
15998 		else
15999 			counter_u64_add(rack_out_size[idx], 1);
16000 	}
16001 	if (tp->t_rtttime == 0) {
16002 		tp->t_rtttime = ticks;
16003 		tp->t_rtseq = startseq;
16004 		KMOD_TCPSTAT_INC(tcps_segstimed);
16005 	}
16006 	counter_u64_add(rack_fto_rsm_send, 1);
16007 	if (error && (error == ENOBUFS)) {
16008 		slot = ((1 + rack->rc_enobuf) * HPTS_USEC_IN_MSEC);
16009 		if (rack->rc_enobuf < 0x7f)
16010 			rack->rc_enobuf++;
16011 		if (slot < (10 * HPTS_USEC_IN_MSEC))
16012 			slot = 10 * HPTS_USEC_IN_MSEC;
16013 	} else
16014 		slot = rack_get_pacing_delay(rack, tp, len, NULL, segsiz);
16015 	if ((slot == 0) ||
16016 	    (rack->rc_always_pace == 0) ||
16017 	    (rack->r_rr_config == 1)) {
16018 		/*
16019 		 * We have no pacing set or we
16020 		 * are using old-style rack or
16021 		 * we are overriden to use the old 1ms pacing.
16022 		 */
16023 		slot = rack->r_ctl.rc_min_to;
16024 	}
16025 	rack_start_hpts_timer(rack, tp, cts, slot, len, 0);
16026 	if (rack->r_must_retran) {
16027 		rack->r_ctl.rc_out_at_rto -= (rsm->r_end - rsm->r_start);
16028 		if (SEQ_GEQ(rsm->r_end, rack->r_ctl.rc_snd_max_at_rto)) {
16029 			/*
16030 			 * We have retransmitted all we need.
16031 			 */
16032 			rack->r_must_retran = 0;
16033 			rack->r_ctl.rc_out_at_rto = 0;
16034 		}
16035 	}
16036 #ifdef TCP_ACCOUNTING
16037 	crtsc = get_cyclecount();
16038 	if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16039 		tp->tcp_cnt_counters[SND_OUT_DATA] += cnt_thru;
16040 	}
16041 	counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], cnt_thru);
16042 	if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16043 		tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
16044 	}
16045 	counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
16046 	if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16047 		tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((len + segsiz - 1) / segsiz);
16048 	}
16049 	counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((len + segsiz - 1) / segsiz));
16050 	sched_unpin();
16051 #endif
16052 	return (0);
16053 failed:
16054 	if (m)
16055 		m_free(m);
16056 	return (-1);
16057 }
16058 
16059 static void
16060 rack_sndbuf_autoscale(struct tcp_rack *rack)
16061 {
16062 	/*
16063 	 * Automatic sizing of send socket buffer.  Often the send buffer
16064 	 * size is not optimally adjusted to the actual network conditions
16065 	 * at hand (delay bandwidth product).  Setting the buffer size too
16066 	 * small limits throughput on links with high bandwidth and high
16067 	 * delay (eg. trans-continental/oceanic links).  Setting the
16068 	 * buffer size too big consumes too much real kernel memory,
16069 	 * especially with many connections on busy servers.
16070 	 *
16071 	 * The criteria to step up the send buffer one notch are:
16072 	 *  1. receive window of remote host is larger than send buffer
16073 	 *     (with a fudge factor of 5/4th);
16074 	 *  2. send buffer is filled to 7/8th with data (so we actually
16075 	 *     have data to make use of it);
16076 	 *  3. send buffer fill has not hit maximal automatic size;
16077 	 *  4. our send window (slow start and cogestion controlled) is
16078 	 *     larger than sent but unacknowledged data in send buffer.
16079 	 *
16080 	 * Note that the rack version moves things much faster since
16081 	 * we want to avoid hitting cache lines in the rack_fast_output()
16082 	 * path so this is called much less often and thus moves
16083 	 * the SB forward by a percentage.
16084 	 */
16085 	struct socket *so;
16086 	struct tcpcb *tp;
16087 	uint32_t sendwin, scaleup;
16088 
16089 	tp = rack->rc_tp;
16090 	so = rack->rc_inp->inp_socket;
16091 	sendwin = min(rack->r_ctl.cwnd_to_use, tp->snd_wnd);
16092 	if (V_tcp_do_autosndbuf && so->so_snd.sb_flags & SB_AUTOSIZE) {
16093 		if ((tp->snd_wnd / 4 * 5) >= so->so_snd.sb_hiwat &&
16094 		    sbused(&so->so_snd) >=
16095 		    (so->so_snd.sb_hiwat / 8 * 7) &&
16096 		    sbused(&so->so_snd) < V_tcp_autosndbuf_max &&
16097 		    sendwin >= (sbused(&so->so_snd) -
16098 		    (tp->snd_nxt - tp->snd_una))) {
16099 			if (rack_autosndbuf_inc)
16100 				scaleup = (rack_autosndbuf_inc * so->so_snd.sb_hiwat) / 100;
16101 			else
16102 				scaleup = V_tcp_autosndbuf_inc;
16103 			if (scaleup < V_tcp_autosndbuf_inc)
16104 				scaleup = V_tcp_autosndbuf_inc;
16105 			scaleup += so->so_snd.sb_hiwat;
16106 			if (scaleup > V_tcp_autosndbuf_max)
16107 				scaleup = V_tcp_autosndbuf_max;
16108 			if (!sbreserve_locked(&so->so_snd, scaleup, so, curthread))
16109 				so->so_snd.sb_flags &= ~SB_AUTOSIZE;
16110 		}
16111 	}
16112 }
16113 
16114 static int
16115 rack_fast_output(struct tcpcb *tp, struct tcp_rack *rack, uint64_t ts_val,
16116 		 uint32_t cts, uint32_t ms_cts, struct timeval *tv, long tot_len, int *send_err)
16117 {
16118 	/*
16119 	 * Enter to do fast output. We are given that the sched_pin is
16120 	 * in place (if accounting is compiled in) and the cycle count taken
16121 	 * at entry is in place in ts_val. The idea here is that
16122 	 * we know how many more bytes needs to be sent (presumably either
16123 	 * during pacing or to fill the cwnd and that was greater than
16124 	 * the max-burst). We have how much to send and all the info we
16125 	 * need to just send.
16126 	 */
16127 	struct ip *ip = NULL;
16128 	struct udphdr *udp = NULL;
16129 	struct tcphdr *th = NULL;
16130 	struct mbuf *m, *s_mb;
16131 	struct inpcb *inp;
16132 	uint8_t *cpto;
16133 	struct tcp_log_buffer *lgb;
16134 #ifdef TCP_ACCOUNTING
16135 	uint64_t crtsc;
16136 #endif
16137 	struct tcpopt to;
16138 	u_char opt[TCP_MAXOLEN];
16139 	uint32_t hdrlen, optlen;
16140 	int cnt_thru = 1;
16141 	int32_t slot, segsiz, len, max_val, tso = 0, sb_offset, error, flags, ulen = 0;
16142 	uint32_t us_cts, s_soff;
16143 	uint32_t if_hw_tsomaxsegcount = 0, startseq;
16144 	uint32_t if_hw_tsomaxsegsize;
16145 	uint16_t add_flag = RACK_SENT_FP;
16146 #ifdef INET6
16147 	struct ip6_hdr *ip6 = NULL;
16148 
16149 	if (rack->r_is_v6) {
16150 		ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
16151 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
16152 	} else
16153 #endif				/* INET6 */
16154 	{
16155 		ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
16156 		hdrlen = sizeof(struct tcpiphdr);
16157 	}
16158 	if (tp->t_port && (V_tcp_udp_tunneling_port == 0)) {
16159 		m = NULL;
16160 		goto failed;
16161 	}
16162 	startseq = tp->snd_max;
16163 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
16164 	inp = rack->rc_inp;
16165 	len = rack->r_ctl.fsb.left_to_send;
16166 	to.to_flags = 0;
16167 	flags = rack->r_ctl.fsb.tcp_flags;
16168 	if (tp->t_flags & TF_RCVD_TSTMP) {
16169 		to.to_tsval = ms_cts + tp->ts_offset;
16170 		to.to_tsecr = tp->ts_recent;
16171 		to.to_flags = TOF_TS;
16172 	}
16173 	optlen = tcp_addoptions(&to, opt);
16174 	hdrlen += optlen;
16175 	udp = rack->r_ctl.fsb.udp;
16176 	if (udp)
16177 		hdrlen += sizeof(struct udphdr);
16178 	if (rack->r_ctl.rc_pace_max_segs)
16179 		max_val = rack->r_ctl.rc_pace_max_segs;
16180 	else if (rack->rc_user_set_max_segs)
16181 		max_val = rack->rc_user_set_max_segs * segsiz;
16182 	else
16183 		max_val = len;
16184 	if ((tp->t_flags & TF_TSO) &&
16185 	    V_tcp_do_tso &&
16186 	    (len > segsiz) &&
16187 	    (tp->t_port == 0))
16188 		tso = 1;
16189 again:
16190 #ifdef INET6
16191 	if (MHLEN < hdrlen + max_linkhdr)
16192 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
16193 	else
16194 #endif
16195 		m = m_gethdr(M_NOWAIT, MT_DATA);
16196 	if (m == NULL)
16197 		goto failed;
16198 	m->m_data += max_linkhdr;
16199 	m->m_len = hdrlen;
16200 	th = rack->r_ctl.fsb.th;
16201 	/* Establish the len to send */
16202 	if (len > max_val)
16203 		len = max_val;
16204 	if ((tso) && (len + optlen > tp->t_maxseg)) {
16205 		uint32_t if_hw_tsomax;
16206 		int32_t max_len;
16207 
16208 		/* extract TSO information */
16209 		if_hw_tsomax = tp->t_tsomax;
16210 		if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
16211 		if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
16212 		/*
16213 		 * Check if we should limit by maximum payload
16214 		 * length:
16215 		 */
16216 		if (if_hw_tsomax != 0) {
16217 			/* compute maximum TSO length */
16218 			max_len = (if_hw_tsomax - hdrlen -
16219 				   max_linkhdr);
16220 			if (max_len <= 0) {
16221 				goto failed;
16222 			} else if (len > max_len) {
16223 				len = max_len;
16224 			}
16225 		}
16226 		if (len <= segsiz) {
16227 			/*
16228 			 * In case there are too many small fragments don't
16229 			 * use TSO:
16230 			 */
16231 			tso = 0;
16232 		}
16233 	} else {
16234 		tso = 0;
16235 	}
16236 	if ((tso == 0) && (len > segsiz))
16237 		len = segsiz;
16238 	us_cts = tcp_get_usecs(tv);
16239 	if ((len == 0) ||
16240 	    (len <= MHLEN - hdrlen - max_linkhdr)) {
16241 		goto failed;
16242 	}
16243 	sb_offset = tp->snd_max - tp->snd_una;
16244 	th->th_seq = htonl(tp->snd_max);
16245 	th->th_ack = htonl(tp->rcv_nxt);
16246 	th->th_flags = flags;
16247 	th->th_win = htons((u_short)(rack->r_ctl.fsb.recwin >> tp->rcv_scale));
16248 	if (th->th_win == 0) {
16249 		tp->t_sndzerowin++;
16250 		tp->t_flags |= TF_RXWIN0SENT;
16251 	} else
16252 		tp->t_flags &= ~TF_RXWIN0SENT;
16253 	tp->snd_up = tp->snd_una;	/* drag it along, its deprecated */
16254 	KMOD_TCPSTAT_INC(tcps_sndpack);
16255 	KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
16256 #ifdef STATS
16257 	stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
16258 				 len);
16259 #endif
16260 	if (rack->r_ctl.fsb.m == NULL)
16261 		goto failed;
16262 
16263 	/* s_mb and s_soff are saved for rack_log_output */
16264 	m->m_next = rack_fo_m_copym(rack, &len, if_hw_tsomaxsegcount, if_hw_tsomaxsegsize,
16265 				    &s_mb, &s_soff);
16266 	if (len <= segsiz) {
16267 		/*
16268 		 * Must have ran out of mbufs for the copy
16269 		 * shorten it to no longer need tso. Lets
16270 		 * not put on sendalot since we are low on
16271 		 * mbufs.
16272 		 */
16273 		tso = 0;
16274 	}
16275 	if (rack->r_ctl.fsb.rfo_apply_push &&
16276 	    (len == rack->r_ctl.fsb.left_to_send)) {
16277 		th->th_flags |= TH_PUSH;
16278 		add_flag |= RACK_HAD_PUSH;
16279 	}
16280 	if ((m->m_next == NULL) || (len <= 0)){
16281 		goto failed;
16282 	}
16283 	if (udp) {
16284 		if (rack->r_is_v6)
16285 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
16286 		else
16287 			ulen = hdrlen + len - sizeof(struct ip);
16288 		udp->uh_ulen = htons(ulen);
16289 	}
16290 	m->m_pkthdr.rcvif = (struct ifnet *)0;
16291 	if (tp->t_state == TCPS_ESTABLISHED &&
16292 	    (tp->t_flags2 & TF2_ECN_PERMIT)) {
16293 		/*
16294 		 * If the peer has ECN, mark data packets with ECN capable
16295 		 * transmission (ECT). Ignore pure ack packets,
16296 		 * retransmissions.
16297 		 */
16298 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
16299 #ifdef INET6
16300 			if (rack->r_is_v6)
16301 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
16302 			else
16303 #endif
16304 				ip->ip_tos |= IPTOS_ECN_ECT0;
16305 			KMOD_TCPSTAT_INC(tcps_ecn_ect0);
16306 			/*
16307 			 * Reply with proper ECN notifications.
16308 			 * Only set CWR on new data segments.
16309 			 */
16310 			if (tp->t_flags2 & TF2_ECN_SND_CWR) {
16311 				flags |= TH_CWR;
16312 				tp->t_flags2 &= ~TF2_ECN_SND_CWR;
16313 			}
16314 		}
16315 		if (tp->t_flags2 & TF2_ECN_SND_ECE)
16316 			flags |= TH_ECE;
16317 	}
16318 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
16319 #ifdef INET6
16320 	if (rack->r_is_v6) {
16321 		if (tp->t_port) {
16322 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
16323 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
16324 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
16325 			th->th_sum = htons(0);
16326 			UDPSTAT_INC(udps_opackets);
16327 		} else {
16328 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
16329 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
16330 			th->th_sum = in6_cksum_pseudo(ip6,
16331 						      sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
16332 						      0);
16333 		}
16334 	}
16335 #endif
16336 #if defined(INET6) && defined(INET)
16337 	else
16338 #endif
16339 #ifdef INET
16340 	{
16341 		if (tp->t_port) {
16342 			m->m_pkthdr.csum_flags = CSUM_UDP;
16343 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
16344 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
16345 						ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
16346 			th->th_sum = htons(0);
16347 			UDPSTAT_INC(udps_opackets);
16348 		} else {
16349 			m->m_pkthdr.csum_flags = CSUM_TCP;
16350 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
16351 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
16352 					       ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
16353 									IPPROTO_TCP + len + optlen));
16354 		}
16355 		/* IP version must be set here for ipv4/ipv6 checking later */
16356 		KASSERT(ip->ip_v == IPVERSION,
16357 			("%s: IP version incorrect: %d", __func__, ip->ip_v));
16358 	}
16359 #endif
16360 	if (tso) {
16361 		KASSERT(len > tp->t_maxseg - optlen,
16362 			("%s: len <= tso_segsz tp:%p", __func__, tp));
16363 		m->m_pkthdr.csum_flags |= CSUM_TSO;
16364 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
16365 	}
16366 #ifdef INET6
16367 	if (rack->r_is_v6) {
16368 		ip6->ip6_hlim = rack->r_ctl.fsb.hoplimit;
16369 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
16370 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
16371 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
16372 		else
16373 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
16374 	}
16375 #endif
16376 #if defined(INET) && defined(INET6)
16377 	else
16378 #endif
16379 #ifdef INET
16380 	{
16381 		ip->ip_len = htons(m->m_pkthdr.len);
16382 		ip->ip_ttl = rack->r_ctl.fsb.hoplimit;
16383 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
16384 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
16385 			if (tp->t_port == 0 || len < V_tcp_minmss) {
16386 				ip->ip_off |= htons(IP_DF);
16387 			}
16388 		} else {
16389 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
16390 		}
16391 	}
16392 #endif
16393 	/* Time to copy in our header */
16394 	cpto = mtod(m, uint8_t *);
16395 	memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
16396 	th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
16397 	if (optlen) {
16398 		bcopy(opt, th + 1, optlen);
16399 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
16400 	} else {
16401 		th->th_off = sizeof(struct tcphdr) >> 2;
16402 	}
16403 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
16404 		union tcp_log_stackspecific log;
16405 
16406 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
16407 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
16408 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
16409 		if (rack->rack_no_prr)
16410 			log.u_bbr.flex1 = 0;
16411 		else
16412 			log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
16413 		log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
16414 		log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
16415 		log.u_bbr.flex4 = max_val;
16416 		log.u_bbr.flex5 = 0;
16417 		/* Save off the early/late values */
16418 		log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
16419 		log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
16420 		log.u_bbr.bw_inuse = rack_get_bw(rack);
16421 		log.u_bbr.flex8 = 0;
16422 		log.u_bbr.pacing_gain = rack_get_output_gain(rack, NULL);
16423 		log.u_bbr.flex7 = 44;
16424 		log.u_bbr.pkts_out = tp->t_maxseg;
16425 		log.u_bbr.timeStamp = cts;
16426 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
16427 		log.u_bbr.lt_epoch = rack->r_ctl.cwnd_to_use;
16428 		log.u_bbr.delivered = 0;
16429 		lgb = tcp_log_event_(tp, th, NULL, NULL, TCP_LOG_OUT, ERRNO_UNK,
16430 				     len, &log, false, NULL, NULL, 0, tv);
16431 	} else
16432 		lgb = NULL;
16433 #ifdef INET6
16434 	if (rack->r_is_v6) {
16435 		error = ip6_output(m, NULL,
16436 				   &inp->inp_route6,
16437 				   0, NULL, NULL, inp);
16438 	}
16439 #endif
16440 #if defined(INET) && defined(INET6)
16441 	else
16442 #endif
16443 #ifdef INET
16444 	{
16445 		error = ip_output(m, NULL,
16446 				  &inp->inp_route,
16447 				  0, 0, inp);
16448 	}
16449 #endif
16450 	if (lgb) {
16451 		lgb->tlb_errno = error;
16452 		lgb = NULL;
16453 	}
16454 	if (error) {
16455 		*send_err = error;
16456 		m = NULL;
16457 		goto failed;
16458 	}
16459 	rack_log_output(tp, &to, len, tp->snd_max, flags, error, rack_to_usec_ts(tv),
16460 			NULL, add_flag, s_mb, s_soff, rack->r_ctl.fsb.hw_tls);
16461 	m = NULL;
16462 	if (tp->snd_una == tp->snd_max) {
16463 		rack->r_ctl.rc_tlp_rxt_last_time = cts;
16464 		rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
16465 		tp->t_acktime = ticks;
16466 	}
16467 	if (error == 0)
16468 		tcp_account_for_send(tp, len, 0, 0, rack->r_ctl.fsb.hw_tls);
16469 
16470 	rack->forced_ack = 0;	/* If we send something zap the FA flag */
16471 	tot_len += len;
16472 	if ((tp->t_flags & TF_GPUTINPROG) == 0)
16473 		rack_start_gp_measurement(tp, rack, tp->snd_max, sb_offset);
16474 	tp->snd_max += len;
16475 	tp->snd_nxt = tp->snd_max;
16476 	{
16477 		int idx;
16478 
16479 		idx = (len / segsiz) + 3;
16480 		if (idx >= TCP_MSS_ACCT_ATIMER)
16481 			counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
16482 		else
16483 			counter_u64_add(rack_out_size[idx], 1);
16484 	}
16485 	if (len <= rack->r_ctl.fsb.left_to_send)
16486 		rack->r_ctl.fsb.left_to_send -= len;
16487 	else
16488 		rack->r_ctl.fsb.left_to_send = 0;
16489 	if (rack->r_ctl.fsb.left_to_send < segsiz) {
16490 		rack->r_fast_output = 0;
16491 		rack->r_ctl.fsb.left_to_send = 0;
16492 		/* At the end of fast_output scale up the sb */
16493 		SOCKBUF_LOCK(&rack->rc_inp->inp_socket->so_snd);
16494 		rack_sndbuf_autoscale(rack);
16495 		SOCKBUF_UNLOCK(&rack->rc_inp->inp_socket->so_snd);
16496 	}
16497 	if (tp->t_rtttime == 0) {
16498 		tp->t_rtttime = ticks;
16499 		tp->t_rtseq = startseq;
16500 		KMOD_TCPSTAT_INC(tcps_segstimed);
16501 	}
16502 	if ((rack->r_ctl.fsb.left_to_send >= segsiz) &&
16503 	    (max_val > len) &&
16504 	    (tso == 0)) {
16505 		max_val -= len;
16506 		len = segsiz;
16507 		th = rack->r_ctl.fsb.th;
16508 		cnt_thru++;
16509 		goto again;
16510 	}
16511 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
16512 	counter_u64_add(rack_fto_send, 1);
16513 	slot = rack_get_pacing_delay(rack, tp, tot_len, NULL, segsiz);
16514 	rack_start_hpts_timer(rack, tp, cts, slot, tot_len, 0);
16515 #ifdef TCP_ACCOUNTING
16516 	crtsc = get_cyclecount();
16517 	if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16518 		tp->tcp_cnt_counters[SND_OUT_DATA] += cnt_thru;
16519 	}
16520 	counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], cnt_thru);
16521 	if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16522 		tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
16523 	}
16524 	counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
16525 	if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16526 		tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len + segsiz - 1) / segsiz);
16527 	}
16528 	counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len + segsiz - 1) / segsiz));
16529 	sched_unpin();
16530 #endif
16531 	return (0);
16532 failed:
16533 	if (m)
16534 		m_free(m);
16535 	rack->r_fast_output = 0;
16536 	return (-1);
16537 }
16538 
16539 static int
16540 rack_output(struct tcpcb *tp)
16541 {
16542 	struct socket *so;
16543 	uint32_t recwin;
16544 	uint32_t sb_offset, s_moff = 0;
16545 	int32_t len, flags, error = 0;
16546 	struct mbuf *m, *s_mb = NULL;
16547 	struct mbuf *mb;
16548 	uint32_t if_hw_tsomaxsegcount = 0;
16549 	uint32_t if_hw_tsomaxsegsize;
16550 	int32_t segsiz, minseg;
16551 	long tot_len_this_send = 0;
16552 #ifdef INET
16553 	struct ip *ip = NULL;
16554 #endif
16555 #ifdef TCPDEBUG
16556 	struct ipovly *ipov = NULL;
16557 #endif
16558 	struct udphdr *udp = NULL;
16559 	struct tcp_rack *rack;
16560 	struct tcphdr *th;
16561 	uint8_t pass = 0;
16562 	uint8_t mark = 0;
16563 	uint8_t wanted_cookie = 0;
16564 	u_char opt[TCP_MAXOLEN];
16565 	unsigned ipoptlen, optlen, hdrlen, ulen=0;
16566 	uint32_t rack_seq;
16567 
16568 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
16569 	unsigned ipsec_optlen = 0;
16570 
16571 #endif
16572 	int32_t idle, sendalot;
16573 	int32_t sub_from_prr = 0;
16574 	volatile int32_t sack_rxmit;
16575 	struct rack_sendmap *rsm = NULL;
16576 	int32_t tso, mtu;
16577 	struct tcpopt to;
16578 	int32_t slot = 0;
16579 	int32_t sup_rack = 0;
16580 	uint32_t cts, ms_cts, delayed, early;
16581 	uint16_t add_flag = RACK_SENT_SP;
16582 	/* The doing_tlp flag will be set by the actual rack_timeout_tlp() */
16583 	uint8_t hpts_calling,  doing_tlp = 0;
16584 	uint32_t cwnd_to_use, pace_max_seg;
16585 	int32_t do_a_prefetch = 0;
16586 	int32_t prefetch_rsm = 0;
16587 	int32_t orig_len = 0;
16588 	struct timeval tv;
16589 	int32_t prefetch_so_done = 0;
16590 	struct tcp_log_buffer *lgb;
16591 	struct inpcb *inp;
16592 	struct sockbuf *sb;
16593 	uint64_t ts_val = 0;
16594 #ifdef TCP_ACCOUNTING
16595 	uint64_t crtsc;
16596 #endif
16597 #ifdef INET6
16598 	struct ip6_hdr *ip6 = NULL;
16599 	int32_t isipv6;
16600 #endif
16601 	uint8_t filled_all = 0;
16602 	bool hw_tls = false;
16603 
16604 	/* setup and take the cache hits here */
16605 	rack = (struct tcp_rack *)tp->t_fb_ptr;
16606 #ifdef TCP_ACCOUNTING
16607 	sched_pin();
16608 	ts_val = get_cyclecount();
16609 #endif
16610 	hpts_calling = rack->rc_inp->inp_hpts_calls;
16611 	NET_EPOCH_ASSERT();
16612 	INP_WLOCK_ASSERT(rack->rc_inp);
16613 #ifdef TCP_OFFLOAD
16614 	if (tp->t_flags & TF_TOE) {
16615 #ifdef TCP_ACCOUNTING
16616 		sched_unpin();
16617 #endif
16618 		return (tcp_offload_output(tp));
16619 	}
16620 #endif
16621 	/*
16622 	 * For TFO connections in SYN_RECEIVED, only allow the initial
16623 	 * SYN|ACK and those sent by the retransmit timer.
16624 	 */
16625 	if (IS_FASTOPEN(tp->t_flags) &&
16626 	    (tp->t_state == TCPS_SYN_RECEIVED) &&
16627 	    SEQ_GT(tp->snd_max, tp->snd_una) &&    /* initial SYN|ACK sent */
16628 	    (rack->r_ctl.rc_resend == NULL)) {         /* not a retransmit */
16629 #ifdef TCP_ACCOUNTING
16630 		sched_unpin();
16631 #endif
16632 		return (0);
16633 	}
16634 #ifdef INET6
16635 	if (rack->r_state) {
16636 		/* Use the cache line loaded if possible */
16637 		isipv6 = rack->r_is_v6;
16638 	} else {
16639 		isipv6 = (rack->rc_inp->inp_vflag & INP_IPV6) != 0;
16640 	}
16641 #endif
16642 	early = 0;
16643 	cts = tcp_get_usecs(&tv);
16644 	ms_cts = tcp_tv_to_mssectick(&tv);
16645 	if (((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
16646 	    rack->rc_inp->inp_in_hpts) {
16647 		/*
16648 		 * We are on the hpts for some timer but not hptsi output.
16649 		 * Remove from the hpts unconditionally.
16650 		 */
16651 		rack_timer_cancel(tp, rack, cts, __LINE__);
16652 	}
16653 	/* Are we pacing and late? */
16654 	if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
16655 	    TSTMP_GEQ(cts, rack->r_ctl.rc_last_output_to)) {
16656 		/* We are delayed */
16657 		delayed = cts - rack->r_ctl.rc_last_output_to;
16658 	} else {
16659 		delayed = 0;
16660 	}
16661 	/* Do the timers, which may override the pacer */
16662 	if (rack->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
16663 		if (rack_process_timers(tp, rack, cts, hpts_calling, &doing_tlp)) {
16664 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_ATIMER], 1);
16665 #ifdef TCP_ACCOUNTING
16666 			sched_unpin();
16667 #endif
16668 			return (0);
16669 		}
16670 	}
16671 	if (rack->rc_in_persist) {
16672 		if (rack->rc_inp->inp_in_hpts == 0) {
16673 			/* Timer is not running */
16674 			rack_start_hpts_timer(rack, tp, cts, 0, 0, 0);
16675 		}
16676 #ifdef TCP_ACCOUNTING
16677 		sched_unpin();
16678 #endif
16679 		return (0);
16680 	}
16681 	if ((rack->r_timer_override) ||
16682 	    (rack->rc_ack_can_sendout_data) ||
16683 	    (delayed) ||
16684 	    (tp->t_state < TCPS_ESTABLISHED)) {
16685 		rack->rc_ack_can_sendout_data = 0;
16686 		if (rack->rc_inp->inp_in_hpts)
16687 			tcp_hpts_remove(rack->rc_inp, HPTS_REMOVE_OUTPUT);
16688 	} else if (rack->rc_inp->inp_in_hpts) {
16689 		/*
16690 		 * On the hpts you can't pass even if ACKNOW is on, we will
16691 		 * when the hpts fires.
16692 		 */
16693 #ifdef TCP_ACCOUNTING
16694 		crtsc = get_cyclecount();
16695 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16696 			tp->tcp_proc_time[SND_BLOCKED] += (crtsc - ts_val);
16697 		}
16698 		counter_u64_add(tcp_proc_time[SND_BLOCKED], (crtsc - ts_val));
16699 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
16700 			tp->tcp_cnt_counters[SND_BLOCKED]++;
16701 		}
16702 		counter_u64_add(tcp_cnt_counters[SND_BLOCKED], 1);
16703 		sched_unpin();
16704 #endif
16705 		counter_u64_add(rack_out_size[TCP_MSS_ACCT_INPACE], 1);
16706 		return (0);
16707 	}
16708 	rack->rc_inp->inp_hpts_calls = 0;
16709 	/* Finish out both pacing early and late accounting */
16710 	if ((rack->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
16711 	    TSTMP_GT(rack->r_ctl.rc_last_output_to, cts)) {
16712 		early = rack->r_ctl.rc_last_output_to - cts;
16713 	} else
16714 		early = 0;
16715 	if (delayed) {
16716 		rack->r_ctl.rc_agg_delayed += delayed;
16717 		rack->r_late = 1;
16718 	} else if (early) {
16719 		rack->r_ctl.rc_agg_early += early;
16720 		rack->r_early = 1;
16721 	}
16722 	/* Now that early/late accounting is done turn off the flag */
16723 	rack->r_ctl.rc_hpts_flags &= ~PACE_PKT_OUTPUT;
16724 	rack->r_wanted_output = 0;
16725 	rack->r_timer_override = 0;
16726 	if ((tp->t_state != rack->r_state) &&
16727 	    TCPS_HAVEESTABLISHED(tp->t_state)) {
16728 		rack_set_state(tp, rack);
16729 	}
16730 	if ((rack->r_fast_output) &&
16731 	    (doing_tlp == 0) &&
16732 	    (tp->rcv_numsacks == 0)) {
16733 		int ret;
16734 
16735 		error = 0;
16736 		ret = rack_fast_output(tp, rack, ts_val, cts, ms_cts, &tv, tot_len_this_send, &error);
16737 		if (ret >= 0)
16738 			return(ret);
16739 		else if (error) {
16740 			inp = rack->rc_inp;
16741 			so = inp->inp_socket;
16742 			sb = &so->so_snd;
16743 			goto nomore;
16744 		}
16745 	}
16746 	inp = rack->rc_inp;
16747 	/*
16748 	 * For TFO connections in SYN_SENT or SYN_RECEIVED,
16749 	 * only allow the initial SYN or SYN|ACK and those sent
16750 	 * by the retransmit timer.
16751 	 */
16752 	if (IS_FASTOPEN(tp->t_flags) &&
16753 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
16754 	     (tp->t_state == TCPS_SYN_SENT)) &&
16755 	    SEQ_GT(tp->snd_max, tp->snd_una) && /* initial SYN or SYN|ACK sent */
16756 	    (tp->t_rxtshift == 0)) {              /* not a retransmit */
16757 		cwnd_to_use = rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
16758 		so = inp->inp_socket;
16759 		sb = &so->so_snd;
16760 		goto just_return_nolock;
16761 	}
16762 	/*
16763 	 * Determine length of data that should be transmitted, and flags
16764 	 * that will be used. If there is some data or critical controls
16765 	 * (SYN, RST) to send, then transmit; otherwise, investigate
16766 	 * further.
16767 	 */
16768 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
16769 	if (tp->t_idle_reduce) {
16770 		if (idle && ((ticks - tp->t_rcvtime) >= tp->t_rxtcur))
16771 			rack_cc_after_idle(rack, tp);
16772 	}
16773 	tp->t_flags &= ~TF_LASTIDLE;
16774 	if (idle) {
16775 		if (tp->t_flags & TF_MORETOCOME) {
16776 			tp->t_flags |= TF_LASTIDLE;
16777 			idle = 0;
16778 		}
16779 	}
16780 	if ((tp->snd_una == tp->snd_max) &&
16781 	    rack->r_ctl.rc_went_idle_time &&
16782 	    TSTMP_GT(cts, rack->r_ctl.rc_went_idle_time)) {
16783 		idle = cts - rack->r_ctl.rc_went_idle_time;
16784 		if (idle > rack_min_probertt_hold) {
16785 			/* Count as a probe rtt */
16786 			if (rack->in_probe_rtt == 0) {
16787 				rack->r_ctl.rc_lower_rtt_us_cts = cts;
16788 				rack->r_ctl.rc_time_probertt_entered = rack->r_ctl.rc_lower_rtt_us_cts;
16789 				rack->r_ctl.rc_time_probertt_starts = rack->r_ctl.rc_lower_rtt_us_cts;
16790 				rack->r_ctl.rc_time_of_last_probertt = rack->r_ctl.rc_lower_rtt_us_cts;
16791 			} else {
16792 				rack_exit_probertt(rack, cts);
16793 			}
16794 		}
16795 		idle = 0;
16796 	}
16797 	if (rack_use_fsb && (rack->r_fsb_inited == 0) && (rack->r_state != TCPS_CLOSED))
16798 		rack_init_fsb_block(tp, rack);
16799 again:
16800 	/*
16801 	 * If we've recently taken a timeout, snd_max will be greater than
16802 	 * snd_nxt.  There may be SACK information that allows us to avoid
16803 	 * resending already delivered data.  Adjust snd_nxt accordingly.
16804 	 */
16805 	sendalot = 0;
16806 	cts = tcp_get_usecs(&tv);
16807 	ms_cts = tcp_tv_to_mssectick(&tv);
16808 	tso = 0;
16809 	mtu = 0;
16810 	segsiz = min(ctf_fixed_maxseg(tp), rack->r_ctl.rc_pace_min_segs);
16811 	minseg = segsiz;
16812 	if (rack->r_ctl.rc_pace_max_segs == 0)
16813 		pace_max_seg = rack->rc_user_set_max_segs * segsiz;
16814 	else
16815 		pace_max_seg = rack->r_ctl.rc_pace_max_segs;
16816 	sb_offset = tp->snd_max - tp->snd_una;
16817 	cwnd_to_use = rack->r_ctl.cwnd_to_use = tp->snd_cwnd;
16818 	flags = tcp_outflags[tp->t_state];
16819 	while (rack->rc_free_cnt < rack_free_cache) {
16820 		rsm = rack_alloc(rack);
16821 		if (rsm == NULL) {
16822 			if (inp->inp_hpts_calls)
16823 				/* Retry in a ms */
16824 				slot = (1 * HPTS_USEC_IN_MSEC);
16825 			so = inp->inp_socket;
16826 			sb = &so->so_snd;
16827 			goto just_return_nolock;
16828 		}
16829 		TAILQ_INSERT_TAIL(&rack->r_ctl.rc_free, rsm, r_tnext);
16830 		rack->rc_free_cnt++;
16831 		rsm = NULL;
16832 	}
16833 	if (inp->inp_hpts_calls)
16834 		inp->inp_hpts_calls = 0;
16835 	sack_rxmit = 0;
16836 	len = 0;
16837 	rsm = NULL;
16838 	if (flags & TH_RST) {
16839 		SOCKBUF_LOCK(&inp->inp_socket->so_snd);
16840 		so = inp->inp_socket;
16841 		sb = &so->so_snd;
16842 		goto send;
16843 	}
16844 	if (rack->r_ctl.rc_resend) {
16845 		/* Retransmit timer */
16846 		rsm = rack->r_ctl.rc_resend;
16847 		rack->r_ctl.rc_resend = NULL;
16848 		len = rsm->r_end - rsm->r_start;
16849 		sack_rxmit = 1;
16850 		sendalot = 0;
16851 		KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
16852 			("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
16853 			 __func__, __LINE__,
16854 			 rsm->r_start, tp->snd_una, tp, rack, rsm));
16855 		sb_offset = rsm->r_start - tp->snd_una;
16856 		if (len >= segsiz)
16857 			len = segsiz;
16858 	} else if ((rsm = tcp_rack_output(tp, rack, cts)) != NULL) {
16859 		/* We have a retransmit that takes precedence */
16860 		if ((!IN_FASTRECOVERY(tp->t_flags)) &&
16861 		    ((tp->t_flags & TF_WASFRECOVERY) == 0)) {
16862 			/* Enter recovery if not induced by a time-out */
16863 			rack->r_ctl.rc_rsm_start = rsm->r_start;
16864 			rack->r_ctl.rc_cwnd_at = tp->snd_cwnd;
16865 			rack->r_ctl.rc_ssthresh_at = tp->snd_ssthresh;
16866 			rack_cong_signal(tp, CC_NDUPACK, tp->snd_una);
16867 		}
16868 #ifdef INVARIANTS
16869 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
16870 			panic("Huh, tp:%p rack:%p rsm:%p start:%u < snd_una:%u\n",
16871 			      tp, rack, rsm, rsm->r_start, tp->snd_una);
16872 		}
16873 #endif
16874 		len = rsm->r_end - rsm->r_start;
16875 		KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
16876 			("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
16877 			 __func__, __LINE__,
16878 			 rsm->r_start, tp->snd_una, tp, rack, rsm));
16879 		sb_offset = rsm->r_start - tp->snd_una;
16880 		sendalot = 0;
16881 		if (len >= segsiz)
16882 			len = segsiz;
16883 		if (len > 0) {
16884 			sack_rxmit = 1;
16885 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
16886 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
16887 			    min(len, segsiz));
16888 			counter_u64_add(rack_rtm_prr_retran, 1);
16889 		}
16890 	} else if (rack->r_ctl.rc_tlpsend) {
16891 		/* Tail loss probe */
16892 		long cwin;
16893 		long tlen;
16894 
16895 		/*
16896 		 * Check if we can do a TLP with a RACK'd packet
16897 		 * this can happen if we are not doing the rack
16898 		 * cheat and we skipped to a TLP and it
16899 		 * went off.
16900 		 */
16901 		rsm = rack->r_ctl.rc_tlpsend;
16902 		/* We are doing a TLP make sure the flag is preent */
16903 		rsm->r_flags |= RACK_TLP;
16904 		rack->r_ctl.rc_tlpsend = NULL;
16905 		sack_rxmit = 1;
16906 		tlen = rsm->r_end - rsm->r_start;
16907 		if (tlen > segsiz)
16908 			tlen = segsiz;
16909 		KASSERT(SEQ_LEQ(tp->snd_una, rsm->r_start),
16910 			("%s:%d: r.start:%u < SND.UNA:%u; tp:%p, rack:%p, rsm:%p",
16911 			 __func__, __LINE__,
16912 			 rsm->r_start, tp->snd_una, tp, rack, rsm));
16913 		sb_offset = rsm->r_start - tp->snd_una;
16914 		cwin = min(tp->snd_wnd, tlen);
16915 		len = cwin;
16916 	}
16917 	if (rack->r_must_retran &&
16918 	    (rsm == NULL)) {
16919 		/*
16920 		 * Non-Sack and we had a RTO or MTU change, we
16921 		 * need to retransmit until we reach
16922 		 * the former snd_max (rack->r_ctl.rc_snd_max_at_rto).
16923 		 */
16924 		if (SEQ_GT(tp->snd_max, tp->snd_una)) {
16925 			int sendwin, flight;
16926 
16927 			sendwin = min(tp->snd_wnd, tp->snd_cwnd);
16928 			flight = ctf_flight_size(tp, rack->r_ctl.rc_out_at_rto);
16929 			if (flight >= sendwin) {
16930 				so = inp->inp_socket;
16931 				sb = &so->so_snd;
16932 				goto just_return_nolock;
16933 			}
16934 			rsm = TAILQ_FIRST(&rack->r_ctl.rc_tmap);
16935 			KASSERT(rsm != NULL, ("rsm is NULL rack:%p r_must_retran set", rack));
16936 			if (rsm == NULL) {
16937 				/* TSNH */
16938 				rack->r_must_retran = 0;
16939 				rack->r_ctl.rc_out_at_rto = 0;
16940 				rack->r_must_retran = 0;
16941 				so = inp->inp_socket;
16942 				sb = &so->so_snd;
16943 				goto just_return_nolock;
16944 			}
16945 			sack_rxmit = 1;
16946 			len = rsm->r_end - rsm->r_start;
16947 			sendalot = 0;
16948 			sb_offset = rsm->r_start - tp->snd_una;
16949 			if (len >= segsiz)
16950 				len = segsiz;
16951 		} else {
16952 			/* We must be done if there is nothing outstanding */
16953 			rack->r_must_retran = 0;
16954 			rack->r_ctl.rc_out_at_rto = 0;
16955 		}
16956 	}
16957 	/*
16958 	 * Enforce a connection sendmap count limit if set
16959 	 * as long as we are not retransmiting.
16960 	 */
16961 	if ((rsm == NULL) &&
16962 	    (rack->do_detection == 0) &&
16963 	    (V_tcp_map_entries_limit > 0) &&
16964 	    (rack->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
16965 		counter_u64_add(rack_to_alloc_limited, 1);
16966 		if (!rack->alloc_limit_reported) {
16967 			rack->alloc_limit_reported = 1;
16968 			counter_u64_add(rack_alloc_limited_conns, 1);
16969 		}
16970 		so = inp->inp_socket;
16971 		sb = &so->so_snd;
16972 		goto just_return_nolock;
16973 	}
16974 	if (rsm && (rsm->r_flags & RACK_HAS_FIN)) {
16975 		/* we are retransmitting the fin */
16976 		len--;
16977 		if (len) {
16978 			/*
16979 			 * When retransmitting data do *not* include the
16980 			 * FIN. This could happen from a TLP probe.
16981 			 */
16982 			flags &= ~TH_FIN;
16983 		}
16984 	}
16985 #ifdef INVARIANTS
16986 	/* For debugging */
16987 	rack->r_ctl.rc_rsm_at_retran = rsm;
16988 #endif
16989 	if (rsm && rack->r_fsb_inited && rack_use_rsm_rfo &&
16990 	    ((rsm->r_flags & RACK_HAS_FIN) == 0)) {
16991 		int ret;
16992 
16993 		ret = rack_fast_rsm_output(tp, rack, rsm, ts_val, cts, ms_cts, &tv, len, doing_tlp);
16994 		if (ret == 0)
16995 			return (0);
16996 	}
16997 	so = inp->inp_socket;
16998 	sb = &so->so_snd;
16999 	if (do_a_prefetch == 0) {
17000 		kern_prefetch(sb, &do_a_prefetch);
17001 		do_a_prefetch = 1;
17002 	}
17003 #ifdef NETFLIX_SHARED_CWND
17004 	if ((tp->t_flags2 & TF2_TCP_SCWND_ALLOWED) &&
17005 	    rack->rack_enable_scwnd) {
17006 		/* We are doing cwnd sharing */
17007 		if (rack->gp_ready &&
17008 		    (rack->rack_attempted_scwnd == 0) &&
17009 		    (rack->r_ctl.rc_scw == NULL) &&
17010 		    tp->t_lib) {
17011 			/* The pcbid is in, lets make an attempt */
17012 			counter_u64_add(rack_try_scwnd, 1);
17013 			rack->rack_attempted_scwnd = 1;
17014 			rack->r_ctl.rc_scw = tcp_shared_cwnd_alloc(tp,
17015 								   &rack->r_ctl.rc_scw_index,
17016 								   segsiz);
17017 		}
17018 		if (rack->r_ctl.rc_scw &&
17019 		    (rack->rack_scwnd_is_idle == 1) &&
17020 		    sbavail(&so->so_snd)) {
17021 			/* we are no longer out of data */
17022 			tcp_shared_cwnd_active(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
17023 			rack->rack_scwnd_is_idle = 0;
17024 		}
17025 		if (rack->r_ctl.rc_scw) {
17026 			/* First lets update and get the cwnd */
17027 			rack->r_ctl.cwnd_to_use = cwnd_to_use = tcp_shared_cwnd_update(rack->r_ctl.rc_scw,
17028 								    rack->r_ctl.rc_scw_index,
17029 								    tp->snd_cwnd, tp->snd_wnd, segsiz);
17030 		}
17031 	}
17032 #endif
17033 	/*
17034 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
17035 	 * state flags.
17036 	 */
17037 	if (tp->t_flags & TF_NEEDFIN)
17038 		flags |= TH_FIN;
17039 	if (tp->t_flags & TF_NEEDSYN)
17040 		flags |= TH_SYN;
17041 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
17042 		void *end_rsm;
17043 		end_rsm = TAILQ_LAST_FAST(&rack->r_ctl.rc_tmap, rack_sendmap, r_tnext);
17044 		if (end_rsm)
17045 			kern_prefetch(end_rsm, &prefetch_rsm);
17046 		prefetch_rsm = 1;
17047 	}
17048 	SOCKBUF_LOCK(sb);
17049 	/*
17050 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
17051 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
17052 	 * negative length.  This can also occur when TCP opens up its
17053 	 * congestion window while receiving additional duplicate acks after
17054 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
17055 	 * the fast-retransmit.
17056 	 *
17057 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
17058 	 * set to snd_una, the sb_offset will be 0, and the length may wind
17059 	 * up 0.
17060 	 *
17061 	 * If sack_rxmit is true we are retransmitting from the scoreboard
17062 	 * in which case len is already set.
17063 	 */
17064 	if ((sack_rxmit == 0) &&
17065 	    (TCPS_HAVEESTABLISHED(tp->t_state) || IS_FASTOPEN(tp->t_flags))) {
17066 		uint32_t avail;
17067 
17068 		avail = sbavail(sb);
17069 		if (SEQ_GT(tp->snd_nxt, tp->snd_una) && avail)
17070 			sb_offset = tp->snd_nxt - tp->snd_una;
17071 		else
17072 			sb_offset = 0;
17073 		if ((IN_FASTRECOVERY(tp->t_flags) == 0) || rack->rack_no_prr) {
17074 			if (rack->r_ctl.rc_tlp_new_data) {
17075 				/* TLP is forcing out new data */
17076 				if (rack->r_ctl.rc_tlp_new_data > (uint32_t) (avail - sb_offset)) {
17077 					rack->r_ctl.rc_tlp_new_data = (uint32_t) (avail - sb_offset);
17078 				}
17079 				if ((rack->r_ctl.rc_tlp_new_data + sb_offset) > tp->snd_wnd) {
17080 					if (tp->snd_wnd > sb_offset)
17081 						len = tp->snd_wnd - sb_offset;
17082 					else
17083 						len = 0;
17084 				} else {
17085 					len = rack->r_ctl.rc_tlp_new_data;
17086 				}
17087 			}  else {
17088 				len = rack_what_can_we_send(tp, rack, cwnd_to_use, avail, sb_offset);
17089 			}
17090 			if ((rack->r_ctl.crte == NULL) && IN_FASTRECOVERY(tp->t_flags) && (len > segsiz)) {
17091 				/*
17092 				 * For prr=off, we need to send only 1 MSS
17093 				 * at a time. We do this because another sack could
17094 				 * be arriving that causes us to send retransmits and
17095 				 * we don't want to be on a long pace due to a larger send
17096 				 * that keeps us from sending out the retransmit.
17097 				 */
17098 				len = segsiz;
17099 			}
17100 		} else {
17101 			uint32_t outstanding;
17102 			/*
17103 			 * We are inside of a Fast recovery episode, this
17104 			 * is caused by a SACK or 3 dup acks. At this point
17105 			 * we have sent all the retransmissions and we rely
17106 			 * on PRR to dictate what we will send in the form of
17107 			 * new data.
17108 			 */
17109 
17110 			outstanding = tp->snd_max - tp->snd_una;
17111 			if ((rack->r_ctl.rc_prr_sndcnt + outstanding) > tp->snd_wnd) {
17112 				if (tp->snd_wnd > outstanding) {
17113 					len = tp->snd_wnd - outstanding;
17114 					/* Check to see if we have the data */
17115 					if ((sb_offset + len) > avail) {
17116 						/* It does not all fit */
17117 						if (avail > sb_offset)
17118 							len = avail - sb_offset;
17119 						else
17120 							len = 0;
17121 					}
17122 				} else {
17123 					len = 0;
17124 				}
17125 			} else if (avail > sb_offset) {
17126 				len = avail - sb_offset;
17127 			} else {
17128 				len = 0;
17129 			}
17130 			if (len > 0) {
17131 				if (len > rack->r_ctl.rc_prr_sndcnt) {
17132 					len = rack->r_ctl.rc_prr_sndcnt;
17133 				}
17134 				if (len > 0) {
17135 					sub_from_prr = 1;
17136 					counter_u64_add(rack_rtm_prr_newdata, 1);
17137 				}
17138 			}
17139 			if (len > segsiz) {
17140 				/*
17141 				 * We should never send more than a MSS when
17142 				 * retransmitting or sending new data in prr
17143 				 * mode unless the override flag is on. Most
17144 				 * likely the PRR algorithm is not going to
17145 				 * let us send a lot as well :-)
17146 				 */
17147 				if (rack->r_ctl.rc_prr_sendalot == 0) {
17148 					len = segsiz;
17149 				}
17150 			} else if (len < segsiz) {
17151 				/*
17152 				 * Do we send any? The idea here is if the
17153 				 * send empty's the socket buffer we want to
17154 				 * do it. However if not then lets just wait
17155 				 * for our prr_sndcnt to get bigger.
17156 				 */
17157 				long leftinsb;
17158 
17159 				leftinsb = sbavail(sb) - sb_offset;
17160 				if (leftinsb > len) {
17161 					/* This send does not empty the sb */
17162 					len = 0;
17163 				}
17164 			}
17165 		}
17166 	} else if (!TCPS_HAVEESTABLISHED(tp->t_state)) {
17167 		/*
17168 		 * If you have not established
17169 		 * and are not doing FAST OPEN
17170 		 * no data please.
17171 		 */
17172 		if ((sack_rxmit == 0) &&
17173 		    (!IS_FASTOPEN(tp->t_flags))){
17174 			len = 0;
17175 			sb_offset = 0;
17176 		}
17177 	}
17178 	if (prefetch_so_done == 0) {
17179 		kern_prefetch(so, &prefetch_so_done);
17180 		prefetch_so_done = 1;
17181 	}
17182 	/*
17183 	 * Lop off SYN bit if it has already been sent.  However, if this is
17184 	 * SYN-SENT state and if segment contains data and if we don't know
17185 	 * that foreign host supports TAO, suppress sending segment.
17186 	 */
17187 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una) &&
17188 	    ((sack_rxmit == 0) && (tp->t_rxtshift == 0))) {
17189 		/*
17190 		 * When sending additional segments following a TFO SYN|ACK,
17191 		 * do not include the SYN bit.
17192 		 */
17193 		if (IS_FASTOPEN(tp->t_flags) &&
17194 		    (tp->t_state == TCPS_SYN_RECEIVED))
17195 			flags &= ~TH_SYN;
17196 	}
17197 	/*
17198 	 * Be careful not to send data and/or FIN on SYN segments. This
17199 	 * measure is needed to prevent interoperability problems with not
17200 	 * fully conformant TCP implementations.
17201 	 */
17202 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
17203 		len = 0;
17204 		flags &= ~TH_FIN;
17205 	}
17206 	/*
17207 	 * On TFO sockets, ensure no data is sent in the following cases:
17208 	 *
17209 	 *  - When retransmitting SYN|ACK on a passively-created socket
17210 	 *
17211 	 *  - When retransmitting SYN on an actively created socket
17212 	 *
17213 	 *  - When sending a zero-length cookie (cookie request) on an
17214 	 *    actively created socket
17215 	 *
17216 	 *  - When the socket is in the CLOSED state (RST is being sent)
17217 	 */
17218 	if (IS_FASTOPEN(tp->t_flags) &&
17219 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
17220 	     ((tp->t_state == TCPS_SYN_SENT) &&
17221 	      (tp->t_tfo_client_cookie_len == 0)) ||
17222 	     (flags & TH_RST))) {
17223 		sack_rxmit = 0;
17224 		len = 0;
17225 	}
17226 	/* Without fast-open there should never be data sent on a SYN */
17227 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags))) {
17228 		tp->snd_nxt = tp->iss;
17229 		len = 0;
17230 	}
17231 	if ((len > segsiz) && (tcp_dsack_block_exists(tp))) {
17232 		/* We only send 1 MSS if we have a DSACK block */
17233 		add_flag |= RACK_SENT_W_DSACK;
17234 		len = segsiz;
17235 	}
17236 	orig_len = len;
17237 	if (len <= 0) {
17238 		/*
17239 		 * If FIN has been sent but not acked, but we haven't been
17240 		 * called to retransmit, len will be < 0.  Otherwise, window
17241 		 * shrank after we sent into it.  If window shrank to 0,
17242 		 * cancel pending retransmit, pull snd_nxt back to (closed)
17243 		 * window, and set the persist timer if it isn't already
17244 		 * going.  If the window didn't close completely, just wait
17245 		 * for an ACK.
17246 		 *
17247 		 * We also do a general check here to ensure that we will
17248 		 * set the persist timer when we have data to send, but a
17249 		 * 0-byte window. This makes sure the persist timer is set
17250 		 * even if the packet hits one of the "goto send" lines
17251 		 * below.
17252 		 */
17253 		len = 0;
17254 		if ((tp->snd_wnd == 0) &&
17255 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
17256 		    (tp->snd_una == tp->snd_max) &&
17257 		    (sb_offset < (int)sbavail(sb))) {
17258 			rack_enter_persist(tp, rack, cts);
17259 		}
17260 	} else if ((rsm == NULL) &&
17261 		   (doing_tlp == 0) &&
17262 		   (len < pace_max_seg)) {
17263 		/*
17264 		 * We are not sending a maximum sized segment for
17265 		 * some reason. Should we not send anything (think
17266 		 * sws or persists)?
17267 		 */
17268 		if ((tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), minseg)) &&
17269 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
17270 		    (len < minseg) &&
17271 		    (len < (int)(sbavail(sb) - sb_offset))) {
17272 			/*
17273 			 * Here the rwnd is less than
17274 			 * the minimum pacing size, this is not a retransmit,
17275 			 * we are established and
17276 			 * the send is not the last in the socket buffer
17277 			 * we send nothing, and we may enter persists
17278 			 * if nothing is outstanding.
17279 			 */
17280 			len = 0;
17281 			if (tp->snd_max == tp->snd_una) {
17282 				/*
17283 				 * Nothing out we can
17284 				 * go into persists.
17285 				 */
17286 				rack_enter_persist(tp, rack, cts);
17287 			}
17288 		     } else if ((cwnd_to_use >= max(minseg, (segsiz * 4))) &&
17289 			   (ctf_flight_size(tp, rack->r_ctl.rc_sacked) > (2 * segsiz)) &&
17290 			   (len < (int)(sbavail(sb) - sb_offset)) &&
17291 			   (len < minseg)) {
17292 			/*
17293 			 * Here we are not retransmitting, and
17294 			 * the cwnd is not so small that we could
17295 			 * not send at least a min size (rxt timer
17296 			 * not having gone off), We have 2 segments or
17297 			 * more already in flight, its not the tail end
17298 			 * of the socket buffer  and the cwnd is blocking
17299 			 * us from sending out a minimum pacing segment size.
17300 			 * Lets not send anything.
17301 			 */
17302 			len = 0;
17303 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
17304 			    min((rack->r_ctl.rc_high_rwnd/2), minseg)) &&
17305 			   (ctf_flight_size(tp, rack->r_ctl.rc_sacked) > (2 * segsiz)) &&
17306 			   (len < (int)(sbavail(sb) - sb_offset)) &&
17307 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
17308 			/*
17309 			 * Here we have a send window but we have
17310 			 * filled it up and we can't send another pacing segment.
17311 			 * We also have in flight more than 2 segments
17312 			 * and we are not completing the sb i.e. we allow
17313 			 * the last bytes of the sb to go out even if
17314 			 * its not a full pacing segment.
17315 			 */
17316 			len = 0;
17317 		} else if ((rack->r_ctl.crte != NULL) &&
17318 			   (tp->snd_wnd >= (pace_max_seg * max(1, rack_hw_rwnd_factor))) &&
17319 			   (cwnd_to_use >= (pace_max_seg + (4 * segsiz))) &&
17320 			   (ctf_flight_size(tp, rack->r_ctl.rc_sacked) >= (2 * segsiz)) &&
17321 			   (len < (int)(sbavail(sb) - sb_offset))) {
17322 			/*
17323 			 * Here we are doing hardware pacing, this is not a TLP,
17324 			 * we are not sending a pace max segment size, there is rwnd
17325 			 * room to send at least N pace_max_seg, the cwnd is greater
17326 			 * than or equal to a full pacing segments plus 4 mss and we have 2 or
17327 			 * more segments in flight and its not the tail of the socket buffer.
17328 			 *
17329 			 * We don't want to send instead we need to get more ack's in to
17330 			 * allow us to send a full pacing segment. Normally, if we are pacing
17331 			 * about the right speed, we should have finished our pacing
17332 			 * send as most of the acks have come back if we are at the
17333 			 * right rate. This is a bit fuzzy since return path delay
17334 			 * can delay the acks, which is why we want to make sure we
17335 			 * have cwnd space to have a bit more than a max pace segments in flight.
17336 			 *
17337 			 * If we have not gotten our acks back we are pacing at too high a
17338 			 * rate delaying will not hurt and will bring our GP estimate down by
17339 			 * injecting the delay. If we don't do this we will send
17340 			 * 2 MSS out in response to the acks being clocked in which
17341 			 * defeats the point of hw-pacing (i.e. to help us get
17342 			 * larger TSO's out).
17343 			 */
17344 			len = 0;
17345 
17346 		}
17347 
17348 	}
17349 	/* len will be >= 0 after this point. */
17350 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
17351 	rack_sndbuf_autoscale(rack);
17352 	/*
17353 	 * Decide if we can use TCP Segmentation Offloading (if supported by
17354 	 * hardware).
17355 	 *
17356 	 * TSO may only be used if we are in a pure bulk sending state.  The
17357 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
17358 	 * options prevent using TSO.  With TSO the TCP header is the same
17359 	 * (except for the sequence number) for all generated packets.  This
17360 	 * makes it impossible to transmit any options which vary per
17361 	 * generated segment or packet.
17362 	 *
17363 	 * IPv4 handling has a clear separation of ip options and ip header
17364 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen() does
17365 	 * the right thing below to provide length of just ip options and thus
17366 	 * checking for ipoptlen is enough to decide if ip options are present.
17367 	 */
17368 	ipoptlen = 0;
17369 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
17370 	/*
17371 	 * Pre-calculate here as we save another lookup into the darknesses
17372 	 * of IPsec that way and can actually decide if TSO is ok.
17373 	 */
17374 #ifdef INET6
17375 	if (isipv6 && IPSEC_ENABLED(ipv6))
17376 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, tp->t_inpcb);
17377 #ifdef INET
17378 	else
17379 #endif
17380 #endif				/* INET6 */
17381 #ifdef INET
17382 		if (IPSEC_ENABLED(ipv4))
17383 			ipsec_optlen = IPSEC_HDRSIZE(ipv4, tp->t_inpcb);
17384 #endif				/* INET */
17385 #endif
17386 
17387 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
17388 	ipoptlen += ipsec_optlen;
17389 #endif
17390 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso && len > segsiz &&
17391 	    (tp->t_port == 0) &&
17392 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
17393 	    tp->rcv_numsacks == 0 && sack_rxmit == 0 &&
17394 	    ipoptlen == 0)
17395 		tso = 1;
17396 	{
17397 		uint32_t outstanding;
17398 
17399 		outstanding = tp->snd_max - tp->snd_una;
17400 		if (tp->t_flags & TF_SENTFIN) {
17401 			/*
17402 			 * If we sent a fin, snd_max is 1 higher than
17403 			 * snd_una
17404 			 */
17405 			outstanding--;
17406 		}
17407 		if (sack_rxmit) {
17408 			if ((rsm->r_flags & RACK_HAS_FIN) == 0)
17409 				flags &= ~TH_FIN;
17410 		} else {
17411 			if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
17412 				   sbused(sb)))
17413 				flags &= ~TH_FIN;
17414 		}
17415 	}
17416 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
17417 	    (long)TCP_MAXWIN << tp->rcv_scale);
17418 
17419 	/*
17420 	 * Sender silly window avoidance.   We transmit under the following
17421 	 * conditions when len is non-zero:
17422 	 *
17423 	 * - We have a full segment (or more with TSO) - This is the last
17424 	 * buffer in a write()/send() and we are either idle or running
17425 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
17426 	 * then 1/2 the maximum send window's worth of data (receiver may be
17427 	 * limited the window size) - we need to retransmit
17428 	 */
17429 	if (len) {
17430 		if (len >= segsiz) {
17431 			goto send;
17432 		}
17433 		/*
17434 		 * NOTE! on localhost connections an 'ack' from the remote
17435 		 * end may occur synchronously with the output and cause us
17436 		 * to flush a buffer queued with moretocome.  XXX
17437 		 *
17438 		 */
17439 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
17440 		    (idle || (tp->t_flags & TF_NODELAY)) &&
17441 		    ((uint32_t)len + (uint32_t)sb_offset >= sbavail(sb)) &&
17442 		    (tp->t_flags & TF_NOPUSH) == 0) {
17443 			pass = 2;
17444 			goto send;
17445 		}
17446 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
17447 			pass = 22;
17448 			goto send;
17449 		}
17450 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
17451 			pass = 4;
17452 			goto send;
17453 		}
17454 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {	/* retransmit case */
17455 			pass = 5;
17456 			goto send;
17457 		}
17458 		if (sack_rxmit) {
17459 			pass = 6;
17460 			goto send;
17461 		}
17462 		if (((tp->snd_wnd - ctf_outstanding(tp)) < segsiz) &&
17463 		    (ctf_outstanding(tp) < (segsiz * 2))) {
17464 			/*
17465 			 * We have less than two MSS outstanding (delayed ack)
17466 			 * and our rwnd will not let us send a full sized
17467 			 * MSS. Lets go ahead and let this small segment
17468 			 * out because we want to try to have at least two
17469 			 * packets inflight to not be caught by delayed ack.
17470 			 */
17471 			pass = 12;
17472 			goto send;
17473 		}
17474 	}
17475 	/*
17476 	 * Sending of standalone window updates.
17477 	 *
17478 	 * Window updates are important when we close our window due to a
17479 	 * full socket buffer and are opening it again after the application
17480 	 * reads data from it.  Once the window has opened again and the
17481 	 * remote end starts to send again the ACK clock takes over and
17482 	 * provides the most current window information.
17483 	 *
17484 	 * We must avoid the silly window syndrome whereas every read from
17485 	 * the receive buffer, no matter how small, causes a window update
17486 	 * to be sent.  We also should avoid sending a flurry of window
17487 	 * updates when the socket buffer had queued a lot of data and the
17488 	 * application is doing small reads.
17489 	 *
17490 	 * Prevent a flurry of pointless window updates by only sending an
17491 	 * update when we can increase the advertized window by more than
17492 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
17493 	 * full or is very small be more aggressive and send an update
17494 	 * whenever we can increase by two mss sized segments. In all other
17495 	 * situations the ACK's to new incoming data will carry further
17496 	 * window increases.
17497 	 *
17498 	 * Don't send an independent window update if a delayed ACK is
17499 	 * pending (it will get piggy-backed on it) or the remote side
17500 	 * already has done a half-close and won't send more data.  Skip
17501 	 * this if the connection is in T/TCP half-open state.
17502 	 */
17503 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
17504 	    !(tp->t_flags & TF_DELACK) &&
17505 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
17506 		/*
17507 		 * "adv" is the amount we could increase the window, taking
17508 		 * into account that we are limited by TCP_MAXWIN <<
17509 		 * tp->rcv_scale.
17510 		 */
17511 		int32_t adv;
17512 		int oldwin;
17513 
17514 		adv = recwin;
17515 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
17516 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
17517 			if (adv > oldwin)
17518 			    adv -= oldwin;
17519 			else {
17520 				/* We can't increase the window */
17521 				adv = 0;
17522 			}
17523 		} else
17524 			oldwin = 0;
17525 
17526 		/*
17527 		 * If the new window size ends up being the same as or less
17528 		 * than the old size when it is scaled, then don't force
17529 		 * a window update.
17530 		 */
17531 		if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
17532 			goto dontupdate;
17533 
17534 		if (adv >= (int32_t)(2 * segsiz) &&
17535 		    (adv >= (int32_t)(so->so_rcv.sb_hiwat / 4) ||
17536 		     recwin <= (int32_t)(so->so_rcv.sb_hiwat / 8) ||
17537 		     so->so_rcv.sb_hiwat <= 8 * segsiz)) {
17538 			pass = 7;
17539 			goto send;
17540 		}
17541 		if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat) {
17542 			pass = 23;
17543 			goto send;
17544 		}
17545 	}
17546 dontupdate:
17547 
17548 	/*
17549 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
17550 	 * is also a catch-all for the retransmit timer timeout case.
17551 	 */
17552 	if (tp->t_flags & TF_ACKNOW) {
17553 		pass = 8;
17554 		goto send;
17555 	}
17556 	if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
17557 		pass = 9;
17558 		goto send;
17559 	}
17560 	/*
17561 	 * If our state indicates that FIN should be sent and we have not
17562 	 * yet done so, then we need to send.
17563 	 */
17564 	if ((flags & TH_FIN) &&
17565 	    (tp->snd_nxt == tp->snd_una)) {
17566 		pass = 11;
17567 		goto send;
17568 	}
17569 	/*
17570 	 * No reason to send a segment, just return.
17571 	 */
17572 just_return:
17573 	SOCKBUF_UNLOCK(sb);
17574 just_return_nolock:
17575 	{
17576 		int app_limited = CTF_JR_SENT_DATA;
17577 
17578 		if (tot_len_this_send > 0) {
17579 			/* Make sure snd_nxt is up to max */
17580 			rack->r_ctl.fsb.recwin = recwin;
17581 			slot = rack_get_pacing_delay(rack, tp, tot_len_this_send, NULL, segsiz);
17582 			if ((error == 0) &&
17583 			    rack_use_rfo &&
17584 			    ((flags & (TH_SYN|TH_FIN)) == 0) &&
17585 			    (ipoptlen == 0) &&
17586 			    (tp->snd_nxt == tp->snd_max) &&
17587 			    (tp->rcv_numsacks == 0) &&
17588 			    rack->r_fsb_inited &&
17589 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
17590 			    (rack->r_must_retran == 0) &&
17591 			    ((tp->t_flags & TF_NEEDFIN) == 0) &&
17592 			    (len > 0) && (orig_len > 0) &&
17593 			    (orig_len > len) &&
17594 			    ((orig_len - len) >= segsiz) &&
17595 			    ((optlen == 0) ||
17596 			     ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
17597 				/* We can send at least one more MSS using our fsb */
17598 
17599 				rack->r_fast_output = 1;
17600 				rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
17601 				rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
17602 				rack->r_ctl.fsb.tcp_flags = flags;
17603 				rack->r_ctl.fsb.left_to_send = orig_len - len;
17604 				if (hw_tls)
17605 					rack->r_ctl.fsb.hw_tls = 1;
17606 				else
17607 					rack->r_ctl.fsb.hw_tls = 0;
17608 				KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
17609 					("rack:%p left_to_send:%u sbavail:%u out:%u",
17610 					rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
17611 					 (tp->snd_max - tp->snd_una)));
17612 				if (rack->r_ctl.fsb.left_to_send < segsiz)
17613 					rack->r_fast_output = 0;
17614 				else {
17615 					if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
17616 						rack->r_ctl.fsb.rfo_apply_push = 1;
17617 					else
17618 						rack->r_ctl.fsb.rfo_apply_push = 0;
17619 				}
17620 			} else
17621 				rack->r_fast_output = 0;
17622 
17623 
17624 			rack_log_fsb(rack, tp, so, flags,
17625 				     ipoptlen, orig_len, len, 0,
17626 				     1, optlen, __LINE__, 1);
17627 			if (SEQ_GT(tp->snd_max, tp->snd_nxt))
17628 				tp->snd_nxt = tp->snd_max;
17629 		} else {
17630 			int end_window = 0;
17631 			uint32_t seq = tp->gput_ack;
17632 
17633 			rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
17634 			if (rsm) {
17635 				/*
17636 				 * Mark the last sent that we just-returned (hinting
17637 				 * that delayed ack may play a role in any rtt measurement).
17638 				 */
17639 				rsm->r_just_ret = 1;
17640 			}
17641 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_JUSTRET], 1);
17642 			rack->r_ctl.rc_agg_delayed = 0;
17643 			rack->r_early = 0;
17644 			rack->r_late = 0;
17645 			rack->r_ctl.rc_agg_early = 0;
17646 			if ((ctf_outstanding(tp) +
17647 			     min(max(segsiz, (rack->r_ctl.rc_high_rwnd/2)),
17648 				 minseg)) >= tp->snd_wnd) {
17649 				/* We are limited by the rwnd */
17650 				app_limited = CTF_JR_RWND_LIMITED;
17651 				if (IN_FASTRECOVERY(tp->t_flags))
17652 				    rack->r_ctl.rc_prr_sndcnt = 0;
17653 			} else if (ctf_outstanding(tp) >= sbavail(sb)) {
17654 				/* We are limited by whats available -- app limited */
17655 				app_limited = CTF_JR_APP_LIMITED;
17656 				if (IN_FASTRECOVERY(tp->t_flags))
17657 				    rack->r_ctl.rc_prr_sndcnt = 0;
17658 			} else if ((idle == 0) &&
17659 				   ((tp->t_flags & TF_NODELAY) == 0) &&
17660 				   ((uint32_t)len + (uint32_t)sb_offset >= sbavail(sb)) &&
17661 				   (len < segsiz)) {
17662 				/*
17663 				 * No delay is not on and the
17664 				 * user is sending less than 1MSS. This
17665 				 * brings out SWS avoidance so we
17666 				 * don't send. Another app-limited case.
17667 				 */
17668 				app_limited = CTF_JR_APP_LIMITED;
17669 			} else if (tp->t_flags & TF_NOPUSH) {
17670 				/*
17671 				 * The user has requested no push of
17672 				 * the last segment and we are
17673 				 * at the last segment. Another app
17674 				 * limited case.
17675 				 */
17676 				app_limited = CTF_JR_APP_LIMITED;
17677 			} else if ((ctf_outstanding(tp) + minseg) > cwnd_to_use) {
17678 				/* Its the cwnd */
17679 				app_limited = CTF_JR_CWND_LIMITED;
17680 			} else if (IN_FASTRECOVERY(tp->t_flags) &&
17681 				   (rack->rack_no_prr == 0) &&
17682 				   (rack->r_ctl.rc_prr_sndcnt < segsiz)) {
17683 				app_limited = CTF_JR_PRR;
17684 			} else {
17685 				/* Now why here are we not sending? */
17686 #ifdef NOW
17687 #ifdef INVARIANTS
17688 				panic("rack:%p hit JR_ASSESSING case cwnd_to_use:%u?", rack, cwnd_to_use);
17689 #endif
17690 #endif
17691 				app_limited = CTF_JR_ASSESSING;
17692 			}
17693 			/*
17694 			 * App limited in some fashion, for our pacing GP
17695 			 * measurements we don't want any gap (even cwnd).
17696 			 * Close  down the measurement window.
17697 			 */
17698 			if (rack_cwnd_block_ends_measure &&
17699 			    ((app_limited == CTF_JR_CWND_LIMITED) ||
17700 			     (app_limited == CTF_JR_PRR))) {
17701 				/*
17702 				 * The reason we are not sending is
17703 				 * the cwnd (or prr). We have been configured
17704 				 * to end the measurement window in
17705 				 * this case.
17706 				 */
17707 				end_window = 1;
17708 			} else if (rack_rwnd_block_ends_measure &&
17709 				   (app_limited == CTF_JR_RWND_LIMITED)) {
17710 				/*
17711 				 * We are rwnd limited and have been
17712 				 * configured to end the measurement
17713 				 * window in this case.
17714 				 */
17715 				end_window = 1;
17716 			} else if (app_limited == CTF_JR_APP_LIMITED) {
17717 				/*
17718 				 * A true application limited period, we have
17719 				 * ran out of data.
17720 				 */
17721 				end_window = 1;
17722 			} else if (app_limited == CTF_JR_ASSESSING) {
17723 				/*
17724 				 * In the assessing case we hit the end of
17725 				 * the if/else and had no known reason
17726 				 * This will panic us under invariants..
17727 				 *
17728 				 * If we get this out in logs we need to
17729 				 * investagate which reason we missed.
17730 				 */
17731 				end_window = 1;
17732 			}
17733 			if (end_window) {
17734 				uint8_t log = 0;
17735 
17736 				/* Adjust the Gput measurement */
17737 				if ((tp->t_flags & TF_GPUTINPROG) &&
17738 				    SEQ_GT(tp->gput_ack, tp->snd_max)) {
17739 					tp->gput_ack = tp->snd_max;
17740 					if ((tp->gput_ack - tp->gput_seq) < (MIN_GP_WIN * segsiz)) {
17741 						/*
17742 						 * There is not enough to measure.
17743 						 */
17744 						tp->t_flags &= ~TF_GPUTINPROG;
17745 						rack_log_pacing_delay_calc(rack, (tp->gput_ack - tp->gput_seq) /*flex2*/,
17746 									   rack->r_ctl.rc_gp_srtt /*flex1*/,
17747 									   tp->gput_seq,
17748 									   0, 0, 18, __LINE__, NULL, 0);
17749 					} else
17750 						log = 1;
17751 				}
17752 				/* Mark the last packet has app limited */
17753 				rsm = RB_MAX(rack_rb_tree_head, &rack->r_ctl.rc_mtree);
17754 				if (rsm && ((rsm->r_flags & RACK_APP_LIMITED) == 0)) {
17755 					if (rack->r_ctl.rc_app_limited_cnt == 0)
17756 						rack->r_ctl.rc_end_appl = rack->r_ctl.rc_first_appl = rsm;
17757 					else {
17758 						/*
17759 						 * Go out to the end app limited and mark
17760 						 * this new one as next and move the end_appl up
17761 						 * to this guy.
17762 						 */
17763 						if (rack->r_ctl.rc_end_appl)
17764 							rack->r_ctl.rc_end_appl->r_nseq_appl = rsm->r_start;
17765 						rack->r_ctl.rc_end_appl = rsm;
17766 					}
17767 					rsm->r_flags |= RACK_APP_LIMITED;
17768 					rack->r_ctl.rc_app_limited_cnt++;
17769 				}
17770 				if (log)
17771 					rack_log_pacing_delay_calc(rack,
17772 								   rack->r_ctl.rc_app_limited_cnt, seq,
17773 								   tp->gput_ack, 0, 0, 4, __LINE__, NULL, 0);
17774 			}
17775 		}
17776 		if (slot) {
17777 			/* set the rack tcb into the slot N */
17778 			counter_u64_add(rack_paced_segments, 1);
17779 		} else if (tot_len_this_send) {
17780 			counter_u64_add(rack_unpaced_segments, 1);
17781 		}
17782 		/* Check if we need to go into persists or not */
17783 		if ((tp->snd_max == tp->snd_una) &&
17784 		    TCPS_HAVEESTABLISHED(tp->t_state) &&
17785 		    sbavail(sb) &&
17786 		    (sbavail(sb) > tp->snd_wnd) &&
17787 		    (tp->snd_wnd < min((rack->r_ctl.rc_high_rwnd/2), minseg))) {
17788 			/* Yes lets make sure to move to persist before timer-start */
17789 			rack_enter_persist(tp, rack, rack->r_ctl.rc_rcvtime);
17790 		}
17791 		rack_start_hpts_timer(rack, tp, cts, slot, tot_len_this_send, sup_rack);
17792 		rack_log_type_just_return(rack, cts, tot_len_this_send, slot, hpts_calling, app_limited, cwnd_to_use);
17793 	}
17794 #ifdef NETFLIX_SHARED_CWND
17795 	if ((sbavail(sb) == 0) &&
17796 	    rack->r_ctl.rc_scw) {
17797 		tcp_shared_cwnd_idle(rack->r_ctl.rc_scw, rack->r_ctl.rc_scw_index);
17798 		rack->rack_scwnd_is_idle = 1;
17799 	}
17800 #endif
17801 #ifdef TCP_ACCOUNTING
17802 	if (tot_len_this_send > 0) {
17803 		crtsc = get_cyclecount();
17804 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17805 			tp->tcp_cnt_counters[SND_OUT_DATA]++;
17806 		}
17807 		counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], 1);
17808 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17809 			tp->tcp_proc_time[SND_OUT_DATA] += (crtsc - ts_val);
17810 		}
17811 		counter_u64_add(tcp_proc_time[SND_OUT_DATA], (crtsc - ts_val));
17812 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17813 			tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len_this_send + segsiz - 1) / segsiz);
17814 		}
17815 		counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len_this_send + segsiz - 1) / segsiz));
17816 	} else {
17817 		crtsc = get_cyclecount();
17818 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17819 			tp->tcp_cnt_counters[SND_LIMITED]++;
17820 		}
17821 		counter_u64_add(tcp_cnt_counters[SND_LIMITED], 1);
17822 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17823 			tp->tcp_proc_time[SND_LIMITED] += (crtsc - ts_val);
17824 		}
17825 		counter_u64_add(tcp_proc_time[SND_LIMITED], (crtsc - ts_val));
17826 	}
17827 	sched_unpin();
17828 #endif
17829 	return (0);
17830 
17831 send:
17832 	if (rsm || sack_rxmit)
17833 		counter_u64_add(rack_nfto_resend, 1);
17834 	else
17835 		counter_u64_add(rack_non_fto_send, 1);
17836 	if ((flags & TH_FIN) &&
17837 	    sbavail(sb)) {
17838 		/*
17839 		 * We do not transmit a FIN
17840 		 * with data outstanding. We
17841 		 * need to make it so all data
17842 		 * is acked first.
17843 		 */
17844 		flags &= ~TH_FIN;
17845 	}
17846 	/* Enforce stack imposed max seg size if we have one */
17847 	if (rack->r_ctl.rc_pace_max_segs &&
17848 	    (len > rack->r_ctl.rc_pace_max_segs)) {
17849 		mark = 1;
17850 		len = rack->r_ctl.rc_pace_max_segs;
17851 	}
17852 	SOCKBUF_LOCK_ASSERT(sb);
17853 	if (len > 0) {
17854 		if (len >= segsiz)
17855 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
17856 		else
17857 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
17858 	}
17859 	/*
17860 	 * Before ESTABLISHED, force sending of initial options unless TCP
17861 	 * set not to do any options. NOTE: we assume that the IP/TCP header
17862 	 * plus TCP options always fit in a single mbuf, leaving room for a
17863 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
17864 	 * + optlen <= MCLBYTES
17865 	 */
17866 	optlen = 0;
17867 #ifdef INET6
17868 	if (isipv6)
17869 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
17870 	else
17871 #endif
17872 		hdrlen = sizeof(struct tcpiphdr);
17873 
17874 	/*
17875 	 * Compute options for segment. We only have to care about SYN and
17876 	 * established connection segments.  Options for SYN-ACK segments
17877 	 * are handled in TCP syncache.
17878 	 */
17879 	to.to_flags = 0;
17880 	if ((tp->t_flags & TF_NOOPT) == 0) {
17881 		/* Maximum segment size. */
17882 		if (flags & TH_SYN) {
17883 			tp->snd_nxt = tp->iss;
17884 			to.to_mss = tcp_mssopt(&inp->inp_inc);
17885 			if (tp->t_port)
17886 				to.to_mss -= V_tcp_udp_tunneling_overhead;
17887 			to.to_flags |= TOF_MSS;
17888 
17889 			/*
17890 			 * On SYN or SYN|ACK transmits on TFO connections,
17891 			 * only include the TFO option if it is not a
17892 			 * retransmit, as the presence of the TFO option may
17893 			 * have caused the original SYN or SYN|ACK to have
17894 			 * been dropped by a middlebox.
17895 			 */
17896 			if (IS_FASTOPEN(tp->t_flags) &&
17897 			    (tp->t_rxtshift == 0)) {
17898 				if (tp->t_state == TCPS_SYN_RECEIVED) {
17899 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
17900 					to.to_tfo_cookie =
17901 						(u_int8_t *)&tp->t_tfo_cookie.server;
17902 					to.to_flags |= TOF_FASTOPEN;
17903 					wanted_cookie = 1;
17904 				} else if (tp->t_state == TCPS_SYN_SENT) {
17905 					to.to_tfo_len =
17906 						tp->t_tfo_client_cookie_len;
17907 					to.to_tfo_cookie =
17908 						tp->t_tfo_cookie.client;
17909 					to.to_flags |= TOF_FASTOPEN;
17910 					wanted_cookie = 1;
17911 					/*
17912 					 * If we wind up having more data to
17913 					 * send with the SYN than can fit in
17914 					 * one segment, don't send any more
17915 					 * until the SYN|ACK comes back from
17916 					 * the other end.
17917 					 */
17918 					sendalot = 0;
17919 				}
17920 			}
17921 		}
17922 		/* Window scaling. */
17923 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
17924 			to.to_wscale = tp->request_r_scale;
17925 			to.to_flags |= TOF_SCALE;
17926 		}
17927 		/* Timestamps. */
17928 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
17929 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
17930 			to.to_tsval = ms_cts + tp->ts_offset;
17931 			to.to_tsecr = tp->ts_recent;
17932 			to.to_flags |= TOF_TS;
17933 		}
17934 		/* Set receive buffer autosizing timestamp. */
17935 		if (tp->rfbuf_ts == 0 &&
17936 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
17937 			tp->rfbuf_ts = tcp_ts_getticks();
17938 		/* Selective ACK's. */
17939 		if (tp->t_flags & TF_SACK_PERMIT) {
17940 			if (flags & TH_SYN)
17941 				to.to_flags |= TOF_SACKPERM;
17942 			else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
17943 				 tp->rcv_numsacks > 0) {
17944 				to.to_flags |= TOF_SACK;
17945 				to.to_nsacks = tp->rcv_numsacks;
17946 				to.to_sacks = (u_char *)tp->sackblks;
17947 			}
17948 		}
17949 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
17950 		/* TCP-MD5 (RFC2385). */
17951 		if (tp->t_flags & TF_SIGNATURE)
17952 			to.to_flags |= TOF_SIGNATURE;
17953 #endif				/* TCP_SIGNATURE */
17954 
17955 		/* Processing the options. */
17956 		hdrlen += optlen = tcp_addoptions(&to, opt);
17957 		/*
17958 		 * If we wanted a TFO option to be added, but it was unable
17959 		 * to fit, ensure no data is sent.
17960 		 */
17961 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
17962 		    !(to.to_flags & TOF_FASTOPEN))
17963 			len = 0;
17964 	}
17965 	if (tp->t_port) {
17966 		if (V_tcp_udp_tunneling_port == 0) {
17967 			/* The port was removed?? */
17968 			SOCKBUF_UNLOCK(&so->so_snd);
17969 #ifdef TCP_ACCOUNTING
17970 			crtsc = get_cyclecount();
17971 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17972 				tp->tcp_cnt_counters[SND_OUT_FAIL]++;
17973 			}
17974 			counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
17975 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
17976 				tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
17977 			}
17978 			counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
17979 			sched_unpin();
17980 #endif
17981 			return (EHOSTUNREACH);
17982 		}
17983 		hdrlen += sizeof(struct udphdr);
17984 	}
17985 #ifdef INET6
17986 	if (isipv6)
17987 		ipoptlen = ip6_optlen(tp->t_inpcb);
17988 	else
17989 #endif
17990 		if (tp->t_inpcb->inp_options)
17991 			ipoptlen = tp->t_inpcb->inp_options->m_len -
17992 				offsetof(struct ipoption, ipopt_list);
17993 		else
17994 			ipoptlen = 0;
17995 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
17996 	ipoptlen += ipsec_optlen;
17997 #endif
17998 
17999 	/*
18000 	 * Adjust data length if insertion of options will bump the packet
18001 	 * length beyond the t_maxseg length. Clear the FIN bit because we
18002 	 * cut off the tail of the segment.
18003 	 */
18004 	if (len + optlen + ipoptlen > tp->t_maxseg) {
18005 		if (tso) {
18006 			uint32_t if_hw_tsomax;
18007 			uint32_t moff;
18008 			int32_t max_len;
18009 
18010 			/* extract TSO information */
18011 			if_hw_tsomax = tp->t_tsomax;
18012 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
18013 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
18014 			KASSERT(ipoptlen == 0,
18015 				("%s: TSO can't do IP options", __func__));
18016 
18017 			/*
18018 			 * Check if we should limit by maximum payload
18019 			 * length:
18020 			 */
18021 			if (if_hw_tsomax != 0) {
18022 				/* compute maximum TSO length */
18023 				max_len = (if_hw_tsomax - hdrlen -
18024 					   max_linkhdr);
18025 				if (max_len <= 0) {
18026 					len = 0;
18027 				} else if (len > max_len) {
18028 					sendalot = 1;
18029 					len = max_len;
18030 					mark = 2;
18031 				}
18032 			}
18033 			/*
18034 			 * Prevent the last segment from being fractional
18035 			 * unless the send sockbuf can be emptied:
18036 			 */
18037 			max_len = (tp->t_maxseg - optlen);
18038 			if ((sb_offset + len) < sbavail(sb)) {
18039 				moff = len % (u_int)max_len;
18040 				if (moff != 0) {
18041 					mark = 3;
18042 					len -= moff;
18043 				}
18044 			}
18045 			/*
18046 			 * In case there are too many small fragments don't
18047 			 * use TSO:
18048 			 */
18049 			if (len <= segsiz) {
18050 				mark = 4;
18051 				tso = 0;
18052 			}
18053 			/*
18054 			 * Send the FIN in a separate segment after the bulk
18055 			 * sending is done. We don't trust the TSO
18056 			 * implementations to clear the FIN flag on all but
18057 			 * the last segment.
18058 			 */
18059 			if (tp->t_flags & TF_NEEDFIN) {
18060 				sendalot = 4;
18061 			}
18062 		} else {
18063 			mark = 5;
18064 			if (optlen + ipoptlen >= tp->t_maxseg) {
18065 				/*
18066 				 * Since we don't have enough space to put
18067 				 * the IP header chain and the TCP header in
18068 				 * one packet as required by RFC 7112, don't
18069 				 * send it. Also ensure that at least one
18070 				 * byte of the payload can be put into the
18071 				 * TCP segment.
18072 				 */
18073 				SOCKBUF_UNLOCK(&so->so_snd);
18074 				error = EMSGSIZE;
18075 				sack_rxmit = 0;
18076 				goto out;
18077 			}
18078 			len = tp->t_maxseg - optlen - ipoptlen;
18079 			sendalot = 5;
18080 		}
18081 	} else {
18082 		tso = 0;
18083 		mark = 6;
18084 	}
18085 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
18086 		("%s: len > IP_MAXPACKET", __func__));
18087 #ifdef DIAGNOSTIC
18088 #ifdef INET6
18089 	if (max_linkhdr + hdrlen > MCLBYTES)
18090 #else
18091 		if (max_linkhdr + hdrlen > MHLEN)
18092 #endif
18093 			panic("tcphdr too big");
18094 #endif
18095 
18096 	/*
18097 	 * This KASSERT is here to catch edge cases at a well defined place.
18098 	 * Before, those had triggered (random) panic conditions further
18099 	 * down.
18100 	 */
18101 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
18102 	if ((len == 0) &&
18103 	    (flags & TH_FIN) &&
18104 	    (sbused(sb))) {
18105 		/*
18106 		 * We have outstanding data, don't send a fin by itself!.
18107 		 */
18108 		goto just_return;
18109 	}
18110 	/*
18111 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
18112 	 * and initialize the header from the template for sends on this
18113 	 * connection.
18114 	 */
18115 	hw_tls = (sb->sb_flags & SB_TLS_IFNET) != 0;
18116 	if (len) {
18117 		uint32_t max_val;
18118 		uint32_t moff;
18119 
18120 		if (rack->r_ctl.rc_pace_max_segs)
18121 			max_val = rack->r_ctl.rc_pace_max_segs;
18122 		else if (rack->rc_user_set_max_segs)
18123 			max_val = rack->rc_user_set_max_segs * segsiz;
18124 		else
18125 			max_val = len;
18126 		/*
18127 		 * We allow a limit on sending with hptsi.
18128 		 */
18129 		if (len > max_val) {
18130 			mark = 7;
18131 			len = max_val;
18132 		}
18133 #ifdef INET6
18134 		if (MHLEN < hdrlen + max_linkhdr)
18135 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
18136 		else
18137 #endif
18138 			m = m_gethdr(M_NOWAIT, MT_DATA);
18139 
18140 		if (m == NULL) {
18141 			SOCKBUF_UNLOCK(sb);
18142 			error = ENOBUFS;
18143 			sack_rxmit = 0;
18144 			goto out;
18145 		}
18146 		m->m_data += max_linkhdr;
18147 		m->m_len = hdrlen;
18148 
18149 		/*
18150 		 * Start the m_copy functions from the closest mbuf to the
18151 		 * sb_offset in the socket buffer chain.
18152 		 */
18153 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
18154 		s_mb = mb;
18155 		s_moff = moff;
18156 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
18157 			m_copydata(mb, moff, (int)len,
18158 				   mtod(m, caddr_t)+hdrlen);
18159 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
18160 				sbsndptr_adv(sb, mb, len);
18161 			m->m_len += len;
18162 		} else {
18163 			struct sockbuf *msb;
18164 
18165 			if (SEQ_LT(tp->snd_nxt, tp->snd_max))
18166 				msb = NULL;
18167 			else
18168 				msb = sb;
18169 			m->m_next = tcp_m_copym(
18170 				mb, moff, &len,
18171 				if_hw_tsomaxsegcount, if_hw_tsomaxsegsize, msb,
18172 				((rsm == NULL) ? hw_tls : 0)
18173 #ifdef NETFLIX_COPY_ARGS
18174 				, &filled_all
18175 #endif
18176 				);
18177 			if (len <= (tp->t_maxseg - optlen)) {
18178 				/*
18179 				 * Must have ran out of mbufs for the copy
18180 				 * shorten it to no longer need tso. Lets
18181 				 * not put on sendalot since we are low on
18182 				 * mbufs.
18183 				 */
18184 				tso = 0;
18185 			}
18186 			if (m->m_next == NULL) {
18187 				SOCKBUF_UNLOCK(sb);
18188 				(void)m_free(m);
18189 				error = ENOBUFS;
18190 				sack_rxmit = 0;
18191 				goto out;
18192 			}
18193 		}
18194 		if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
18195 			if (rsm && (rsm->r_flags & RACK_TLP)) {
18196 				/*
18197 				 * TLP should not count in retran count, but
18198 				 * in its own bin
18199 				 */
18200 				counter_u64_add(rack_tlp_retran, 1);
18201 				counter_u64_add(rack_tlp_retran_bytes, len);
18202 			} else {
18203 				tp->t_sndrexmitpack++;
18204 				KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
18205 				KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
18206 			}
18207 #ifdef STATS
18208 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
18209 						 len);
18210 #endif
18211 		} else {
18212 			KMOD_TCPSTAT_INC(tcps_sndpack);
18213 			KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
18214 #ifdef STATS
18215 			stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
18216 						 len);
18217 #endif
18218 		}
18219 		/*
18220 		 * If we're sending everything we've got, set PUSH. (This
18221 		 * will keep happy those implementations which only give
18222 		 * data to the user when a buffer fills or a PUSH comes in.)
18223 		 */
18224 		if (sb_offset + len == sbused(sb) &&
18225 		    sbused(sb) &&
18226 		    !(flags & TH_SYN)) {
18227 			flags |= TH_PUSH;
18228 			add_flag |= RACK_HAD_PUSH;
18229 		}
18230 
18231 		SOCKBUF_UNLOCK(sb);
18232 	} else {
18233 		SOCKBUF_UNLOCK(sb);
18234 		if (tp->t_flags & TF_ACKNOW)
18235 			KMOD_TCPSTAT_INC(tcps_sndacks);
18236 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
18237 			KMOD_TCPSTAT_INC(tcps_sndctrl);
18238 		else
18239 			KMOD_TCPSTAT_INC(tcps_sndwinup);
18240 
18241 		m = m_gethdr(M_NOWAIT, MT_DATA);
18242 		if (m == NULL) {
18243 			error = ENOBUFS;
18244 			sack_rxmit = 0;
18245 			goto out;
18246 		}
18247 #ifdef INET6
18248 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
18249 		    MHLEN >= hdrlen) {
18250 			M_ALIGN(m, hdrlen);
18251 		} else
18252 #endif
18253 			m->m_data += max_linkhdr;
18254 		m->m_len = hdrlen;
18255 	}
18256 	SOCKBUF_UNLOCK_ASSERT(sb);
18257 	m->m_pkthdr.rcvif = (struct ifnet *)0;
18258 #ifdef MAC
18259 	mac_inpcb_create_mbuf(inp, m);
18260 #endif
18261 	if ((ipoptlen == 0) && (rack->r_ctl.fsb.tcp_ip_hdr) &&  rack->r_fsb_inited) {
18262 #ifdef INET6
18263 		if (isipv6)
18264 			ip6 = (struct ip6_hdr *)rack->r_ctl.fsb.tcp_ip_hdr;
18265 		else
18266 #endif				/* INET6 */
18267 			ip = (struct ip *)rack->r_ctl.fsb.tcp_ip_hdr;
18268 		th = rack->r_ctl.fsb.th;
18269 		udp = rack->r_ctl.fsb.udp;
18270 		if (udp) {
18271 #ifdef INET6
18272 			if (isipv6)
18273 				ulen = hdrlen + len - sizeof(struct ip6_hdr);
18274 			else
18275 #endif				/* INET6 */
18276 				ulen = hdrlen + len - sizeof(struct ip);
18277 			udp->uh_ulen = htons(ulen);
18278 		}
18279 	} else {
18280 #ifdef INET6
18281 		if (isipv6) {
18282 			ip6 = mtod(m, struct ip6_hdr *);
18283 			if (tp->t_port) {
18284 				udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
18285 				udp->uh_sport = htons(V_tcp_udp_tunneling_port);
18286 				udp->uh_dport = tp->t_port;
18287 				ulen = hdrlen + len - sizeof(struct ip6_hdr);
18288 				udp->uh_ulen = htons(ulen);
18289 				th = (struct tcphdr *)(udp + 1);
18290 			} else
18291 				th = (struct tcphdr *)(ip6 + 1);
18292 			tcpip_fillheaders(inp, tp->t_port, ip6, th);
18293 		} else
18294 #endif				/* INET6 */
18295 		{
18296 			ip = mtod(m, struct ip *);
18297 #ifdef TCPDEBUG
18298 			ipov = (struct ipovly *)ip;
18299 #endif
18300 			if (tp->t_port) {
18301 				udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
18302 				udp->uh_sport = htons(V_tcp_udp_tunneling_port);
18303 				udp->uh_dport = tp->t_port;
18304 				ulen = hdrlen + len - sizeof(struct ip);
18305 				udp->uh_ulen = htons(ulen);
18306 				th = (struct tcphdr *)(udp + 1);
18307 			} else
18308 				th = (struct tcphdr *)(ip + 1);
18309 			tcpip_fillheaders(inp, tp->t_port, ip, th);
18310 		}
18311 	}
18312 	/*
18313 	 * Fill in fields, remembering maximum advertised window for use in
18314 	 * delaying messages about window sizes. If resending a FIN, be sure
18315 	 * not to use a new sequence number.
18316 	 */
18317 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
18318 	    tp->snd_nxt == tp->snd_max)
18319 		tp->snd_nxt--;
18320 	/*
18321 	 * If we are starting a connection, send ECN setup SYN packet. If we
18322 	 * are on a retransmit, we may resend those bits a number of times
18323 	 * as per RFC 3168.
18324 	 */
18325 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn == 1) {
18326 		if (tp->t_rxtshift >= 1) {
18327 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
18328 				flags |= TH_ECE | TH_CWR;
18329 		} else
18330 			flags |= TH_ECE | TH_CWR;
18331 	}
18332 	/* Handle parallel SYN for ECN */
18333 	if ((tp->t_state == TCPS_SYN_RECEIVED) &&
18334 	    (tp->t_flags2 & TF2_ECN_SND_ECE)) {
18335 		flags |= TH_ECE;
18336 		tp->t_flags2 &= ~TF2_ECN_SND_ECE;
18337 	}
18338 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
18339 	    (tp->t_flags2 & TF2_ECN_PERMIT)) {
18340 		/*
18341 		 * If the peer has ECN, mark data packets with ECN capable
18342 		 * transmission (ECT). Ignore pure ack packets,
18343 		 * retransmissions.
18344 		 */
18345 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
18346 		    (sack_rxmit == 0)) {
18347 #ifdef INET6
18348 			if (isipv6)
18349 				ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
18350 			else
18351 #endif
18352 				ip->ip_tos |= IPTOS_ECN_ECT0;
18353 			KMOD_TCPSTAT_INC(tcps_ecn_ect0);
18354 			/*
18355 			 * Reply with proper ECN notifications.
18356 			 * Only set CWR on new data segments.
18357 			 */
18358 			if (tp->t_flags2 & TF2_ECN_SND_CWR) {
18359 				flags |= TH_CWR;
18360 				tp->t_flags2 &= ~TF2_ECN_SND_CWR;
18361 			}
18362 		}
18363 		if (tp->t_flags2 & TF2_ECN_SND_ECE)
18364 			flags |= TH_ECE;
18365 	}
18366 	/*
18367 	 * If we are doing retransmissions, then snd_nxt will not reflect
18368 	 * the first unsent octet.  For ACK only packets, we do not want the
18369 	 * sequence number of the retransmitted packet, we want the sequence
18370 	 * number of the next unsent octet.  So, if there is no data (and no
18371 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
18372 	 * ti_seq.  But if we are in persist state, snd_max might reflect
18373 	 * one byte beyond the right edge of the window, so use snd_nxt in
18374 	 * that case, since we know we aren't doing a retransmission.
18375 	 * (retransmit and persist are mutually exclusive...)
18376 	 */
18377 	if (sack_rxmit == 0) {
18378 		if (len || (flags & (TH_SYN | TH_FIN))) {
18379 			th->th_seq = htonl(tp->snd_nxt);
18380 			rack_seq = tp->snd_nxt;
18381 		} else {
18382 			th->th_seq = htonl(tp->snd_max);
18383 			rack_seq = tp->snd_max;
18384 		}
18385 	} else {
18386 		th->th_seq = htonl(rsm->r_start);
18387 		rack_seq = rsm->r_start;
18388 	}
18389 	th->th_ack = htonl(tp->rcv_nxt);
18390 	th->th_flags = flags;
18391 	/*
18392 	 * Calculate receive window.  Don't shrink window, but avoid silly
18393 	 * window syndrome.
18394 	 * If a RST segment is sent, advertise a window of zero.
18395 	 */
18396 	if (flags & TH_RST) {
18397 		recwin = 0;
18398 	} else {
18399 		if (recwin < (long)(so->so_rcv.sb_hiwat / 4) &&
18400 		    recwin < (long)segsiz) {
18401 			recwin = 0;
18402 		}
18403 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
18404 		    recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
18405 			recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
18406 	}
18407 
18408 	/*
18409 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
18410 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
18411 	 * handled in syncache.
18412 	 */
18413 	if (flags & TH_SYN)
18414 		th->th_win = htons((u_short)
18415 				   (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
18416 	else {
18417 		/* Avoid shrinking window with window scaling. */
18418 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
18419 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
18420 	}
18421 	/*
18422 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
18423 	 * window.  This may cause the remote transmitter to stall.  This
18424 	 * flag tells soreceive() to disable delayed acknowledgements when
18425 	 * draining the buffer.  This can occur if the receiver is
18426 	 * attempting to read more data than can be buffered prior to
18427 	 * transmitting on the connection.
18428 	 */
18429 	if (th->th_win == 0) {
18430 		tp->t_sndzerowin++;
18431 		tp->t_flags |= TF_RXWIN0SENT;
18432 	} else
18433 		tp->t_flags &= ~TF_RXWIN0SENT;
18434 	tp->snd_up = tp->snd_una;	/* drag it along, its deprecated */
18435 	/* Now are we using fsb?, if so copy the template data to the mbuf */
18436 	if ((ipoptlen == 0) && (rack->r_ctl.fsb.tcp_ip_hdr) && rack->r_fsb_inited) {
18437 		uint8_t *cpto;
18438 
18439 		cpto = mtod(m, uint8_t *);
18440 		memcpy(cpto, rack->r_ctl.fsb.tcp_ip_hdr, rack->r_ctl.fsb.tcp_ip_hdr_len);
18441 		/*
18442 		 * We have just copied in:
18443 		 * IP/IP6
18444 		 * <optional udphdr>
18445 		 * tcphdr (no options)
18446 		 *
18447 		 * We need to grab the correct pointers into the mbuf
18448 		 * for both the tcp header, and possibly the udp header (if tunneling).
18449 		 * We do this by using the offset in the copy buffer and adding it
18450 		 * to the mbuf base pointer (cpto).
18451 		 */
18452 #ifdef INET6
18453 		if (isipv6)
18454 			ip6 = mtod(m, struct ip6_hdr *);
18455 		else
18456 #endif				/* INET6 */
18457 			ip = mtod(m, struct ip *);
18458 		th = (struct tcphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.th - rack->r_ctl.fsb.tcp_ip_hdr));
18459 		/* If we have a udp header lets set it into the mbuf as well */
18460 		if (udp)
18461 			udp = (struct udphdr *)(cpto + ((uint8_t *)rack->r_ctl.fsb.udp - rack->r_ctl.fsb.tcp_ip_hdr));
18462 	}
18463 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
18464 	if (to.to_flags & TOF_SIGNATURE) {
18465 		/*
18466 		 * Calculate MD5 signature and put it into the place
18467 		 * determined before.
18468 		 * NOTE: since TCP options buffer doesn't point into
18469 		 * mbuf's data, calculate offset and use it.
18470 		 */
18471 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
18472 						       (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
18473 			/*
18474 			 * Do not send segment if the calculation of MD5
18475 			 * digest has failed.
18476 			 */
18477 			goto out;
18478 		}
18479 	}
18480 #endif
18481 	if (optlen) {
18482 		bcopy(opt, th + 1, optlen);
18483 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
18484 	}
18485 	/*
18486 	 * Put TCP length in extended header, and then checksum extended
18487 	 * header and data.
18488 	 */
18489 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
18490 #ifdef INET6
18491 	if (isipv6) {
18492 		/*
18493 		 * ip6_plen is not need to be filled now, and will be filled
18494 		 * in ip6_output.
18495 		 */
18496 		if (tp->t_port) {
18497 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
18498 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
18499 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
18500 			th->th_sum = htons(0);
18501 			UDPSTAT_INC(udps_opackets);
18502 		} else {
18503 			m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
18504 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
18505 			th->th_sum = in6_cksum_pseudo(ip6,
18506 						      sizeof(struct tcphdr) + optlen + len, IPPROTO_TCP,
18507 						      0);
18508 		}
18509 	}
18510 #endif
18511 #if defined(INET6) && defined(INET)
18512 	else
18513 #endif
18514 #ifdef INET
18515 	{
18516 		if (tp->t_port) {
18517 			m->m_pkthdr.csum_flags = CSUM_UDP;
18518 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
18519 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
18520 						ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
18521 			th->th_sum = htons(0);
18522 			UDPSTAT_INC(udps_opackets);
18523 		} else {
18524 			m->m_pkthdr.csum_flags = CSUM_TCP;
18525 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
18526 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
18527 					       ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
18528 									IPPROTO_TCP + len + optlen));
18529 		}
18530 		/* IP version must be set here for ipv4/ipv6 checking later */
18531 		KASSERT(ip->ip_v == IPVERSION,
18532 			("%s: IP version incorrect: %d", __func__, ip->ip_v));
18533 	}
18534 #endif
18535 	/*
18536 	 * Enable TSO and specify the size of the segments. The TCP pseudo
18537 	 * header checksum is always provided. XXX: Fixme: This is currently
18538 	 * not the case for IPv6.
18539 	 */
18540 	if (tso) {
18541 		KASSERT(len > tp->t_maxseg - optlen,
18542 			("%s: len <= tso_segsz", __func__));
18543 		m->m_pkthdr.csum_flags |= CSUM_TSO;
18544 		m->m_pkthdr.tso_segsz = tp->t_maxseg - optlen;
18545 	}
18546 	KASSERT(len + hdrlen == m_length(m, NULL),
18547 		("%s: mbuf chain different than expected: %d + %u != %u",
18548 		 __func__, len, hdrlen, m_length(m, NULL)));
18549 
18550 #ifdef TCP_HHOOK
18551 	/* Run HHOOK_TCP_ESTABLISHED_OUT helper hooks. */
18552 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
18553 #endif
18554 	/* We're getting ready to send; log now. */
18555 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
18556 		union tcp_log_stackspecific log;
18557 
18558 		memset(&log.u_bbr, 0, sizeof(log.u_bbr));
18559 		log.u_bbr.inhpts = rack->rc_inp->inp_in_hpts;
18560 		log.u_bbr.ininput = rack->rc_inp->inp_in_input;
18561 		if (rack->rack_no_prr)
18562 			log.u_bbr.flex1 = 0;
18563 		else
18564 			log.u_bbr.flex1 = rack->r_ctl.rc_prr_sndcnt;
18565 		log.u_bbr.flex2 = rack->r_ctl.rc_pace_min_segs;
18566 		log.u_bbr.flex3 = rack->r_ctl.rc_pace_max_segs;
18567 		log.u_bbr.flex4 = orig_len;
18568 		if (filled_all)
18569 			log.u_bbr.flex5 = 0x80000000;
18570 		else
18571 			log.u_bbr.flex5 = 0;
18572 		/* Save off the early/late values */
18573 		log.u_bbr.flex6 = rack->r_ctl.rc_agg_early;
18574 		log.u_bbr.applimited = rack->r_ctl.rc_agg_delayed;
18575 		log.u_bbr.bw_inuse = rack_get_bw(rack);
18576 		if (rsm || sack_rxmit) {
18577 			if (doing_tlp)
18578 				log.u_bbr.flex8 = 2;
18579 			else
18580 				log.u_bbr.flex8 = 1;
18581 		} else {
18582 			if (doing_tlp)
18583 				log.u_bbr.flex8 = 3;
18584 			else
18585 				log.u_bbr.flex8 = 0;
18586 		}
18587 		log.u_bbr.pacing_gain = rack_get_output_gain(rack, rsm);
18588 		log.u_bbr.flex7 = mark;
18589 		log.u_bbr.flex7 <<= 8;
18590 		log.u_bbr.flex7 |= pass;
18591 		log.u_bbr.pkts_out = tp->t_maxseg;
18592 		log.u_bbr.timeStamp = cts;
18593 		log.u_bbr.inflight = ctf_flight_size(rack->rc_tp, rack->r_ctl.rc_sacked);
18594 		log.u_bbr.lt_epoch = cwnd_to_use;
18595 		log.u_bbr.delivered = sendalot;
18596 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
18597 				     len, &log, false, NULL, NULL, 0, &tv);
18598 	} else
18599 		lgb = NULL;
18600 
18601 	/*
18602 	 * Fill in IP length and desired time to live and send to IP level.
18603 	 * There should be a better way to handle ttl and tos; we could keep
18604 	 * them in the template, but need a way to checksum without them.
18605 	 */
18606 	/*
18607 	 * m->m_pkthdr.len should have been set before cksum calcuration,
18608 	 * because in6_cksum() need it.
18609 	 */
18610 #ifdef INET6
18611 	if (isipv6) {
18612 		/*
18613 		 * we separately set hoplimit for every segment, since the
18614 		 * user might want to change the value via setsockopt. Also,
18615 		 * desired default hop limit might be changed via Neighbor
18616 		 * Discovery.
18617 		 */
18618 		rack->r_ctl.fsb.hoplimit = ip6->ip6_hlim = in6_selecthlim(inp, NULL);
18619 
18620 		/*
18621 		 * Set the packet size here for the benefit of DTrace
18622 		 * probes. ip6_output() will set it properly; it's supposed
18623 		 * to include the option header lengths as well.
18624 		 */
18625 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
18626 
18627 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss)
18628 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
18629 		else
18630 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
18631 
18632 		if (tp->t_state == TCPS_SYN_SENT)
18633 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
18634 
18635 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
18636 		/* TODO: IPv6 IP6TOS_ECT bit on */
18637 		error = ip6_output(m,
18638 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18639 				   inp->in6p_outputopts,
18640 #else
18641 				   NULL,
18642 #endif
18643 				   &inp->inp_route6,
18644 				   ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
18645 				   NULL, NULL, inp);
18646 
18647 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
18648 			mtu = inp->inp_route6.ro_nh->nh_mtu;
18649 	}
18650 #endif				/* INET6 */
18651 #if defined(INET) && defined(INET6)
18652 	else
18653 #endif
18654 #ifdef INET
18655 	{
18656 		ip->ip_len = htons(m->m_pkthdr.len);
18657 #ifdef INET6
18658 		if (inp->inp_vflag & INP_IPV6PROTO)
18659 			ip->ip_ttl = in6_selecthlim(inp, NULL);
18660 #endif				/* INET6 */
18661 		rack->r_ctl.fsb.hoplimit = ip->ip_ttl;
18662 		/*
18663 		 * If we do path MTU discovery, then we set DF on every
18664 		 * packet. This might not be the best thing to do according
18665 		 * to RFC3390 Section 2. However the tcp hostcache migitates
18666 		 * the problem so it affects only the first tcp connection
18667 		 * with a host.
18668 		 *
18669 		 * NB: Don't set DF on small MTU/MSS to have a safe
18670 		 * fallback.
18671 		 */
18672 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
18673 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
18674 			if (tp->t_port == 0 || len < V_tcp_minmss) {
18675 				ip->ip_off |= htons(IP_DF);
18676 			}
18677 		} else {
18678 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
18679 		}
18680 
18681 		if (tp->t_state == TCPS_SYN_SENT)
18682 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
18683 
18684 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
18685 
18686 		error = ip_output(m,
18687 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
18688 				  inp->inp_options,
18689 #else
18690 				  NULL,
18691 #endif
18692 				  &inp->inp_route,
18693 				  ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
18694 				  inp);
18695 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
18696 			mtu = inp->inp_route.ro_nh->nh_mtu;
18697 	}
18698 #endif				/* INET */
18699 
18700 out:
18701 	if (lgb) {
18702 		lgb->tlb_errno = error;
18703 		lgb = NULL;
18704 	}
18705 	/*
18706 	 * In transmit state, time the transmission and arrange for the
18707 	 * retransmit.  In persist state, just set snd_max.
18708 	 */
18709 	if (error == 0) {
18710 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
18711 		if (rsm && doing_tlp) {
18712 			rack->rc_last_sent_tlp_past_cumack = 0;
18713 			rack->rc_last_sent_tlp_seq_valid = 1;
18714 			rack->r_ctl.last_sent_tlp_seq = rsm->r_start;
18715 			rack->r_ctl.last_sent_tlp_len = rsm->r_end - rsm->r_start;
18716 		}
18717 		rack->forced_ack = 0;	/* If we send something zap the FA flag */
18718 		if (rsm && (doing_tlp == 0)) {
18719 			/* Set we retransmitted */
18720 			rack->rc_gp_saw_rec = 1;
18721 		} else {
18722 			if (cwnd_to_use > tp->snd_ssthresh) {
18723 				/* Set we sent in CA */
18724 				rack->rc_gp_saw_ca = 1;
18725 			} else {
18726 				/* Set we sent in SS */
18727 				rack->rc_gp_saw_ss = 1;
18728 			}
18729 		}
18730 		if (doing_tlp && (rsm == NULL)) {
18731 			/* Make sure new data TLP cnt is clear */
18732 			rack->r_ctl.rc_tlp_new_data = 0;
18733 		}
18734 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
18735 		    (tp->t_flags & TF_SACK_PERMIT) &&
18736 		    tp->rcv_numsacks > 0)
18737 			tcp_clean_dsack_blocks(tp);
18738 		tot_len_this_send += len;
18739 		if (len == 0)
18740 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_SNDACK], 1);
18741 		else if (len == 1) {
18742 			counter_u64_add(rack_out_size[TCP_MSS_ACCT_PERSIST], 1);
18743 		} else if (len > 1) {
18744 			int idx;
18745 
18746 			idx = (len / segsiz) + 3;
18747 			if (idx >= TCP_MSS_ACCT_ATIMER)
18748 				counter_u64_add(rack_out_size[(TCP_MSS_ACCT_ATIMER-1)], 1);
18749 			else
18750 				counter_u64_add(rack_out_size[idx], 1);
18751 		}
18752 	}
18753 	if ((rack->rack_no_prr == 0) &&
18754 	    sub_from_prr &&
18755 	    (error == 0)) {
18756 		if (rack->r_ctl.rc_prr_sndcnt >= len)
18757 			rack->r_ctl.rc_prr_sndcnt -= len;
18758 		else
18759 			rack->r_ctl.rc_prr_sndcnt = 0;
18760 	}
18761 	sub_from_prr = 0;
18762 	if (doing_tlp) {
18763 		/* Make sure the TLP is added */
18764 		add_flag |= RACK_TLP;
18765 	} else if (rsm) {
18766 		/* If its a resend without TLP then it must not have the flag */
18767 		rsm->r_flags &= ~RACK_TLP;
18768 	}
18769 	rack_log_output(tp, &to, len, rack_seq, (uint8_t) flags, error,
18770 			rack_to_usec_ts(&tv),
18771 			rsm, add_flag, s_mb, s_moff, hw_tls);
18772 
18773 
18774 	if ((error == 0) &&
18775 	    (len > 0) &&
18776 	    (tp->snd_una == tp->snd_max))
18777 		rack->r_ctl.rc_tlp_rxt_last_time = cts;
18778 	{
18779 		tcp_seq startseq = tp->snd_nxt;
18780 
18781 		/* Track our lost count */
18782 		if (rsm && (doing_tlp == 0))
18783 			rack->r_ctl.rc_loss_count += rsm->r_end - rsm->r_start;
18784 		/*
18785 		 * Advance snd_nxt over sequence space of this segment.
18786 		 */
18787 		if (error)
18788 			/* We don't log or do anything with errors */
18789 			goto nomore;
18790 		if (doing_tlp == 0) {
18791 			if (rsm == NULL) {
18792 				/*
18793 				 * Not a retransmission of some
18794 				 * sort, new data is going out so
18795 				 * clear our TLP count and flag.
18796 				 */
18797 				rack->rc_tlp_in_progress = 0;
18798 				rack->r_ctl.rc_tlp_cnt_out = 0;
18799 			}
18800 		} else {
18801 			/*
18802 			 * We have just sent a TLP, mark that it is true
18803 			 * and make sure our in progress is set so we
18804 			 * continue to check the count.
18805 			 */
18806 			rack->rc_tlp_in_progress = 1;
18807 			rack->r_ctl.rc_tlp_cnt_out++;
18808 		}
18809 		if (flags & (TH_SYN | TH_FIN)) {
18810 			if (flags & TH_SYN)
18811 				tp->snd_nxt++;
18812 			if (flags & TH_FIN) {
18813 				tp->snd_nxt++;
18814 				tp->t_flags |= TF_SENTFIN;
18815 			}
18816 		}
18817 		/* In the ENOBUFS case we do *not* update snd_max */
18818 		if (sack_rxmit)
18819 			goto nomore;
18820 
18821 		tp->snd_nxt += len;
18822 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
18823 			if (tp->snd_una == tp->snd_max) {
18824 				/*
18825 				 * Update the time we just added data since
18826 				 * none was outstanding.
18827 				 */
18828 				rack_log_progress_event(rack, tp, ticks, PROGRESS_START, __LINE__);
18829 				tp->t_acktime = ticks;
18830 			}
18831 			tp->snd_max = tp->snd_nxt;
18832 			/*
18833 			 * Time this transmission if not a retransmission and
18834 			 * not currently timing anything.
18835 			 * This is only relevant in case of switching back to
18836 			 * the base stack.
18837 			 */
18838 			if (tp->t_rtttime == 0) {
18839 				tp->t_rtttime = ticks;
18840 				tp->t_rtseq = startseq;
18841 				KMOD_TCPSTAT_INC(tcps_segstimed);
18842 			}
18843 			if (len &&
18844 			    ((tp->t_flags & TF_GPUTINPROG) == 0))
18845 				rack_start_gp_measurement(tp, rack, startseq, sb_offset);
18846 		}
18847 		/*
18848 		 * If we are doing FO we need to update the mbuf position and subtract
18849 		 * this happens when the peer sends us duplicate information and
18850 		 * we thus want to send a DSACK.
18851 		 *
18852 		 * XXXRRS: This brings to mind a ?, when we send a DSACK block is TSO
18853 		 * turned off? If not then we are going to echo multiple DSACK blocks
18854 		 * out (with the TSO), which we should not be doing.
18855 		 */
18856 		if (rack->r_fast_output && len) {
18857 			if (rack->r_ctl.fsb.left_to_send > len)
18858 				rack->r_ctl.fsb.left_to_send -= len;
18859 			else
18860 				rack->r_ctl.fsb.left_to_send = 0;
18861 			if (rack->r_ctl.fsb.left_to_send < segsiz)
18862 				rack->r_fast_output = 0;
18863 			if (rack->r_fast_output) {
18864 				rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
18865 				rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
18866 			}
18867 		}
18868 	}
18869 nomore:
18870 	if (error) {
18871 		rack->r_ctl.rc_agg_delayed = 0;
18872 		rack->r_early = 0;
18873 		rack->r_late = 0;
18874 		rack->r_ctl.rc_agg_early = 0;
18875 		SOCKBUF_UNLOCK_ASSERT(sb);	/* Check gotos. */
18876 		/*
18877 		 * Failures do not advance the seq counter above. For the
18878 		 * case of ENOBUFS we will fall out and retry in 1ms with
18879 		 * the hpts. Everything else will just have to retransmit
18880 		 * with the timer.
18881 		 *
18882 		 * In any case, we do not want to loop around for another
18883 		 * send without a good reason.
18884 		 */
18885 		sendalot = 0;
18886 		switch (error) {
18887 		case EPERM:
18888 			tp->t_softerror = error;
18889 #ifdef TCP_ACCOUNTING
18890 			crtsc = get_cyclecount();
18891 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18892 				tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18893 			}
18894 			counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18895 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18896 				tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18897 			}
18898 			counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18899 			sched_unpin();
18900 #endif
18901 			return (error);
18902 		case ENOBUFS:
18903 			/*
18904 			 * Pace us right away to retry in a some
18905 			 * time
18906 			 */
18907 			slot = ((1 + rack->rc_enobuf) * HPTS_USEC_IN_MSEC);
18908 			if (rack->rc_enobuf < 0x7f)
18909 				rack->rc_enobuf++;
18910 			if (slot < (10 * HPTS_USEC_IN_MSEC))
18911 				slot = 10 * HPTS_USEC_IN_MSEC;
18912 			if (rack->r_ctl.crte != NULL) {
18913 				counter_u64_add(rack_saw_enobuf_hw, 1);
18914 				tcp_rl_log_enobuf(rack->r_ctl.crte);
18915 			}
18916 			counter_u64_add(rack_saw_enobuf, 1);
18917 			goto enobufs;
18918 		case EMSGSIZE:
18919 			/*
18920 			 * For some reason the interface we used initially
18921 			 * to send segments changed to another or lowered
18922 			 * its MTU. If TSO was active we either got an
18923 			 * interface without TSO capabilits or TSO was
18924 			 * turned off. If we obtained mtu from ip_output()
18925 			 * then update it and try again.
18926 			 */
18927 			if (tso)
18928 				tp->t_flags &= ~TF_TSO;
18929 			if (mtu != 0) {
18930 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
18931 				goto again;
18932 			}
18933 			slot = 10 * HPTS_USEC_IN_MSEC;
18934 			rack_start_hpts_timer(rack, tp, cts, slot, 0, 0);
18935 #ifdef TCP_ACCOUNTING
18936 			crtsc = get_cyclecount();
18937 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18938 				tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18939 			}
18940 			counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18941 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18942 				tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18943 			}
18944 			counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18945 			sched_unpin();
18946 #endif
18947 			return (error);
18948 		case ENETUNREACH:
18949 			counter_u64_add(rack_saw_enetunreach, 1);
18950 		case EHOSTDOWN:
18951 		case EHOSTUNREACH:
18952 		case ENETDOWN:
18953 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
18954 				tp->t_softerror = error;
18955 			}
18956 			/* FALLTHROUGH */
18957 		default:
18958 			slot = 10 * HPTS_USEC_IN_MSEC;
18959 			rack_start_hpts_timer(rack, tp, cts, slot, 0, 0);
18960 #ifdef TCP_ACCOUNTING
18961 			crtsc = get_cyclecount();
18962 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18963 				tp->tcp_cnt_counters[SND_OUT_FAIL]++;
18964 			}
18965 			counter_u64_add(tcp_cnt_counters[SND_OUT_FAIL], 1);
18966 			if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
18967 				tp->tcp_proc_time[SND_OUT_FAIL] += (crtsc - ts_val);
18968 			}
18969 			counter_u64_add(tcp_proc_time[SND_OUT_FAIL], (crtsc - ts_val));
18970 			sched_unpin();
18971 #endif
18972 			return (error);
18973 		}
18974 	} else {
18975 		rack->rc_enobuf = 0;
18976 		if (IN_FASTRECOVERY(tp->t_flags) && rsm)
18977 			rack->r_ctl.retran_during_recovery += len;
18978 	}
18979 	KMOD_TCPSTAT_INC(tcps_sndtotal);
18980 
18981 	/*
18982 	 * Data sent (as far as we can tell). If this advertises a larger
18983 	 * window than any other segment, then remember the size of the
18984 	 * advertised window. Any pending ACK has now been sent.
18985 	 */
18986 	if (recwin > 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
18987 		tp->rcv_adv = tp->rcv_nxt + recwin;
18988 
18989 	tp->last_ack_sent = tp->rcv_nxt;
18990 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
18991 enobufs:
18992 	if (sendalot) {
18993 		/* Do we need to turn off sendalot? */
18994 		if (rack->r_ctl.rc_pace_max_segs &&
18995 		    (tot_len_this_send >= rack->r_ctl.rc_pace_max_segs)) {
18996 			/* We hit our max. */
18997 			sendalot = 0;
18998 		} else if ((rack->rc_user_set_max_segs) &&
18999 			   (tot_len_this_send >= (rack->rc_user_set_max_segs * segsiz))) {
19000 			/* We hit the user defined max */
19001 			sendalot = 0;
19002 		}
19003 	}
19004 	if ((error == 0) && (flags & TH_FIN))
19005 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
19006 	if (flags & TH_RST) {
19007 		/*
19008 		 * We don't send again after sending a RST.
19009 		 */
19010 		slot = 0;
19011 		sendalot = 0;
19012 		if (error == 0)
19013 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
19014 	} else if ((slot == 0) && (sendalot == 0) && tot_len_this_send) {
19015 		/*
19016 		 * Get our pacing rate, if an error
19017 		 * occurred in sending (ENOBUF) we would
19018 		 * hit the else if with slot preset. Other
19019 		 * errors return.
19020 		 */
19021 		slot = rack_get_pacing_delay(rack, tp, tot_len_this_send, rsm, segsiz);
19022 	}
19023 	if (rsm &&
19024 	    (rsm->r_flags & RACK_HAS_SYN) == 0 &&
19025 	    rack->use_rack_rr) {
19026 		/* Its a retransmit and we use the rack cheat? */
19027 		if ((slot == 0) ||
19028 		    (rack->rc_always_pace == 0) ||
19029 		    (rack->r_rr_config == 1)) {
19030 			/*
19031 			 * We have no pacing set or we
19032 			 * are using old-style rack or
19033 			 * we are overriden to use the old 1ms pacing.
19034 			 */
19035 			slot = rack->r_ctl.rc_min_to;
19036 		}
19037 	}
19038 	/* We have sent clear the flag */
19039 	rack->r_ent_rec_ns = 0;
19040 	if (rack->r_must_retran) {
19041 		if (rsm) {
19042 			rack->r_ctl.rc_out_at_rto -= (rsm->r_end - rsm->r_start);
19043 			if (SEQ_GEQ(rsm->r_end, rack->r_ctl.rc_snd_max_at_rto)) {
19044 				/*
19045 				 * We have retransmitted all.
19046 				 */
19047 				rack->r_must_retran = 0;
19048 				rack->r_ctl.rc_out_at_rto = 0;
19049 			}
19050 		} else if (SEQ_GEQ(tp->snd_max, rack->r_ctl.rc_snd_max_at_rto)) {
19051 			/*
19052 			 * Sending new data will also kill
19053 			 * the loop.
19054 			 */
19055 			rack->r_must_retran = 0;
19056 			rack->r_ctl.rc_out_at_rto = 0;
19057 		}
19058 	}
19059 	rack->r_ctl.fsb.recwin = recwin;
19060 	if ((tp->t_flags & (TF_WASCRECOVERY|TF_WASFRECOVERY)) &&
19061 	    SEQ_GT(tp->snd_max, rack->r_ctl.rc_snd_max_at_rto)) {
19062 		/*
19063 		 * We hit an RTO and now have past snd_max at the RTO
19064 		 * clear all the WAS flags.
19065 		 */
19066 		tp->t_flags &= ~(TF_WASCRECOVERY|TF_WASFRECOVERY);
19067 	}
19068 	if (slot) {
19069 		/* set the rack tcb into the slot N */
19070 		counter_u64_add(rack_paced_segments, 1);
19071 		if ((error == 0) &&
19072 		    rack_use_rfo &&
19073 		    ((flags & (TH_SYN|TH_FIN)) == 0) &&
19074 		    (rsm == NULL) &&
19075 		    (tp->snd_nxt == tp->snd_max) &&
19076 		    (ipoptlen == 0) &&
19077 		    (tp->rcv_numsacks == 0) &&
19078 		    rack->r_fsb_inited &&
19079 		    TCPS_HAVEESTABLISHED(tp->t_state) &&
19080 		    (rack->r_must_retran == 0) &&
19081 		    ((tp->t_flags & TF_NEEDFIN) == 0) &&
19082 		    (len > 0) && (orig_len > 0) &&
19083 		    (orig_len > len) &&
19084 		    ((orig_len - len) >= segsiz) &&
19085 		    ((optlen == 0) ||
19086 		     ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
19087 			/* We can send at least one more MSS using our fsb */
19088 
19089 			rack->r_fast_output = 1;
19090 			rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
19091 			rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
19092 			rack->r_ctl.fsb.tcp_flags = flags;
19093 			rack->r_ctl.fsb.left_to_send = orig_len - len;
19094 			if (hw_tls)
19095 				rack->r_ctl.fsb.hw_tls = 1;
19096 			else
19097 				rack->r_ctl.fsb.hw_tls = 0;
19098 			KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
19099 				("rack:%p left_to_send:%u sbavail:%u out:%u",
19100 				 rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
19101 				 (tp->snd_max - tp->snd_una)));
19102 			if (rack->r_ctl.fsb.left_to_send < segsiz)
19103 				rack->r_fast_output = 0;
19104 			else {
19105 				if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
19106 					rack->r_ctl.fsb.rfo_apply_push = 1;
19107 				else
19108 					rack->r_ctl.fsb.rfo_apply_push = 0;
19109 			}
19110 		} else
19111 			rack->r_fast_output = 0;
19112 		rack_log_fsb(rack, tp, so, flags,
19113 			     ipoptlen, orig_len, len, error,
19114 			     (rsm == NULL), optlen, __LINE__, 2);
19115 	} else if (sendalot) {
19116 		int ret;
19117 
19118 		if (len)
19119 			counter_u64_add(rack_unpaced_segments, 1);
19120 		sack_rxmit = 0;
19121 		if ((error == 0) &&
19122 		    rack_use_rfo &&
19123 		    ((flags & (TH_SYN|TH_FIN)) == 0) &&
19124 		    (rsm == NULL) &&
19125 		    (ipoptlen == 0) &&
19126 		    (tp->rcv_numsacks == 0) &&
19127 		    (tp->snd_nxt == tp->snd_max) &&
19128 		    (rack->r_must_retran == 0) &&
19129 		    rack->r_fsb_inited &&
19130 		    TCPS_HAVEESTABLISHED(tp->t_state) &&
19131 		    ((tp->t_flags & TF_NEEDFIN) == 0) &&
19132 		    (len > 0) && (orig_len > 0) &&
19133 		    (orig_len > len) &&
19134 		    ((orig_len - len) >= segsiz) &&
19135 		    ((optlen == 0) ||
19136 		     ((optlen == TCPOLEN_TSTAMP_APPA) && (to.to_flags & TOF_TS)))) {
19137 			/* we can use fast_output for more */
19138 
19139 			rack->r_fast_output = 1;
19140 			rack->r_ctl.fsb.m = sbsndmbuf(sb, (tp->snd_max - tp->snd_una), &rack->r_ctl.fsb.off);
19141 			rack->r_ctl.fsb.o_m_len = rack->r_ctl.fsb.m->m_len;
19142 			rack->r_ctl.fsb.tcp_flags = flags;
19143 			rack->r_ctl.fsb.left_to_send = orig_len - len;
19144 			if (hw_tls)
19145 				rack->r_ctl.fsb.hw_tls = 1;
19146 			else
19147 				rack->r_ctl.fsb.hw_tls = 0;
19148 			KASSERT((rack->r_ctl.fsb.left_to_send <= (sbavail(sb) - (tp->snd_max - tp->snd_una))),
19149 				("rack:%p left_to_send:%u sbavail:%u out:%u",
19150 				 rack, rack->r_ctl.fsb.left_to_send, sbavail(sb),
19151 				 (tp->snd_max - tp->snd_una)));
19152 			if (rack->r_ctl.fsb.left_to_send < segsiz) {
19153 				rack->r_fast_output = 0;
19154 			}
19155 			if (rack->r_fast_output) {
19156 				if (rack->r_ctl.fsb.left_to_send == (sbavail(sb) - (tp->snd_max - tp->snd_una)))
19157 					rack->r_ctl.fsb.rfo_apply_push = 1;
19158 				else
19159 					rack->r_ctl.fsb.rfo_apply_push = 0;
19160 				rack_log_fsb(rack, tp, so, flags,
19161 					     ipoptlen, orig_len, len, error,
19162 					     (rsm == NULL), optlen, __LINE__, 3);
19163 				error = 0;
19164 				ret = rack_fast_output(tp, rack, ts_val, cts, ms_cts, &tv, tot_len_this_send, &error);
19165 				if (ret >= 0)
19166 					return (ret);
19167 			        else if (error)
19168 					goto nomore;
19169 
19170 			}
19171 		}
19172 		goto again;
19173 	} else if (len) {
19174 		counter_u64_add(rack_unpaced_segments, 1);
19175 	}
19176 	/* Assure when we leave that snd_nxt will point to top */
19177 	if (SEQ_GT(tp->snd_max, tp->snd_nxt))
19178 		tp->snd_nxt = tp->snd_max;
19179 	rack_start_hpts_timer(rack, tp, cts, slot, tot_len_this_send, 0);
19180 #ifdef TCP_ACCOUNTING
19181 	crtsc = get_cyclecount() - ts_val;
19182 	if (tot_len_this_send) {
19183 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19184 			tp->tcp_cnt_counters[SND_OUT_DATA]++;
19185 		}
19186 		counter_u64_add(tcp_cnt_counters[SND_OUT_DATA], 1);
19187 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19188 			tp->tcp_proc_time[SND_OUT_DATA] += crtsc;
19189 		}
19190 		counter_u64_add(tcp_proc_time[SND_OUT_DATA], crtsc);
19191 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19192 			tp->tcp_cnt_counters[CNT_OF_MSS_OUT] += ((tot_len_this_send + segsiz - 1) /segsiz);
19193 		}
19194 		counter_u64_add(tcp_cnt_counters[CNT_OF_MSS_OUT], ((tot_len_this_send + segsiz - 1) /segsiz));
19195 	} else {
19196 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19197 			tp->tcp_cnt_counters[SND_OUT_ACK]++;
19198 		}
19199 		counter_u64_add(tcp_cnt_counters[SND_OUT_ACK], 1);
19200 		if (tp->t_flags2 & TF2_TCP_ACCOUNTING) {
19201 			tp->tcp_proc_time[SND_OUT_ACK] += crtsc;
19202 		}
19203 		counter_u64_add(tcp_proc_time[SND_OUT_ACK], crtsc);
19204 	}
19205 	sched_unpin();
19206 #endif
19207 	if (error == ENOBUFS)
19208 		error = 0;
19209 	return (error);
19210 }
19211 
19212 static void
19213 rack_update_seg(struct tcp_rack *rack)
19214 {
19215 	uint32_t orig_val;
19216 
19217 	orig_val = rack->r_ctl.rc_pace_max_segs;
19218 	rack_set_pace_segments(rack->rc_tp, rack, __LINE__, NULL);
19219 	if (orig_val != rack->r_ctl.rc_pace_max_segs)
19220 		rack_log_pacing_delay_calc(rack, 0, 0, orig_val, 0, 0, 15, __LINE__, NULL, 0);
19221 }
19222 
19223 static void
19224 rack_mtu_change(struct tcpcb *tp)
19225 {
19226 	/*
19227 	 * The MSS may have changed
19228 	 */
19229 	struct tcp_rack *rack;
19230 
19231 	rack = (struct tcp_rack *)tp->t_fb_ptr;
19232 	if (rack->r_ctl.rc_pace_min_segs != ctf_fixed_maxseg(tp)) {
19233 		/*
19234 		 * The MTU has changed we need to resend everything
19235 		 * since all we have sent is lost. We first fix
19236 		 * up the mtu though.
19237 		 */
19238 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
19239 		/* We treat this like a full retransmit timeout without the cwnd adjustment */
19240 		rack_remxt_tmr(tp);
19241 		rack->r_fast_output = 0;
19242 		rack->r_ctl.rc_out_at_rto = ctf_flight_size(tp,
19243 						rack->r_ctl.rc_sacked);
19244 		rack->r_ctl.rc_snd_max_at_rto = tp->snd_max;
19245 		rack->r_must_retran = 1;
19246 
19247 	}
19248 	sack_filter_clear(&rack->r_ctl.rack_sf, tp->snd_una);
19249 	/* We don't use snd_nxt to retransmit */
19250 	tp->snd_nxt = tp->snd_max;
19251 }
19252 
19253 static int
19254 rack_set_profile(struct tcp_rack *rack, int prof)
19255 {
19256 	int err = EINVAL;
19257 	if (prof == 1) {
19258 		/* pace_always=1 */
19259 		if (rack->rc_always_pace == 0) {
19260 			if (tcp_can_enable_pacing() == 0)
19261 				return (EBUSY);
19262 		}
19263 		rack->rc_always_pace = 1;
19264 		if (rack->use_fixed_rate || rack->gp_ready)
19265 			rack_set_cc_pacing(rack);
19266 		rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19267 		rack->rack_attempt_hdwr_pace = 0;
19268 		/* cmpack=1 */
19269 		if (rack_use_cmp_acks)
19270 			rack->r_use_cmp_ack = 1;
19271 		if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state) &&
19272 		    rack->r_use_cmp_ack)
19273 			rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19274 		/* scwnd=1 */
19275 		rack->rack_enable_scwnd = 1;
19276 		/* dynamic=100 */
19277 		rack->rc_gp_dyn_mul = 1;
19278 		/* gp_inc_ca */
19279 		rack->r_ctl.rack_per_of_gp_ca = 100;
19280 		/* rrr_conf=3 */
19281 		rack->r_rr_config = 3;
19282 		/* npush=2 */
19283 		rack->r_ctl.rc_no_push_at_mrtt = 2;
19284 		/* fillcw=1 */
19285 		rack->rc_pace_to_cwnd = 1;
19286 		rack->rc_pace_fill_if_rttin_range = 0;
19287 		rack->rtt_limit_mul = 0;
19288 		/* noprr=1 */
19289 		rack->rack_no_prr = 1;
19290 		/* lscwnd=1 */
19291 		rack->r_limit_scw = 1;
19292 		/* gp_inc_rec */
19293 		rack->r_ctl.rack_per_of_gp_rec = 90;
19294 		err = 0;
19295 
19296 	} else if (prof == 3) {
19297 		/* Same as profile one execept fill_cw becomes 2 (less aggressive set) */
19298 		/* pace_always=1 */
19299 		if (rack->rc_always_pace == 0) {
19300 			if (tcp_can_enable_pacing() == 0)
19301 				return (EBUSY);
19302 		}
19303 		rack->rc_always_pace = 1;
19304 		if (rack->use_fixed_rate || rack->gp_ready)
19305 			rack_set_cc_pacing(rack);
19306 		rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19307 		rack->rack_attempt_hdwr_pace = 0;
19308 		/* cmpack=1 */
19309 		if (rack_use_cmp_acks)
19310 			rack->r_use_cmp_ack = 1;
19311 		if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state) &&
19312 		    rack->r_use_cmp_ack)
19313 			rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19314 		/* scwnd=1 */
19315 		rack->rack_enable_scwnd = 1;
19316 		/* dynamic=100 */
19317 		rack->rc_gp_dyn_mul = 1;
19318 		/* gp_inc_ca */
19319 		rack->r_ctl.rack_per_of_gp_ca = 100;
19320 		/* rrr_conf=3 */
19321 		rack->r_rr_config = 3;
19322 		/* npush=2 */
19323 		rack->r_ctl.rc_no_push_at_mrtt = 2;
19324 		/* fillcw=2 */
19325 		rack->rc_pace_to_cwnd = 1;
19326 		rack->r_fill_less_agg = 1;
19327 		rack->rc_pace_fill_if_rttin_range = 0;
19328 		rack->rtt_limit_mul = 0;
19329 		/* noprr=1 */
19330 		rack->rack_no_prr = 1;
19331 		/* lscwnd=1 */
19332 		rack->r_limit_scw = 1;
19333 		/* gp_inc_rec */
19334 		rack->r_ctl.rack_per_of_gp_rec = 90;
19335 		err = 0;
19336 
19337 
19338 	} else if (prof == 2) {
19339 		/* cmpack=1 */
19340 		if (rack->rc_always_pace == 0) {
19341 			if (tcp_can_enable_pacing() == 0)
19342 				return (EBUSY);
19343 		}
19344 		rack->rc_always_pace = 1;
19345 		if (rack->use_fixed_rate || rack->gp_ready)
19346 			rack_set_cc_pacing(rack);
19347 		rack->r_use_cmp_ack = 1;
19348 		if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state))
19349 			rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19350 		/* pace_always=1 */
19351 		rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19352 		/* scwnd=1 */
19353 		rack->rack_enable_scwnd = 1;
19354 		/* dynamic=100 */
19355 		rack->rc_gp_dyn_mul = 1;
19356 		rack->r_ctl.rack_per_of_gp_ca = 100;
19357 		/* rrr_conf=3 */
19358 		rack->r_rr_config = 3;
19359 		/* npush=2 */
19360 		rack->r_ctl.rc_no_push_at_mrtt = 2;
19361 		/* fillcw=1 */
19362 		rack->rc_pace_to_cwnd = 1;
19363 		rack->rc_pace_fill_if_rttin_range = 0;
19364 		rack->rtt_limit_mul = 0;
19365 		/* noprr=1 */
19366 		rack->rack_no_prr = 1;
19367 		/* lscwnd=0 */
19368 		rack->r_limit_scw = 0;
19369 		err = 0;
19370 	} else if (prof == 0) {
19371 		/* This changes things back to the default settings */
19372 		err = 0;
19373 		if (rack->rc_always_pace) {
19374 			tcp_decrement_paced_conn();
19375 			rack_undo_cc_pacing(rack);
19376 			rack->rc_always_pace = 0;
19377 		}
19378 		if (rack_pace_every_seg && tcp_can_enable_pacing()) {
19379 			rack->rc_always_pace = 1;
19380 			if (rack->use_fixed_rate || rack->gp_ready)
19381 				rack_set_cc_pacing(rack);
19382 		} else
19383 			rack->rc_always_pace = 0;
19384 		if (rack_dsack_std_based & 0x1) {
19385 			/* Basically this means all rack timers are at least (srtt + 1/4 srtt) */
19386 			rack->rc_rack_tmr_std_based = 1;
19387 		}
19388 		if (rack_dsack_std_based & 0x2) {
19389 			/* Basically this means  rack timers are extended based on dsack by up to (2 * srtt) */
19390 			rack->rc_rack_use_dsack = 1;
19391 		}
19392 		if (rack_use_cmp_acks)
19393 			rack->r_use_cmp_ack = 1;
19394 		else
19395 			rack->r_use_cmp_ack = 0;
19396 		if (rack_disable_prr)
19397 			rack->rack_no_prr = 1;
19398 		else
19399 			rack->rack_no_prr = 0;
19400 		if (rack_gp_no_rec_chg)
19401 			rack->rc_gp_no_rec_chg = 1;
19402 		else
19403 			rack->rc_gp_no_rec_chg = 0;
19404 		if (rack_enable_mqueue_for_nonpaced || rack->r_use_cmp_ack) {
19405 			rack->r_mbuf_queue = 1;
19406 			if (TCPS_HAVEESTABLISHED(rack->rc_tp->t_state))
19407 				rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19408 			rack->rc_inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19409 		} else {
19410 			rack->r_mbuf_queue = 0;
19411 			rack->rc_inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19412 		}
19413 		if (rack_enable_shared_cwnd)
19414 			rack->rack_enable_scwnd = 1;
19415 		else
19416 			rack->rack_enable_scwnd = 0;
19417 		if (rack_do_dyn_mul) {
19418 			/* When dynamic adjustment is on CA needs to start at 100% */
19419 			rack->rc_gp_dyn_mul = 1;
19420 			if (rack_do_dyn_mul >= 100)
19421 				rack->r_ctl.rack_per_of_gp_ca = rack_do_dyn_mul;
19422 		} else {
19423 			rack->r_ctl.rack_per_of_gp_ca = rack_per_of_gp_ca;
19424 			rack->rc_gp_dyn_mul = 0;
19425 		}
19426 		rack->r_rr_config = 0;
19427 		rack->r_ctl.rc_no_push_at_mrtt = 0;
19428 		rack->rc_pace_to_cwnd = 0;
19429 		rack->rc_pace_fill_if_rttin_range = 0;
19430 		rack->rtt_limit_mul = 0;
19431 
19432 		if (rack_enable_hw_pacing)
19433 			rack->rack_hdw_pace_ena = 1;
19434 		else
19435 			rack->rack_hdw_pace_ena = 0;
19436 		if (rack_disable_prr)
19437 			rack->rack_no_prr = 1;
19438 		else
19439 			rack->rack_no_prr = 0;
19440 		if (rack_limits_scwnd)
19441 			rack->r_limit_scw  = 1;
19442 		else
19443 			rack->r_limit_scw  = 0;
19444 		err = 0;
19445 	}
19446 	return (err);
19447 }
19448 
19449 static int
19450 rack_add_deferred_option(struct tcp_rack *rack, int sopt_name, uint64_t loptval)
19451 {
19452 	struct deferred_opt_list *dol;
19453 
19454 	dol = malloc(sizeof(struct deferred_opt_list),
19455 		     M_TCPFSB, M_NOWAIT|M_ZERO);
19456 	if (dol == NULL) {
19457 		/*
19458 		 * No space yikes -- fail out..
19459 		 */
19460 		return (0);
19461 	}
19462 	dol->optname = sopt_name;
19463 	dol->optval = loptval;
19464 	TAILQ_INSERT_TAIL(&rack->r_ctl.opt_list, dol, next);
19465 	return (1);
19466 }
19467 
19468 static int
19469 rack_process_option(struct tcpcb *tp, struct tcp_rack *rack, int sopt_name,
19470 		    uint32_t optval, uint64_t loptval)
19471 {
19472 	struct epoch_tracker et;
19473 	struct sockopt sopt;
19474 	struct cc_newreno_opts opt;
19475 	uint64_t val;
19476 	int error = 0;
19477 	uint16_t ca, ss;
19478 
19479 	switch (sopt_name) {
19480 
19481 	case TCP_RACK_DSACK_OPT:
19482 		RACK_OPTS_INC(tcp_rack_dsack_opt);
19483 		if (optval & 0x1) {
19484 			rack->rc_rack_tmr_std_based = 1;
19485 		} else {
19486 			rack->rc_rack_tmr_std_based = 0;
19487 		}
19488 		if (optval & 0x2) {
19489 			rack->rc_rack_use_dsack = 1;
19490 		} else {
19491 			rack->rc_rack_use_dsack = 0;
19492 		}
19493 		rack_log_dsack_event(rack, 5, __LINE__, 0, 0);
19494 		break;
19495 	case TCP_RACK_PACING_BETA:
19496 		RACK_OPTS_INC(tcp_rack_beta);
19497 		if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
19498 			/* This only works for newreno. */
19499 			error = EINVAL;
19500 			break;
19501 		}
19502 		if (rack->rc_pacing_cc_set) {
19503 			/*
19504 			 * Set them into the real CC module
19505 			 * whats in the rack pcb is the old values
19506 			 * to be used on restoral/
19507 			 */
19508 			sopt.sopt_dir = SOPT_SET;
19509 			opt.name = CC_NEWRENO_BETA;
19510 			opt.val = optval;
19511 			if (CC_ALGO(tp)->ctl_output != NULL)
19512 				error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
19513 			else {
19514 				error = ENOENT;
19515 				break;
19516 			}
19517 		} else {
19518 			/*
19519 			 * Not pacing yet so set it into our local
19520 			 * rack pcb storage.
19521 			 */
19522 			rack->r_ctl.rc_saved_beta.beta = optval;
19523 		}
19524 		break;
19525 	case TCP_RACK_TIMER_SLOP:
19526 		RACK_OPTS_INC(tcp_rack_timer_slop);
19527 		rack->r_ctl.timer_slop = optval;
19528 		if (rack->rc_tp->t_srtt) {
19529 			/*
19530 			 * If we have an SRTT lets update t_rxtcur
19531 			 * to have the new slop.
19532 			 */
19533 			RACK_TCPT_RANGESET(tp->t_rxtcur, RACK_REXMTVAL(tp),
19534 					   rack_rto_min, rack_rto_max,
19535 					   rack->r_ctl.timer_slop);
19536 		}
19537 		break;
19538 	case TCP_RACK_PACING_BETA_ECN:
19539 		RACK_OPTS_INC(tcp_rack_beta_ecn);
19540 		if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0) {
19541 			/* This only works for newreno. */
19542 			error = EINVAL;
19543 			break;
19544 		}
19545 		if (rack->rc_pacing_cc_set) {
19546 			/*
19547 			 * Set them into the real CC module
19548 			 * whats in the rack pcb is the old values
19549 			 * to be used on restoral/
19550 			 */
19551 			sopt.sopt_dir = SOPT_SET;
19552 			opt.name = CC_NEWRENO_BETA_ECN;
19553 			opt.val = optval;
19554 			if (CC_ALGO(tp)->ctl_output != NULL)
19555 				error = CC_ALGO(tp)->ctl_output(tp->ccv, &sopt, &opt);
19556 			else
19557 				error = ENOENT;
19558 		} else {
19559 			/*
19560 			 * Not pacing yet so set it into our local
19561 			 * rack pcb storage.
19562 			 */
19563 			rack->r_ctl.rc_saved_beta.beta_ecn = optval;
19564 			rack->r_ctl.rc_saved_beta.newreno_flags = CC_NEWRENO_BETA_ECN;
19565 		}
19566 		break;
19567 	case TCP_DEFER_OPTIONS:
19568 		RACK_OPTS_INC(tcp_defer_opt);
19569 		if (optval) {
19570 			if (rack->gp_ready) {
19571 				/* Too late */
19572 				error = EINVAL;
19573 				break;
19574 			}
19575 			rack->defer_options = 1;
19576 		} else
19577 			rack->defer_options = 0;
19578 		break;
19579 	case TCP_RACK_MEASURE_CNT:
19580 		RACK_OPTS_INC(tcp_rack_measure_cnt);
19581 		if (optval && (optval <= 0xff)) {
19582 			rack->r_ctl.req_measurements = optval;
19583 		} else
19584 			error = EINVAL;
19585 		break;
19586 	case TCP_REC_ABC_VAL:
19587 		RACK_OPTS_INC(tcp_rec_abc_val);
19588 		if (optval > 0)
19589 			rack->r_use_labc_for_rec = 1;
19590 		else
19591 			rack->r_use_labc_for_rec = 0;
19592 		break;
19593 	case TCP_RACK_ABC_VAL:
19594 		RACK_OPTS_INC(tcp_rack_abc_val);
19595 		if ((optval > 0) && (optval < 255))
19596 			rack->rc_labc = optval;
19597 		else
19598 			error = EINVAL;
19599 		break;
19600 	case TCP_HDWR_UP_ONLY:
19601 		RACK_OPTS_INC(tcp_pacing_up_only);
19602 		if (optval)
19603 			rack->r_up_only = 1;
19604 		else
19605 			rack->r_up_only = 0;
19606 		break;
19607 	case TCP_PACING_RATE_CAP:
19608 		RACK_OPTS_INC(tcp_pacing_rate_cap);
19609 		rack->r_ctl.bw_rate_cap = loptval;
19610 		break;
19611 	case TCP_RACK_PROFILE:
19612 		RACK_OPTS_INC(tcp_profile);
19613 		error = rack_set_profile(rack, optval);
19614 		break;
19615 	case TCP_USE_CMP_ACKS:
19616 		RACK_OPTS_INC(tcp_use_cmp_acks);
19617 		if ((optval == 0) && (rack->rc_inp->inp_flags2 & INP_MBUF_ACKCMP)) {
19618 			/* You can't turn it off once its on! */
19619 			error = EINVAL;
19620 		} else if ((optval == 1) && (rack->r_use_cmp_ack == 0)) {
19621 			rack->r_use_cmp_ack = 1;
19622 			rack->r_mbuf_queue = 1;
19623 			tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19624 		}
19625 		if (rack->r_use_cmp_ack && TCPS_HAVEESTABLISHED(tp->t_state))
19626 			rack->rc_inp->inp_flags2 |= INP_MBUF_ACKCMP;
19627 		break;
19628 	case TCP_SHARED_CWND_TIME_LIMIT:
19629 		RACK_OPTS_INC(tcp_lscwnd);
19630 		if (optval)
19631 			rack->r_limit_scw = 1;
19632 		else
19633 			rack->r_limit_scw = 0;
19634 		break;
19635  	case TCP_RACK_PACE_TO_FILL:
19636 		RACK_OPTS_INC(tcp_fillcw);
19637 		if (optval == 0)
19638 			rack->rc_pace_to_cwnd = 0;
19639 		else {
19640 			rack->rc_pace_to_cwnd = 1;
19641 			if (optval > 1)
19642 				rack->r_fill_less_agg = 1;
19643 		}
19644 		if ((optval >= rack_gp_rtt_maxmul) &&
19645 		    rack_gp_rtt_maxmul &&
19646 		    (optval < 0xf)) {
19647 			rack->rc_pace_fill_if_rttin_range = 1;
19648 			rack->rtt_limit_mul = optval;
19649 		} else {
19650 			rack->rc_pace_fill_if_rttin_range = 0;
19651 			rack->rtt_limit_mul = 0;
19652 		}
19653 		break;
19654 	case TCP_RACK_NO_PUSH_AT_MAX:
19655 		RACK_OPTS_INC(tcp_npush);
19656 		if (optval == 0)
19657 			rack->r_ctl.rc_no_push_at_mrtt = 0;
19658 		else if (optval < 0xff)
19659 			rack->r_ctl.rc_no_push_at_mrtt = optval;
19660 		else
19661 			error = EINVAL;
19662 		break;
19663 	case TCP_SHARED_CWND_ENABLE:
19664 		RACK_OPTS_INC(tcp_rack_scwnd);
19665 		if (optval == 0)
19666 			rack->rack_enable_scwnd = 0;
19667 		else
19668 			rack->rack_enable_scwnd = 1;
19669 		break;
19670 	case TCP_RACK_MBUF_QUEUE:
19671 		/* Now do we use the LRO mbuf-queue feature */
19672 		RACK_OPTS_INC(tcp_rack_mbufq);
19673 		if (optval || rack->r_use_cmp_ack)
19674 			rack->r_mbuf_queue = 1;
19675 		else
19676 			rack->r_mbuf_queue = 0;
19677 		if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
19678 			tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19679 		else
19680 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19681 		break;
19682 	case TCP_RACK_NONRXT_CFG_RATE:
19683 		RACK_OPTS_INC(tcp_rack_cfg_rate);
19684 		if (optval == 0)
19685 			rack->rack_rec_nonrxt_use_cr = 0;
19686 		else
19687 			rack->rack_rec_nonrxt_use_cr = 1;
19688 		break;
19689 	case TCP_NO_PRR:
19690 		RACK_OPTS_INC(tcp_rack_noprr);
19691 		if (optval == 0)
19692 			rack->rack_no_prr = 0;
19693 		else if (optval == 1)
19694 			rack->rack_no_prr = 1;
19695 		else if (optval == 2)
19696 			rack->no_prr_addback = 1;
19697 		else
19698 			error = EINVAL;
19699 		break;
19700 	case TCP_TIMELY_DYN_ADJ:
19701 		RACK_OPTS_INC(tcp_timely_dyn);
19702 		if (optval == 0)
19703 			rack->rc_gp_dyn_mul = 0;
19704 		else {
19705 			rack->rc_gp_dyn_mul = 1;
19706 			if (optval >= 100) {
19707 				/*
19708 				 * If the user sets something 100 or more
19709 				 * its the gp_ca value.
19710 				 */
19711 				rack->r_ctl.rack_per_of_gp_ca  = optval;
19712 			}
19713 		}
19714 		break;
19715 	case TCP_RACK_DO_DETECTION:
19716 		RACK_OPTS_INC(tcp_rack_do_detection);
19717 		if (optval == 0)
19718 			rack->do_detection = 0;
19719 		else
19720 			rack->do_detection = 1;
19721 		break;
19722 	case TCP_RACK_TLP_USE:
19723 		if ((optval < TLP_USE_ID) || (optval > TLP_USE_TWO_TWO)) {
19724 			error = EINVAL;
19725 			break;
19726 		}
19727 		RACK_OPTS_INC(tcp_tlp_use);
19728 		rack->rack_tlp_threshold_use = optval;
19729 		break;
19730 	case TCP_RACK_TLP_REDUCE:
19731 		/* RACK TLP cwnd reduction (bool) */
19732 		RACK_OPTS_INC(tcp_rack_tlp_reduce);
19733 		rack->r_ctl.rc_tlp_cwnd_reduce = optval;
19734 		break;
19735 	/*  Pacing related ones */
19736 	case TCP_RACK_PACE_ALWAYS:
19737 		/*
19738 		 * zero is old rack method, 1 is new
19739 		 * method using a pacing rate.
19740 		 */
19741 		RACK_OPTS_INC(tcp_rack_pace_always);
19742 		if (optval > 0) {
19743 			if (rack->rc_always_pace) {
19744 				error = EALREADY;
19745 				break;
19746 			} else if (tcp_can_enable_pacing()) {
19747 				rack->rc_always_pace = 1;
19748 				if (rack->use_fixed_rate || rack->gp_ready)
19749 					rack_set_cc_pacing(rack);
19750 			}
19751 			else {
19752 				error = ENOSPC;
19753 				break;
19754 			}
19755 		} else {
19756 			if (rack->rc_always_pace) {
19757 				tcp_decrement_paced_conn();
19758 				rack->rc_always_pace = 0;
19759 				rack_undo_cc_pacing(rack);
19760 			}
19761 		}
19762 		if  (rack->r_mbuf_queue || rack->rc_always_pace || rack->r_use_cmp_ack)
19763 			tp->t_inpcb->inp_flags2 |= INP_SUPPORTS_MBUFQ;
19764 		else
19765 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
19766 		/* A rate may be set irate or other, if so set seg size */
19767 		rack_update_seg(rack);
19768 		break;
19769 	case TCP_BBR_RACK_INIT_RATE:
19770 		RACK_OPTS_INC(tcp_initial_rate);
19771 		val = optval;
19772 		/* Change from kbits per second to bytes per second */
19773 		val *= 1000;
19774 		val /= 8;
19775 		rack->r_ctl.init_rate = val;
19776 		if (rack->rc_init_win != rack_default_init_window) {
19777 			uint32_t win, snt;
19778 
19779 			/*
19780 			 * Options don't always get applied
19781 			 * in the order you think. So in order
19782 			 * to assure we update a cwnd we need
19783 			 * to check and see if we are still
19784 			 * where we should raise the cwnd.
19785 			 */
19786 			win = rc_init_window(rack);
19787 			if (SEQ_GT(tp->snd_max, tp->iss))
19788 				snt = tp->snd_max - tp->iss;
19789 			else
19790 				snt = 0;
19791 			if ((snt < win) &&
19792 			    (tp->snd_cwnd < win))
19793 				tp->snd_cwnd = win;
19794 		}
19795 		if (rack->rc_always_pace)
19796 			rack_update_seg(rack);
19797 		break;
19798 	case TCP_BBR_IWINTSO:
19799 		RACK_OPTS_INC(tcp_initial_win);
19800 		if (optval && (optval <= 0xff)) {
19801 			uint32_t win, snt;
19802 
19803 			rack->rc_init_win = optval;
19804 			win = rc_init_window(rack);
19805 			if (SEQ_GT(tp->snd_max, tp->iss))
19806 				snt = tp->snd_max - tp->iss;
19807 			else
19808 				snt = 0;
19809 			if ((snt < win) &&
19810 			    (tp->t_srtt |
19811 #ifdef NETFLIX_PEAKRATE
19812 			     tp->t_maxpeakrate |
19813 #endif
19814 			     rack->r_ctl.init_rate)) {
19815 				/*
19816 				 * We are not past the initial window
19817 				 * and we have some bases for pacing,
19818 				 * so we need to possibly adjust up
19819 				 * the cwnd. Note even if we don't set
19820 				 * the cwnd, its still ok to raise the rc_init_win
19821 				 * which can be used coming out of idle when we
19822 				 * would have a rate.
19823 				 */
19824 				if (tp->snd_cwnd < win)
19825 					tp->snd_cwnd = win;
19826 			}
19827 			if (rack->rc_always_pace)
19828 				rack_update_seg(rack);
19829 		} else
19830 			error = EINVAL;
19831 		break;
19832 	case TCP_RACK_FORCE_MSEG:
19833 		RACK_OPTS_INC(tcp_rack_force_max_seg);
19834 		if (optval)
19835 			rack->rc_force_max_seg = 1;
19836 		else
19837 			rack->rc_force_max_seg = 0;
19838 		break;
19839 	case TCP_RACK_PACE_MAX_SEG:
19840 		/* Max segments size in a pace in bytes */
19841 		RACK_OPTS_INC(tcp_rack_max_seg);
19842 		rack->rc_user_set_max_segs = optval;
19843 		rack_set_pace_segments(tp, rack, __LINE__, NULL);
19844 		break;
19845 	case TCP_RACK_PACE_RATE_REC:
19846 		/* Set the fixed pacing rate in Bytes per second ca */
19847 		RACK_OPTS_INC(tcp_rack_pace_rate_rec);
19848 		rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
19849 		if (rack->r_ctl.rc_fixed_pacing_rate_ca == 0)
19850 			rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
19851 		if (rack->r_ctl.rc_fixed_pacing_rate_ss == 0)
19852 			rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
19853 		rack->use_fixed_rate = 1;
19854 		if (rack->rc_always_pace)
19855 			rack_set_cc_pacing(rack);
19856 		rack_log_pacing_delay_calc(rack,
19857 					   rack->r_ctl.rc_fixed_pacing_rate_ss,
19858 					   rack->r_ctl.rc_fixed_pacing_rate_ca,
19859 					   rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
19860 					   __LINE__, NULL,0);
19861 		break;
19862 
19863 	case TCP_RACK_PACE_RATE_SS:
19864 		/* Set the fixed pacing rate in Bytes per second ca */
19865 		RACK_OPTS_INC(tcp_rack_pace_rate_ss);
19866 		rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
19867 		if (rack->r_ctl.rc_fixed_pacing_rate_ca == 0)
19868 			rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
19869 		if (rack->r_ctl.rc_fixed_pacing_rate_rec == 0)
19870 			rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
19871 		rack->use_fixed_rate = 1;
19872 		if (rack->rc_always_pace)
19873 			rack_set_cc_pacing(rack);
19874 		rack_log_pacing_delay_calc(rack,
19875 					   rack->r_ctl.rc_fixed_pacing_rate_ss,
19876 					   rack->r_ctl.rc_fixed_pacing_rate_ca,
19877 					   rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
19878 					   __LINE__, NULL, 0);
19879 		break;
19880 
19881 	case TCP_RACK_PACE_RATE_CA:
19882 		/* Set the fixed pacing rate in Bytes per second ca */
19883 		RACK_OPTS_INC(tcp_rack_pace_rate_ca);
19884 		rack->r_ctl.rc_fixed_pacing_rate_ca = optval;
19885 		if (rack->r_ctl.rc_fixed_pacing_rate_ss == 0)
19886 			rack->r_ctl.rc_fixed_pacing_rate_ss = optval;
19887 		if (rack->r_ctl.rc_fixed_pacing_rate_rec == 0)
19888 			rack->r_ctl.rc_fixed_pacing_rate_rec = optval;
19889 		rack->use_fixed_rate = 1;
19890 		if (rack->rc_always_pace)
19891 			rack_set_cc_pacing(rack);
19892 		rack_log_pacing_delay_calc(rack,
19893 					   rack->r_ctl.rc_fixed_pacing_rate_ss,
19894 					   rack->r_ctl.rc_fixed_pacing_rate_ca,
19895 					   rack->r_ctl.rc_fixed_pacing_rate_rec, 0, 0, 8,
19896 					   __LINE__, NULL, 0);
19897 		break;
19898 	case TCP_RACK_GP_INCREASE_REC:
19899 		RACK_OPTS_INC(tcp_gp_inc_rec);
19900 		rack->r_ctl.rack_per_of_gp_rec = optval;
19901 		rack_log_pacing_delay_calc(rack,
19902 					   rack->r_ctl.rack_per_of_gp_ss,
19903 					   rack->r_ctl.rack_per_of_gp_ca,
19904 					   rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
19905 					   __LINE__, NULL, 0);
19906 		break;
19907 	case TCP_RACK_GP_INCREASE_CA:
19908 		RACK_OPTS_INC(tcp_gp_inc_ca);
19909 		ca = optval;
19910 		if (ca < 100) {
19911 			/*
19912 			 * We don't allow any reduction
19913 			 * over the GP b/w.
19914 			 */
19915 			error = EINVAL;
19916 			break;
19917 		}
19918 		rack->r_ctl.rack_per_of_gp_ca = ca;
19919 		rack_log_pacing_delay_calc(rack,
19920 					   rack->r_ctl.rack_per_of_gp_ss,
19921 					   rack->r_ctl.rack_per_of_gp_ca,
19922 					   rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
19923 					   __LINE__, NULL, 0);
19924 		break;
19925 	case TCP_RACK_GP_INCREASE_SS:
19926 		RACK_OPTS_INC(tcp_gp_inc_ss);
19927 		ss = optval;
19928 		if (ss < 100) {
19929 			/*
19930 			 * We don't allow any reduction
19931 			 * over the GP b/w.
19932 			 */
19933 			error = EINVAL;
19934 			break;
19935 		}
19936 		rack->r_ctl.rack_per_of_gp_ss = ss;
19937 		rack_log_pacing_delay_calc(rack,
19938 					   rack->r_ctl.rack_per_of_gp_ss,
19939 					   rack->r_ctl.rack_per_of_gp_ca,
19940 					   rack->r_ctl.rack_per_of_gp_rec, 0, 0, 1,
19941 					   __LINE__, NULL, 0);
19942 		break;
19943 	case TCP_RACK_RR_CONF:
19944 		RACK_OPTS_INC(tcp_rack_rrr_no_conf_rate);
19945 		if (optval && optval <= 3)
19946 			rack->r_rr_config = optval;
19947 		else
19948 			rack->r_rr_config = 0;
19949 		break;
19950 	case TCP_HDWR_RATE_CAP:
19951 		RACK_OPTS_INC(tcp_hdwr_rate_cap);
19952 		if (optval) {
19953 			if (rack->r_rack_hw_rate_caps == 0)
19954 				rack->r_rack_hw_rate_caps = 1;
19955 			else
19956 				error = EALREADY;
19957 		} else {
19958 			rack->r_rack_hw_rate_caps = 0;
19959 		}
19960 		break;
19961 	case TCP_BBR_HDWR_PACE:
19962 		RACK_OPTS_INC(tcp_hdwr_pacing);
19963 		if (optval){
19964 			if (rack->rack_hdrw_pacing == 0) {
19965 				rack->rack_hdw_pace_ena = 1;
19966 				rack->rack_attempt_hdwr_pace = 0;
19967 			} else
19968 				error = EALREADY;
19969 		} else {
19970 			rack->rack_hdw_pace_ena = 0;
19971 #ifdef RATELIMIT
19972 			if (rack->r_ctl.crte != NULL) {
19973 				rack->rack_hdrw_pacing = 0;
19974 				rack->rack_attempt_hdwr_pace = 0;
19975 				tcp_rel_pacing_rate(rack->r_ctl.crte, tp);
19976 				rack->r_ctl.crte = NULL;
19977 			}
19978 #endif
19979 		}
19980 		break;
19981 	/*  End Pacing related ones */
19982 	case TCP_RACK_PRR_SENDALOT:
19983 		/* Allow PRR to send more than one seg */
19984 		RACK_OPTS_INC(tcp_rack_prr_sendalot);
19985 		rack->r_ctl.rc_prr_sendalot = optval;
19986 		break;
19987 	case TCP_RACK_MIN_TO:
19988 		/* Minimum time between rack t-o's in ms */
19989 		RACK_OPTS_INC(tcp_rack_min_to);
19990 		rack->r_ctl.rc_min_to = optval;
19991 		break;
19992 	case TCP_RACK_EARLY_SEG:
19993 		/* If early recovery max segments */
19994 		RACK_OPTS_INC(tcp_rack_early_seg);
19995 		rack->r_ctl.rc_early_recovery_segs = optval;
19996 		break;
19997 	case TCP_RACK_REORD_THRESH:
19998 		/* RACK reorder threshold (shift amount) */
19999 		RACK_OPTS_INC(tcp_rack_reord_thresh);
20000 		if ((optval > 0) && (optval < 31))
20001 			rack->r_ctl.rc_reorder_shift = optval;
20002 		else
20003 			error = EINVAL;
20004 		break;
20005 	case TCP_RACK_REORD_FADE:
20006 		/* Does reordering fade after ms time */
20007 		RACK_OPTS_INC(tcp_rack_reord_fade);
20008 		rack->r_ctl.rc_reorder_fade = optval;
20009 		break;
20010 	case TCP_RACK_TLP_THRESH:
20011 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
20012 		RACK_OPTS_INC(tcp_rack_tlp_thresh);
20013 		if (optval)
20014 			rack->r_ctl.rc_tlp_threshold = optval;
20015 		else
20016 			error = EINVAL;
20017 		break;
20018 	case TCP_BBR_USE_RACK_RR:
20019 		RACK_OPTS_INC(tcp_rack_rr);
20020 		if (optval)
20021 			rack->use_rack_rr = 1;
20022 		else
20023 			rack->use_rack_rr = 0;
20024 		break;
20025 	case TCP_FAST_RSM_HACK:
20026 		RACK_OPTS_INC(tcp_rack_fastrsm_hack);
20027 		if (optval)
20028 			rack->fast_rsm_hack = 1;
20029 		else
20030 			rack->fast_rsm_hack = 0;
20031 		break;
20032 	case TCP_RACK_PKT_DELAY:
20033 		/* RACK added ms i.e. rack-rtt + reord + N */
20034 		RACK_OPTS_INC(tcp_rack_pkt_delay);
20035 		rack->r_ctl.rc_pkt_delay = optval;
20036 		break;
20037 	case TCP_DELACK:
20038 		RACK_OPTS_INC(tcp_rack_delayed_ack);
20039 		if (optval == 0)
20040 			tp->t_delayed_ack = 0;
20041 		else
20042 			tp->t_delayed_ack = 1;
20043 		if (tp->t_flags & TF_DELACK) {
20044 			tp->t_flags &= ~TF_DELACK;
20045 			tp->t_flags |= TF_ACKNOW;
20046 			NET_EPOCH_ENTER(et);
20047 			rack_output(tp);
20048 			NET_EPOCH_EXIT(et);
20049 		}
20050 		break;
20051 
20052 	case TCP_BBR_RACK_RTT_USE:
20053 		RACK_OPTS_INC(tcp_rack_rtt_use);
20054 		if ((optval != USE_RTT_HIGH) &&
20055 		    (optval != USE_RTT_LOW) &&
20056 		    (optval != USE_RTT_AVG))
20057 			error = EINVAL;
20058 		else
20059 			rack->r_ctl.rc_rate_sample_method = optval;
20060 		break;
20061 	case TCP_DATA_AFTER_CLOSE:
20062 		RACK_OPTS_INC(tcp_data_after_close);
20063 		if (optval)
20064 			rack->rc_allow_data_af_clo = 1;
20065 		else
20066 			rack->rc_allow_data_af_clo = 0;
20067 		break;
20068 	default:
20069 		break;
20070 	}
20071 #ifdef NETFLIX_STATS
20072 	tcp_log_socket_option(tp, sopt_name, optval, error);
20073 #endif
20074 	return (error);
20075 }
20076 
20077 
20078 static void
20079 rack_apply_deferred_options(struct tcp_rack *rack)
20080 {
20081 	struct deferred_opt_list *dol, *sdol;
20082 	uint32_t s_optval;
20083 
20084 	TAILQ_FOREACH_SAFE(dol, &rack->r_ctl.opt_list, next, sdol) {
20085 		TAILQ_REMOVE(&rack->r_ctl.opt_list, dol, next);
20086 		/* Disadvantage of deferal is you loose the error return */
20087 		s_optval = (uint32_t)dol->optval;
20088 		(void)rack_process_option(rack->rc_tp, rack, dol->optname, s_optval, dol->optval);
20089 		free(dol, M_TCPDO);
20090 	}
20091 }
20092 
20093 static void
20094 rack_hw_tls_change(struct tcpcb *tp, int chg)
20095 {
20096 	/*
20097 	 * HW tls state has changed.. fix all
20098 	 * rsm's in flight.
20099 	 */
20100 	struct tcp_rack *rack;
20101 	struct rack_sendmap *rsm;
20102 
20103 	rack = (struct tcp_rack *)tp->t_fb_ptr;
20104 	RB_FOREACH(rsm, rack_rb_tree_head, &rack->r_ctl.rc_mtree) {
20105 		if (chg)
20106 			rsm->r_hw_tls = 1;
20107 		else
20108 			rsm->r_hw_tls = 0;
20109 	}
20110 	if (chg)
20111 		rack->r_ctl.fsb.hw_tls = 1;
20112 	else
20113 		rack->r_ctl.fsb.hw_tls = 0;
20114 }
20115 
20116 static int
20117 rack_pru_options(struct tcpcb *tp, int flags)
20118 {
20119 	if (flags & PRUS_OOB)
20120 		return (EOPNOTSUPP);
20121 	return (0);
20122 }
20123 
20124 static struct tcp_function_block __tcp_rack = {
20125 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
20126 	.tfb_tcp_output = rack_output,
20127 	.tfb_do_queued_segments = ctf_do_queued_segments,
20128 	.tfb_do_segment_nounlock = rack_do_segment_nounlock,
20129 	.tfb_tcp_do_segment = rack_do_segment,
20130 	.tfb_tcp_ctloutput = rack_ctloutput,
20131 	.tfb_tcp_fb_init = rack_init,
20132 	.tfb_tcp_fb_fini = rack_fini,
20133 	.tfb_tcp_timer_stop_all = rack_stopall,
20134 	.tfb_tcp_timer_activate = rack_timer_activate,
20135 	.tfb_tcp_timer_active = rack_timer_active,
20136 	.tfb_tcp_timer_stop = rack_timer_stop,
20137 	.tfb_tcp_rexmit_tmr = rack_remxt_tmr,
20138 	.tfb_tcp_handoff_ok = rack_handoff_ok,
20139 	.tfb_tcp_mtu_chg = rack_mtu_change,
20140 	.tfb_pru_options = rack_pru_options,
20141 	.tfb_hwtls_change = rack_hw_tls_change,
20142 };
20143 
20144 /*
20145  * rack_ctloutput() must drop the inpcb lock before performing copyin on
20146  * socket option arguments.  When it re-acquires the lock after the copy, it
20147  * has to revalidate that the connection is still valid for the socket
20148  * option.
20149  */
20150 static int
20151 rack_set_sockopt(struct socket *so, struct sockopt *sopt,
20152     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
20153 {
20154 	uint64_t loptval;
20155 	int32_t error = 0, optval;
20156 
20157 	switch (sopt->sopt_name) {
20158 	case TCP_RACK_TLP_REDUCE:		/*  URL:tlp_reduce */
20159 	/*  Pacing related ones */
20160 	case TCP_RACK_PACE_ALWAYS:		/*  URL:pace_always */
20161 	case TCP_BBR_RACK_INIT_RATE:		/*  URL:irate */
20162 	case TCP_BBR_IWINTSO:			/*  URL:tso_iwin */
20163 	case TCP_RACK_PACE_MAX_SEG:		/*  URL:pace_max_seg */
20164 	case TCP_RACK_FORCE_MSEG:		/*  URL:force_max_seg */
20165 	case TCP_RACK_PACE_RATE_CA:		/*  URL:pr_ca */
20166 	case TCP_RACK_PACE_RATE_SS:		/*  URL:pr_ss*/
20167 	case TCP_RACK_PACE_RATE_REC:		/*  URL:pr_rec */
20168 	case TCP_RACK_GP_INCREASE_CA:		/*  URL:gp_inc_ca */
20169 	case TCP_RACK_GP_INCREASE_SS:		/*  URL:gp_inc_ss */
20170 	case TCP_RACK_GP_INCREASE_REC:		/*  URL:gp_inc_rec */
20171 	case TCP_RACK_RR_CONF:			/*  URL:rrr_conf */
20172 	case TCP_BBR_HDWR_PACE:			/*  URL:hdwrpace */
20173 	case TCP_HDWR_RATE_CAP:			/*  URL:hdwrcap boolean */
20174 	case TCP_PACING_RATE_CAP:		/*  URL:cap  -- used by side-channel */
20175 	case TCP_HDWR_UP_ONLY:			/*  URL:uponly -- hardware pacing  boolean */
20176        /* End pacing related */
20177 	case TCP_FAST_RSM_HACK:			/*  URL:frsm_hack */
20178 	case TCP_DELACK:			/*  URL:delack (in base TCP i.e. tcp_hints along with cc etc ) */
20179 	case TCP_RACK_PRR_SENDALOT:		/*  URL:prr_sendalot */
20180 	case TCP_RACK_MIN_TO:			/*  URL:min_to */
20181 	case TCP_RACK_EARLY_SEG:		/*  URL:early_seg */
20182 	case TCP_RACK_REORD_THRESH:		/*  URL:reord_thresh */
20183 	case TCP_RACK_REORD_FADE:		/*  URL:reord_fade */
20184 	case TCP_RACK_TLP_THRESH:		/*  URL:tlp_thresh */
20185 	case TCP_RACK_PKT_DELAY:		/*  URL:pkt_delay */
20186 	case TCP_RACK_TLP_USE:			/*  URL:tlp_use */
20187 	case TCP_BBR_RACK_RTT_USE:		/*  URL:rttuse */
20188 	case TCP_BBR_USE_RACK_RR:		/*  URL:rackrr */
20189 	case TCP_RACK_DO_DETECTION:		/*  URL:detect */
20190 	case TCP_NO_PRR:			/*  URL:noprr */
20191 	case TCP_TIMELY_DYN_ADJ:      		/*  URL:dynamic */
20192 	case TCP_DATA_AFTER_CLOSE:		/*  no URL */
20193 	case TCP_RACK_NONRXT_CFG_RATE:		/*  URL:nonrxtcr */
20194 	case TCP_SHARED_CWND_ENABLE:		/*  URL:scwnd */
20195 	case TCP_RACK_MBUF_QUEUE:		/*  URL:mqueue */
20196 	case TCP_RACK_NO_PUSH_AT_MAX:		/*  URL:npush */
20197 	case TCP_RACK_PACE_TO_FILL:		/*  URL:fillcw */
20198 	case TCP_SHARED_CWND_TIME_LIMIT:	/*  URL:lscwnd */
20199 	case TCP_RACK_PROFILE:			/*  URL:profile */
20200 	case TCP_USE_CMP_ACKS:			/*  URL:cmpack */
20201 	case TCP_RACK_ABC_VAL:			/*  URL:labc */
20202 	case TCP_REC_ABC_VAL:			/*  URL:reclabc */
20203 	case TCP_RACK_MEASURE_CNT:		/*  URL:measurecnt */
20204 	case TCP_DEFER_OPTIONS:			/*  URL:defer */
20205 	case TCP_RACK_DSACK_OPT:		/*  URL:dsack */
20206 	case TCP_RACK_PACING_BETA:		/*  URL:pacing_beta */
20207 	case TCP_RACK_PACING_BETA_ECN:		/*  URL:pacing_beta_ecn */
20208 	case TCP_RACK_TIMER_SLOP:		/*  URL:timer_slop */
20209 		break;
20210 	default:
20211 		/* Filter off all unknown options to the base stack */
20212 		return (tcp_default_ctloutput(so, sopt, inp, tp));
20213 		break;
20214 	}
20215 	INP_WUNLOCK(inp);
20216 	if (sopt->sopt_name == TCP_PACING_RATE_CAP) {
20217 		error = sooptcopyin(sopt, &loptval, sizeof(loptval), sizeof(loptval));
20218 		/*
20219 		 * We truncate it down to 32 bits for the socket-option trace this
20220 		 * means rates > 34Gbps won't show right, but thats probably ok.
20221 		 */
20222 		optval = (uint32_t)loptval;
20223 	} else {
20224 		error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
20225 		/* Save it in 64 bit form too */
20226 		loptval = optval;
20227 	}
20228 	if (error)
20229 		return (error);
20230 	INP_WLOCK(inp);
20231 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
20232 		INP_WUNLOCK(inp);
20233 		return (ECONNRESET);
20234 	}
20235 	if (tp->t_fb != &__tcp_rack) {
20236 		INP_WUNLOCK(inp);
20237 		return (ENOPROTOOPT);
20238 	}
20239 	if (rack->defer_options && (rack->gp_ready == 0) &&
20240 	    (sopt->sopt_name != TCP_DEFER_OPTIONS) &&
20241 	    (sopt->sopt_name != TCP_RACK_PACING_BETA) &&
20242 	    (sopt->sopt_name != TCP_RACK_PACING_BETA_ECN) &&
20243 	    (sopt->sopt_name != TCP_RACK_MEASURE_CNT)) {
20244 		/* Options are beind deferred */
20245 		if (rack_add_deferred_option(rack, sopt->sopt_name, loptval)) {
20246 			INP_WUNLOCK(inp);
20247 			return (0);
20248 		} else {
20249 			/* No memory to defer, fail */
20250 			INP_WUNLOCK(inp);
20251 			return (ENOMEM);
20252 		}
20253 	}
20254 	error = rack_process_option(tp, rack, sopt->sopt_name, optval, loptval);
20255 	INP_WUNLOCK(inp);
20256 	return (error);
20257 }
20258 
20259 static void
20260 rack_fill_info(struct tcpcb *tp, struct tcp_info *ti)
20261 {
20262 
20263 	INP_WLOCK_ASSERT(tp->t_inpcb);
20264 	bzero(ti, sizeof(*ti));
20265 
20266 	ti->tcpi_state = tp->t_state;
20267 	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
20268 		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
20269 	if (tp->t_flags & TF_SACK_PERMIT)
20270 		ti->tcpi_options |= TCPI_OPT_SACK;
20271 	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
20272 		ti->tcpi_options |= TCPI_OPT_WSCALE;
20273 		ti->tcpi_snd_wscale = tp->snd_scale;
20274 		ti->tcpi_rcv_wscale = tp->rcv_scale;
20275 	}
20276 	if (tp->t_flags2 & TF2_ECN_PERMIT)
20277 		ti->tcpi_options |= TCPI_OPT_ECN;
20278 	if (tp->t_flags & TF_FASTOPEN)
20279 		ti->tcpi_options |= TCPI_OPT_TFO;
20280 	/* still kept in ticks is t_rcvtime */
20281 	ti->tcpi_last_data_recv = ((uint32_t)ticks - tp->t_rcvtime) * tick;
20282 	/* Since we hold everything in precise useconds this is easy */
20283 	ti->tcpi_rtt = tp->t_srtt;
20284 	ti->tcpi_rttvar = tp->t_rttvar;
20285 	ti->tcpi_rto = tp->t_rxtcur;
20286 	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
20287 	ti->tcpi_snd_cwnd = tp->snd_cwnd;
20288 	/*
20289 	 * FreeBSD-specific extension fields for tcp_info.
20290 	 */
20291 	ti->tcpi_rcv_space = tp->rcv_wnd;
20292 	ti->tcpi_rcv_nxt = tp->rcv_nxt;
20293 	ti->tcpi_snd_wnd = tp->snd_wnd;
20294 	ti->tcpi_snd_bwnd = 0;		/* Unused, kept for compat. */
20295 	ti->tcpi_snd_nxt = tp->snd_nxt;
20296 	ti->tcpi_snd_mss = tp->t_maxseg;
20297 	ti->tcpi_rcv_mss = tp->t_maxseg;
20298 	ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
20299 	ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
20300 	ti->tcpi_snd_zerowin = tp->t_sndzerowin;
20301 #ifdef NETFLIX_STATS
20302 	ti->tcpi_total_tlp = tp->t_sndtlppack;
20303 	ti->tcpi_total_tlp_bytes = tp->t_sndtlpbyte;
20304 	memcpy(&ti->tcpi_rxsyninfo, &tp->t_rxsyninfo, sizeof(struct tcpsyninfo));
20305 #endif
20306 #ifdef TCP_OFFLOAD
20307 	if (tp->t_flags & TF_TOE) {
20308 		ti->tcpi_options |= TCPI_OPT_TOE;
20309 		tcp_offload_tcp_info(tp, ti);
20310 	}
20311 #endif
20312 }
20313 
20314 static int
20315 rack_get_sockopt(struct socket *so, struct sockopt *sopt,
20316     struct inpcb *inp, struct tcpcb *tp, struct tcp_rack *rack)
20317 {
20318 	int32_t error, optval;
20319 	uint64_t val, loptval;
20320 	struct	tcp_info ti;
20321 	/*
20322 	 * Because all our options are either boolean or an int, we can just
20323 	 * pull everything into optval and then unlock and copy. If we ever
20324 	 * add a option that is not a int, then this will have quite an
20325 	 * impact to this routine.
20326 	 */
20327 	error = 0;
20328 	switch (sopt->sopt_name) {
20329 	case TCP_INFO:
20330 		/* First get the info filled */
20331 		rack_fill_info(tp, &ti);
20332 		/* Fix up the rtt related fields if needed */
20333 		INP_WUNLOCK(inp);
20334 		error = sooptcopyout(sopt, &ti, sizeof ti);
20335 		return (error);
20336 	/*
20337 	 * Beta is the congestion control value for NewReno that influences how
20338 	 * much of a backoff happens when loss is detected. It is normally set
20339 	 * to 50 for 50% i.e. the cwnd is reduced to 50% of its previous value
20340 	 * when you exit recovery.
20341 	 */
20342 	case TCP_RACK_PACING_BETA:
20343 		if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0)
20344 			error = EINVAL;
20345 		else if (rack->rc_pacing_cc_set == 0)
20346 			optval = rack->r_ctl.rc_saved_beta.beta;
20347 		else {
20348 			/*
20349 			 * Reach out into the CC data and report back what
20350 			 * I have previously set. Yeah it looks hackish but
20351 			 * we don't want to report the saved values.
20352 			 */
20353 			if (tp->ccv->cc_data)
20354 				optval = ((struct newreno *)tp->ccv->cc_data)->beta;
20355 			else
20356 				error = EINVAL;
20357 		}
20358 		break;
20359 		/*
20360 		 * Beta_ecn is the congestion control value for NewReno that influences how
20361 		 * much of a backoff happens when a ECN mark is detected. It is normally set
20362 		 * to 80 for 80% i.e. the cwnd is reduced by 20% of its previous value when
20363 		 * you exit recovery. Note that classic ECN has a beta of 50, it is only
20364 		 * ABE Ecn that uses this "less" value, but we do too with pacing :)
20365 		 */
20366 
20367 	case TCP_RACK_PACING_BETA_ECN:
20368 		if (strcmp(tp->cc_algo->name, CCALGONAME_NEWRENO) != 0)
20369 			error = EINVAL;
20370 		else if (rack->rc_pacing_cc_set == 0)
20371 			optval = rack->r_ctl.rc_saved_beta.beta_ecn;
20372 		else {
20373 			/*
20374 			 * Reach out into the CC data and report back what
20375 			 * I have previously set. Yeah it looks hackish but
20376 			 * we don't want to report the saved values.
20377 			 */
20378 			if (tp->ccv->cc_data)
20379 				optval = ((struct newreno *)tp->ccv->cc_data)->beta_ecn;
20380 			else
20381 				error = EINVAL;
20382 		}
20383 		break;
20384 	case TCP_RACK_DSACK_OPT:
20385 		optval = 0;
20386 		if (rack->rc_rack_tmr_std_based) {
20387 			optval |= 1;
20388 		}
20389 		if (rack->rc_rack_use_dsack) {
20390 			optval |= 2;
20391 		}
20392 		break;
20393 	case TCP_FAST_RSM_HACK:
20394 		optval = rack->fast_rsm_hack;
20395 		break;
20396 	case TCP_DEFER_OPTIONS:
20397 		optval = rack->defer_options;
20398 		break;
20399 	case TCP_RACK_MEASURE_CNT:
20400 		optval = rack->r_ctl.req_measurements;
20401 		break;
20402 	case TCP_REC_ABC_VAL:
20403 		optval = rack->r_use_labc_for_rec;
20404 		break;
20405 	case TCP_RACK_ABC_VAL:
20406 		optval = rack->rc_labc;
20407 		break;
20408 	case TCP_HDWR_UP_ONLY:
20409 		optval= rack->r_up_only;
20410 		break;
20411 	case TCP_PACING_RATE_CAP:
20412 		loptval = rack->r_ctl.bw_rate_cap;
20413 		break;
20414 	case TCP_RACK_PROFILE:
20415 		/* You cannot retrieve a profile, its write only */
20416 		error = EINVAL;
20417 		break;
20418 	case TCP_USE_CMP_ACKS:
20419 		optval = rack->r_use_cmp_ack;
20420 		break;
20421 	case TCP_RACK_PACE_TO_FILL:
20422 		optval = rack->rc_pace_to_cwnd;
20423 		if (optval && rack->r_fill_less_agg)
20424 			optval++;
20425 		break;
20426 	case TCP_RACK_NO_PUSH_AT_MAX:
20427 		optval = rack->r_ctl.rc_no_push_at_mrtt;
20428 		break;
20429 	case TCP_SHARED_CWND_ENABLE:
20430 		optval = rack->rack_enable_scwnd;
20431 		break;
20432 	case TCP_RACK_NONRXT_CFG_RATE:
20433 		optval = rack->rack_rec_nonrxt_use_cr;
20434 		break;
20435 	case TCP_NO_PRR:
20436 		if (rack->rack_no_prr  == 1)
20437 			optval = 1;
20438 		else if (rack->no_prr_addback == 1)
20439 			optval = 2;
20440 		else
20441 			optval = 0;
20442 		break;
20443 	case TCP_RACK_DO_DETECTION:
20444 		optval = rack->do_detection;
20445 		break;
20446 	case TCP_RACK_MBUF_QUEUE:
20447 		/* Now do we use the LRO mbuf-queue feature */
20448 		optval = rack->r_mbuf_queue;
20449 		break;
20450 	case TCP_TIMELY_DYN_ADJ:
20451 		optval = rack->rc_gp_dyn_mul;
20452 		break;
20453 	case TCP_BBR_IWINTSO:
20454 		optval = rack->rc_init_win;
20455 		break;
20456 	case TCP_RACK_TLP_REDUCE:
20457 		/* RACK TLP cwnd reduction (bool) */
20458 		optval = rack->r_ctl.rc_tlp_cwnd_reduce;
20459 		break;
20460 	case TCP_BBR_RACK_INIT_RATE:
20461 		val = rack->r_ctl.init_rate;
20462 		/* convert to kbits per sec */
20463 		val *= 8;
20464 		val /= 1000;
20465 		optval = (uint32_t)val;
20466 		break;
20467 	case TCP_RACK_FORCE_MSEG:
20468 		optval = rack->rc_force_max_seg;
20469 		break;
20470 	case TCP_RACK_PACE_MAX_SEG:
20471 		/* Max segments in a pace */
20472 		optval = rack->rc_user_set_max_segs;
20473 		break;
20474 	case TCP_RACK_PACE_ALWAYS:
20475 		/* Use the always pace method */
20476 		optval = rack->rc_always_pace;
20477 		break;
20478 	case TCP_RACK_PRR_SENDALOT:
20479 		/* Allow PRR to send more than one seg */
20480 		optval = rack->r_ctl.rc_prr_sendalot;
20481 		break;
20482 	case TCP_RACK_MIN_TO:
20483 		/* Minimum time between rack t-o's in ms */
20484 		optval = rack->r_ctl.rc_min_to;
20485 		break;
20486 	case TCP_RACK_EARLY_SEG:
20487 		/* If early recovery max segments */
20488 		optval = rack->r_ctl.rc_early_recovery_segs;
20489 		break;
20490 	case TCP_RACK_REORD_THRESH:
20491 		/* RACK reorder threshold (shift amount) */
20492 		optval = rack->r_ctl.rc_reorder_shift;
20493 		break;
20494 	case TCP_RACK_REORD_FADE:
20495 		/* Does reordering fade after ms time */
20496 		optval = rack->r_ctl.rc_reorder_fade;
20497 		break;
20498 	case TCP_BBR_USE_RACK_RR:
20499 		/* Do we use the rack cheat for rxt */
20500 		optval = rack->use_rack_rr;
20501 		break;
20502 	case TCP_RACK_RR_CONF:
20503 		optval = rack->r_rr_config;
20504 		break;
20505 	case TCP_HDWR_RATE_CAP:
20506 		optval = rack->r_rack_hw_rate_caps;
20507 		break;
20508 	case TCP_BBR_HDWR_PACE:
20509 		optval = rack->rack_hdw_pace_ena;
20510 		break;
20511 	case TCP_RACK_TLP_THRESH:
20512 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
20513 		optval = rack->r_ctl.rc_tlp_threshold;
20514 		break;
20515 	case TCP_RACK_PKT_DELAY:
20516 		/* RACK added ms i.e. rack-rtt + reord + N */
20517 		optval = rack->r_ctl.rc_pkt_delay;
20518 		break;
20519 	case TCP_RACK_TLP_USE:
20520 		optval = rack->rack_tlp_threshold_use;
20521 		break;
20522 	case TCP_RACK_PACE_RATE_CA:
20523 		optval = rack->r_ctl.rc_fixed_pacing_rate_ca;
20524 		break;
20525 	case TCP_RACK_PACE_RATE_SS:
20526 		optval = rack->r_ctl.rc_fixed_pacing_rate_ss;
20527 		break;
20528 	case TCP_RACK_PACE_RATE_REC:
20529 		optval = rack->r_ctl.rc_fixed_pacing_rate_rec;
20530 		break;
20531 	case TCP_RACK_GP_INCREASE_SS:
20532 		optval = rack->r_ctl.rack_per_of_gp_ca;
20533 		break;
20534 	case TCP_RACK_GP_INCREASE_CA:
20535 		optval = rack->r_ctl.rack_per_of_gp_ss;
20536 		break;
20537 	case TCP_BBR_RACK_RTT_USE:
20538 		optval = rack->r_ctl.rc_rate_sample_method;
20539 		break;
20540 	case TCP_DELACK:
20541 		optval = tp->t_delayed_ack;
20542 		break;
20543 	case TCP_DATA_AFTER_CLOSE:
20544 		optval = rack->rc_allow_data_af_clo;
20545 		break;
20546 	case TCP_SHARED_CWND_TIME_LIMIT:
20547 		optval = rack->r_limit_scw;
20548 		break;
20549 	case TCP_RACK_TIMER_SLOP:
20550 		optval = rack->r_ctl.timer_slop;
20551 		break;
20552 	default:
20553 		return (tcp_default_ctloutput(so, sopt, inp, tp));
20554 		break;
20555 	}
20556 	INP_WUNLOCK(inp);
20557 	if (error == 0) {
20558 		if (TCP_PACING_RATE_CAP)
20559 			error = sooptcopyout(sopt, &loptval, sizeof loptval);
20560 		else
20561 			error = sooptcopyout(sopt, &optval, sizeof optval);
20562 	}
20563 	return (error);
20564 }
20565 
20566 static int
20567 rack_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
20568 {
20569 	int32_t error = EINVAL;
20570 	struct tcp_rack *rack;
20571 
20572 	rack = (struct tcp_rack *)tp->t_fb_ptr;
20573 	if (rack == NULL) {
20574 		/* Huh? */
20575 		goto out;
20576 	}
20577 	if (sopt->sopt_dir == SOPT_SET) {
20578 		return (rack_set_sockopt(so, sopt, inp, tp, rack));
20579 	} else if (sopt->sopt_dir == SOPT_GET) {
20580 		return (rack_get_sockopt(so, sopt, inp, tp, rack));
20581 	}
20582 out:
20583 	INP_WUNLOCK(inp);
20584 	return (error);
20585 }
20586 
20587 static const char *rack_stack_names[] = {
20588 	__XSTRING(STACKNAME),
20589 #ifdef STACKALIAS
20590 	__XSTRING(STACKALIAS),
20591 #endif
20592 };
20593 
20594 static int
20595 rack_ctor(void *mem, int32_t size, void *arg, int32_t how)
20596 {
20597 	memset(mem, 0, size);
20598 	return (0);
20599 }
20600 
20601 static void
20602 rack_dtor(void *mem, int32_t size, void *arg)
20603 {
20604 
20605 }
20606 
20607 static bool rack_mod_inited = false;
20608 
20609 static int
20610 tcp_addrack(module_t mod, int32_t type, void *data)
20611 {
20612 	int32_t err = 0;
20613 	int num_stacks;
20614 
20615 	switch (type) {
20616 	case MOD_LOAD:
20617 		rack_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
20618 		    sizeof(struct rack_sendmap),
20619 		    rack_ctor, rack_dtor, NULL, NULL, UMA_ALIGN_PTR, 0);
20620 
20621 		rack_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
20622 		    sizeof(struct tcp_rack),
20623 		    rack_ctor, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
20624 
20625 		sysctl_ctx_init(&rack_sysctl_ctx);
20626 		rack_sysctl_root = SYSCTL_ADD_NODE(&rack_sysctl_ctx,
20627 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
20628 		    OID_AUTO,
20629 #ifdef STACKALIAS
20630 		    __XSTRING(STACKALIAS),
20631 #else
20632 		    __XSTRING(STACKNAME),
20633 #endif
20634 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
20635 		    "");
20636 		if (rack_sysctl_root == NULL) {
20637 			printf("Failed to add sysctl node\n");
20638 			err = EFAULT;
20639 			goto free_uma;
20640 		}
20641 		rack_init_sysctls();
20642 		num_stacks = nitems(rack_stack_names);
20643 		err = register_tcp_functions_as_names(&__tcp_rack, M_WAITOK,
20644 		    rack_stack_names, &num_stacks);
20645 		if (err) {
20646 			printf("Failed to register %s stack name for "
20647 			    "%s module\n", rack_stack_names[num_stacks],
20648 			    __XSTRING(MODNAME));
20649 			sysctl_ctx_free(&rack_sysctl_ctx);
20650 free_uma:
20651 			uma_zdestroy(rack_zone);
20652 			uma_zdestroy(rack_pcb_zone);
20653 			rack_counter_destroy();
20654 			printf("Failed to register rack module -- err:%d\n", err);
20655 			return (err);
20656 		}
20657 		tcp_lro_reg_mbufq();
20658 		rack_mod_inited = true;
20659 		break;
20660 	case MOD_QUIESCE:
20661 		err = deregister_tcp_functions(&__tcp_rack, true, false);
20662 		break;
20663 	case MOD_UNLOAD:
20664 		err = deregister_tcp_functions(&__tcp_rack, false, true);
20665 		if (err == EBUSY)
20666 			break;
20667 		if (rack_mod_inited) {
20668 			uma_zdestroy(rack_zone);
20669 			uma_zdestroy(rack_pcb_zone);
20670 			sysctl_ctx_free(&rack_sysctl_ctx);
20671 			rack_counter_destroy();
20672 			rack_mod_inited = false;
20673 		}
20674 		tcp_lro_dereg_mbufq();
20675 		err = 0;
20676 		break;
20677 	default:
20678 		return (EOPNOTSUPP);
20679 	}
20680 	return (err);
20681 }
20682 
20683 static moduledata_t tcp_rack = {
20684 	.name = __XSTRING(MODNAME),
20685 	.evhand = tcp_addrack,
20686 	.priv = 0
20687 };
20688 
20689 MODULE_VERSION(MODNAME, 1);
20690 DECLARE_MODULE(MODNAME, tcp_rack, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
20691 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
20692