xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision d003e0d7fe0d3a9b4b2c5835bb3f0f6faf3ab538)
1 /*-
2  * Copyright (c) 2016-2019
3  *	Netflix Inc.
4  *      All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  */
28 /**
29  * Author: Randall Stewart <rrs@netflix.com>
30  * This work is based on the ACM Queue paper
31  * BBR - Congestion Based Congestion Control
32  * and also numerous discussions with Neal, Yuchung and Van.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_inet.h"
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 #include "opt_tcpdebug.h"
42 #include "opt_ratelimit.h"
43 #include "opt_kern_tls.h"
44 #include <sys/param.h>
45 #include <sys/module.h>
46 #include <sys/kernel.h>
47 #ifdef TCP_HHOOK
48 #include <sys/hhook.h>
49 #endif
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/proc.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #ifdef KERN_TLS
56 #include <sys/ktls.h>
57 #endif
58 #include <sys/sysctl.h>
59 #include <sys/systm.h>
60 #include <sys/qmath.h>
61 #include <sys/tree.h>
62 #ifdef NETFLIX_STATS
63 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
64 #endif
65 #include <sys/refcount.h>
66 #include <sys/queue.h>
67 #include <sys/eventhandler.h>
68 #include <sys/smp.h>
69 #include <sys/kthread.h>
70 #include <sys/lock.h>
71 #include <sys/mutex.h>
72 #include <sys/tim_filter.h>
73 #include <sys/time.h>
74 #include <vm/uma.h>
75 #include <sys/kern_prefetch.h>
76 
77 #include <net/route.h>
78 #include <net/vnet.h>
79 
80 #define TCPSTATES		/* for logging */
81 
82 #include <netinet/in.h>
83 #include <netinet/in_kdtrace.h>
84 #include <netinet/in_pcb.h>
85 #include <netinet/ip.h>
86 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
87 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
88 #include <netinet/ip_var.h>
89 #include <netinet/ip6.h>
90 #include <netinet6/in6_pcb.h>
91 #include <netinet6/ip6_var.h>
92 #define	TCPOUTFLAGS
93 #include <netinet/tcp.h>
94 #include <netinet/tcp_fsm.h>
95 #include <netinet/tcp_seq.h>
96 #include <netinet/tcp_timer.h>
97 #include <netinet/tcp_var.h>
98 #include <netinet/tcpip.h>
99 #include <netinet/tcp_hpts.h>
100 #include <netinet/cc/cc.h>
101 #include <netinet/tcp_log_buf.h>
102 #include <netinet/tcp_ratelimit.h>
103 #include <netinet/tcp_lro.h>
104 #ifdef TCPDEBUG
105 #include <netinet/tcp_debug.h>
106 #endif				/* TCPDEBUG */
107 #ifdef TCP_OFFLOAD
108 #include <netinet/tcp_offload.h>
109 #endif
110 #ifdef INET6
111 #include <netinet6/tcp6_var.h>
112 #endif
113 #include <netinet/tcp_fastopen.h>
114 
115 #include <netipsec/ipsec_support.h>
116 #include <net/if.h>
117 #include <net/if_var.h>
118 #include <net/ethernet.h>
119 
120 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
121 #include <netipsec/ipsec.h>
122 #include <netipsec/ipsec6.h>
123 #endif				/* IPSEC */
124 
125 #include <netinet/udp.h>
126 #include <netinet/udp_var.h>
127 #include <machine/in_cksum.h>
128 
129 #ifdef MAC
130 #include <security/mac/mac_framework.h>
131 #endif
132 
133 #include "sack_filter.h"
134 #include "tcp_bbr.h"
135 #include "rack_bbr_common.h"
136 uma_zone_t bbr_zone;
137 uma_zone_t bbr_pcb_zone;
138 
139 struct sysctl_ctx_list bbr_sysctl_ctx;
140 struct sysctl_oid *bbr_sysctl_root;
141 
142 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
143 	(tv) = (value); \
144 	if ((u_long)(tv) < (u_long)(tvmin)) \
145 		(tv) = (tvmin); \
146 	if ((u_long)(tv) > (u_long)(tvmax)) \
147 		(tv) = (tvmax); \
148 } while(0)
149 
150 /*#define BBR_INVARIANT 1*/
151 
152 /*
153  * initial window
154  */
155 static uint32_t bbr_def_init_win = 10;
156 static int32_t bbr_persist_min = 250000;	/* 250ms */
157 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
158 static int32_t bbr_cwnd_may_shrink = 0;
159 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
160 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
161 static int32_t bbr_hardware_pacing_limit = 8000;
162 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
163 static int32_t bbr_no_retran = 0;
164 static int32_t bbr_tcp_map_entries_limit = 1500;
165 static int32_t bbr_tcp_map_split_limit = 256;
166 
167 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
168 static int32_t bbr_max_net_error_cnt = 10;
169 /* Should the following be dynamic too -- loss wise */
170 static int32_t bbr_rtt_gain_thresh = 0;
171 /* Measurement controls */
172 static int32_t bbr_use_google_algo = 1;
173 static int32_t bbr_ts_limiting = 1;
174 static int32_t bbr_ts_can_raise = 0;
175 static int32_t bbr_do_red = 600;
176 static int32_t bbr_red_scale = 20000;
177 static int32_t bbr_red_mul = 1;
178 static int32_t bbr_red_div = 2;
179 static int32_t bbr_red_growth_restrict = 1;
180 static int32_t  bbr_target_is_bbunit = 0;
181 static int32_t bbr_drop_limit = 0;
182 /*
183  * How much gain do we need to see to
184  * stay in startup?
185  */
186 static int32_t bbr_marks_rxt_sack_passed = 0;
187 static int32_t bbr_start_exit = 25;
188 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
189 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
190 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
191 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
192 					 * if we go back ever to where the pacer
193 					 * has priority over timers.
194 					 */
195 static int32_t bbr_policer_call_from_rack_to = 0;
196 static int32_t bbr_policer_detection_enabled = 1;
197 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
198 						 * measurments before we are
199 						 * "good" note that 2 == 1.
200 						 * This is because we use a >
201 						 * comparison. This means if
202 						 * min_measure was 0, it takes
203 						 * num-measures > min(0) and
204 						 * you get 1 measurement and
205 						 * you are good. Set to 1, you
206 						 * have to have two
207 						 * measurements (this is done
208 						 * to prevent it from being ok
209 						 * to have no measurements). */
210 static int32_t bbr_no_pacing_until = 4;
211 
212 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
213 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
214 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
215 
216 static int32_t bbr_target_cwnd_mult_limit = 8;
217 /*
218  * bbr_cwnd_min_val is the number of
219  * segments we hold to in the RTT probe
220  * state typically 4.
221  */
222 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
223 
224 
225 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
226 
227 static int32_t bbr_gain_to_target = 1;
228 static int32_t bbr_gain_gets_extra_too = 1;
229 /*
230  * bbr_high_gain is the 2/ln(2) value we need
231  * to double the sending rate in startup. This
232  * is used for both cwnd and hptsi gain's.
233  */
234 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
235 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
236 static int32_t bbr_use_lower_gain_in_startup = 1;
237 
238 /* thresholds for reduction on drain in sub-states/drain */
239 static int32_t bbr_drain_rtt = BBR_SRTT;
240 static int32_t bbr_drain_floor = 88;
241 static int32_t google_allow_early_out = 1;
242 static int32_t google_consider_lost = 1;
243 static int32_t bbr_drain_drop_mul = 4;
244 static int32_t bbr_drain_drop_div = 5;
245 static int32_t bbr_rand_ot = 50;
246 static int32_t bbr_can_force_probertt = 0;
247 static int32_t bbr_can_adjust_probertt = 1;
248 static int32_t bbr_probertt_sets_rtt = 0;
249 static int32_t bbr_can_use_ts_for_rtt = 1;
250 static int32_t bbr_is_ratio = 0;
251 static int32_t bbr_sub_drain_app_limit = 1;
252 static int32_t bbr_prtt_slam_cwnd = 1;
253 static int32_t bbr_sub_drain_slam_cwnd = 1;
254 static int32_t bbr_slam_cwnd_in_main_drain = 1;
255 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
256 					 * hold */
257 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
258 /*
259  * bbr_drain_gain is the reverse of the high_gain
260  * designed to drain back out the standing queue
261  * that is formed in startup by causing a larger
262  * hptsi gain and thus drainging the packets
263  * in flight.
264  */
265 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
266 static int32_t bbr_rttprobe_gain = 192;
267 
268 /*
269  * The cwnd_gain is the default cwnd gain applied when
270  * calculating a target cwnd. Note that the cwnd is
271  * a secondary factor in the way BBR works (see the
272  * paper and think about it, it will take some time).
273  * Basically the hptsi_gain spreads the packets out
274  * so you never get more than BDP to the peer even
275  * if the cwnd is high. In our implemenation that
276  * means in non-recovery/retransmission scenarios
277  * cwnd will never be reached by the flight-size.
278  */
279 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
280 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
281 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
282 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
283 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
284 static int32_t bbr_ignore_data_after_close = 1;
285 static int16_t bbr_hptsi_gain[] = {
286 	(BBR_UNIT *5 / 4),
287 	(BBR_UNIT * 3 / 4),
288 	BBR_UNIT,
289 	BBR_UNIT,
290 	BBR_UNIT,
291 	BBR_UNIT,
292 	BBR_UNIT,
293 	BBR_UNIT
294 };
295 int32_t bbr_use_rack_resend_cheat = 1;
296 int32_t bbr_sends_full_iwnd = 1;
297 
298 #define BBR_HPTSI_GAIN_MAX 8
299 /*
300  * The BBR module incorporates a number of
301  * TCP ideas that have been put out into the IETF
302  * over the last few years:
303  * - Yuchung Cheng's RACK TCP (for which its named) that
304  *    will stop us using the number of dup acks and instead
305  *    use time as the gage of when we retransmit.
306  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
307  *    of Dukkipati et.al.
308  * - Van Jacobson's et.al BBR.
309  *
310  * RACK depends on SACK, so if an endpoint arrives that
311  * cannot do SACK the state machine below will shuttle the
312  * connection back to using the "default" TCP stack that is
313  * in FreeBSD.
314  *
315  * To implement BBR and RACK the original TCP stack was first decomposed
316  * into a functional state machine with individual states
317  * for each of the possible TCP connection states. The do_segement
318  * functions role in life is to mandate the connection supports SACK
319  * initially and then assure that the RACK state matches the conenction
320  * state before calling the states do_segment function. Data processing
321  * of inbound segments also now happens in the hpts_do_segment in general
322  * with only one exception. This is so we can keep the connection on
323  * a single CPU.
324  *
325  * Each state is simplified due to the fact that the original do_segment
326  * has been decomposed and we *know* what state we are in (no
327  * switches on the state) and all tests for SACK are gone. This
328  * greatly simplifies what each state does.
329  *
330  * TCP output is also over-written with a new version since it
331  * must maintain the new rack scoreboard and has had hptsi
332  * integrated as a requirment. Still todo is to eliminate the
333  * use of the callout_() system and use the hpts for all
334  * timers as well.
335  */
336 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
337 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
338 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
339 						 * free list */
340 static int32_t bbr_tlp_thresh = 1;
341 static int32_t bbr_reorder_thresh = 2;
342 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
343 						 * 60,000,000 - 60 seconds */
344 static int32_t bbr_pkt_delay = 1000;
345 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
346 static int32_t bbr_incr_timers = 1;
347 
348 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
349 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
350 static int32_t bbr_exit_startup_at_loss = 1;
351 
352 /*
353  * bbr_lt_bw_ratio is 1/8th
354  * bbr_lt_bw_diff is  < 4 Kbit/sec
355  */
356 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
357 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
358 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
359 						 * the lt_bw for */
360 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
361 						 * lt_bw */
362 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
363 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
364 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
365 
366 static int32_t bbr_verbose_logging = 0;
367 /*
368  * Currently regular tcp has a rto_min of 30ms
369  * the backoff goes 12 times so that ends up
370  * being a total of 122.850 seconds before a
371  * connection is killed.
372  */
373 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
374 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
375 
376 /****************************************************/
377 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
378 /****************************************************/
379 /* What amount is our formula using to get TSO size */
380 static int32_t bbr_hptsi_per_second = 1000;
381 
382 /*
383  * For hptsi under bbr_cross_over connections what is delay
384  * target 7ms (in usec) combined with a seg_max of 2
385  * gets us close to identical google behavior in
386  * TSO size selection (possibly more 1MSS sends).
387  */
388 static int32_t bbr_hptsi_segments_delay_tar = 7000;
389 
390 /* Does pacing delay include overhead's in its time calculations? */
391 static int32_t bbr_include_enet_oh = 0;
392 static int32_t bbr_include_ip_oh = 1;
393 static int32_t bbr_include_tcp_oh = 1;
394 static int32_t bbr_google_discount = 10;
395 
396 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
397 static int32_t bbr_state_is_pkt_epoch = 0;
398 static int32_t bbr_state_drain_2_tar = 1;
399 /* What is the max the 0 - bbr_cross_over MBPS TSO target
400  * can reach using our delay target. Note that this
401  * value becomes the floor for the cross over
402  * algorithm.
403  */
404 static int32_t bbr_hptsi_segments_max = 2;
405 static int32_t bbr_hptsi_segments_floor = 1;
406 static int32_t bbr_hptsi_utter_max = 0;
407 
408 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
409 static int32_t bbr_hptsi_bytes_min = 1460;
410 static int32_t bbr_all_get_min = 0;
411 
412 /* Cross over point from algo-a to algo-b */
413 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
414 
415 /* Do we deal with our restart state? */
416 static int32_t bbr_uses_idle_restart = 0;
417 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
418 
419 /* Do we allow hardware pacing? */
420 static int32_t bbr_allow_hdwr_pacing = 0;
421 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
422 static int32_t bbr_hdwr_pace_floor = 1;
423 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
424 
425 /****************************************************/
426 static int32_t bbr_resends_use_tso = 0;
427 static int32_t bbr_tlp_max_resend = 2;
428 static int32_t bbr_sack_block_limit = 128;
429 
430 #define  BBR_MAX_STAT 19
431 counter_u64_t bbr_state_time[BBR_MAX_STAT];
432 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
433 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
434 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
435 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
436 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
437 counter_u64_t bbr_flows_whdwr_pacing;
438 counter_u64_t bbr_flows_nohdwr_pacing;
439 
440 counter_u64_t bbr_nohdwr_pacing_enobuf;
441 counter_u64_t bbr_hdwr_pacing_enobuf;
442 
443 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
444 
445 /*
446  * Static defintions we need for forward declarations.
447  */
448 static uint32_t
449 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
450     uint32_t useconds_time, uint64_t bw);
451 static uint32_t
452 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
453 static void
454      bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
455 static void
456 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
457 static void
458 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
459 		    int dolog);
460 static uint32_t
461 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
462 static void
463 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
464 		 int32_t pkt_epoch, uint32_t losses);
465 static uint32_t
466 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm);
467 static uint32_t bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
468 static uint32_t
469 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
470     struct bbr_sendmap *rsm, uint32_t srtt,
471     uint32_t cts);
472 static void
473 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
474     int32_t line);
475 static void
476      bbr_set_state_target(struct tcp_bbr *bbr, int line);
477 static void
478      bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
479 
480 static void
481      bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line);
482 
483 static void
484      tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
485 
486 static void
487      bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
488 
489 static void
490      bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied, uint32_t rtt,
491 			 uint32_t line, uint8_t is_start, uint16_t set);
492 
493 static struct bbr_sendmap *
494             bbr_find_lowest_rsm(struct tcp_bbr *bbr);
495 static __inline uint32_t
496 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
497 static void
498      bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which);
499 
500 static void
501 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
502     uint32_t thresh, uint32_t to);
503 static void
504      bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
505 
506 static void
507 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
508     uint32_t del_by, uint32_t cts, uint32_t sloton, uint32_t prev_delay);
509 
510 static void
511 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr,
512     uint32_t cts, int32_t line);
513 static void
514      bbr_stop_all_timers(struct tcpcb *tp);
515 static void
516      bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
517 static void
518      bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
519 static void
520      bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
521 
522 
523 static void
524 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
525     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod);
526 
527 static inline uint8_t
528 bbr_state_val(struct tcp_bbr *bbr)
529 {
530 	return(bbr->rc_bbr_substate);
531 }
532 
533 static inline uint32_t
534 get_min_cwnd(struct tcp_bbr *bbr)
535 {
536 	int mss;
537 
538 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
539 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
540 		return (bbr_cwnd_min_val_hs * mss);
541 	else
542 		return (bbr_cwnd_min_val * mss);
543 }
544 
545 static uint32_t
546 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
547 {
548 	uint64_t srtt, var;
549 	uint64_t ret_val;
550 
551 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
552 	if (tp->t_srtt == 0) {
553 		srtt = (uint64_t)BBR_INITIAL_RTO;
554 		var = 0;
555 	} else {
556 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
557 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
558 	}
559 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
560 	    bbr_persist_min, bbr_persist_max);
561 	return ((uint32_t)ret_val);
562 }
563 
564 static uint32_t
565 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
566 {
567 	/*
568 	 * Start the FR timer, we do this based on getting the first one in
569 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
570 	 * events we need to stop the running timer (if its running) before
571 	 * starting the new one.
572 	 */
573 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
574 	int32_t idx;
575 	int32_t is_tlp_timer = 0;
576 	struct bbr_sendmap *rsm;
577 
578 	if (bbr->rc_all_timers_stopped) {
579 		/* All timers have been stopped none are to run */
580 		return (0);
581 	}
582 	if (bbr->rc_in_persist) {
583 		/* We can't start any timer in persists */
584 		return (bbr_get_persists_timer_val(tp, bbr));
585 	}
586 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
587 	if ((rsm == NULL) ||
588 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
589 	    (tp->t_state < TCPS_ESTABLISHED)) {
590 		/* Nothing on the send map */
591 activate_rxt:
592 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
593 			uint64_t tov;
594 
595 			time_since_sent = 0;
596 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
597 			if (rsm) {
598 				idx = rsm->r_rtr_cnt - 1;
599 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
600 					tstmp_touse = rsm->r_tim_lastsent[idx];
601 				else
602 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
603 				if (TSTMP_GT(tstmp_touse, cts))
604 				    time_since_sent = cts - tstmp_touse;
605 			}
606 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
607 			if (tp->t_srtt == 0)
608 				tov = BBR_INITIAL_RTO;
609 			else
610 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
611 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
612 			if (tp->t_rxtshift)
613 				tov *= tcp_backoff[tp->t_rxtshift];
614 			if (tov > time_since_sent)
615 				tov -= time_since_sent;
616 			else
617 				tov = bbr->r_ctl.rc_min_to;
618 			TCPT_RANGESET_NOSLOP(to, tov,
619 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
620 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
621 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
622 			return (to);
623 		}
624 		return (0);
625 	}
626 	if (rsm->r_flags & BBR_ACKED) {
627 		rsm = bbr_find_lowest_rsm(bbr);
628 		if (rsm == NULL) {
629 			/* No lowest? */
630 			goto activate_rxt;
631 		}
632 	}
633 	/* Convert from ms to usecs */
634 	if (rsm->r_flags & BBR_SACK_PASSED) {
635 		if ((tp->t_flags & TF_SENTFIN) &&
636 		    ((tp->snd_max - tp->snd_una) == 1) &&
637 		    (rsm->r_flags & BBR_HAS_FIN)) {
638 			/*
639 			 * We don't start a bbr rack timer if all we have is
640 			 * a FIN outstanding.
641 			 */
642 			goto activate_rxt;
643 		}
644 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
645 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
646 		idx = rsm->r_rtr_cnt - 1;
647 		exp = rsm->r_tim_lastsent[idx] + thresh;
648 		if (SEQ_GEQ(exp, cts)) {
649 			to = exp - cts;
650 			if (to < bbr->r_ctl.rc_min_to) {
651 				to = bbr->r_ctl.rc_min_to;
652 			}
653 		} else {
654 			to = bbr->r_ctl.rc_min_to;
655 		}
656 	} else {
657 		/* Ok we need to do a TLP not RACK */
658 		if (bbr->rc_tlp_in_progress != 0) {
659 			/*
660 			 * The previous send was a TLP.
661 			 */
662 			goto activate_rxt;
663 		}
664 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
665 		if (rsm == NULL) {
666 			/* We found no rsm to TLP with. */
667 			goto activate_rxt;
668 		}
669 		if (rsm->r_flags & BBR_HAS_FIN) {
670 			/* If its a FIN we don't do TLP */
671 			rsm = NULL;
672 			goto activate_rxt;
673 		}
674 		time_since_sent = 0;
675 		idx = rsm->r_rtr_cnt - 1;
676 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
677 			tstmp_touse = rsm->r_tim_lastsent[idx];
678 		else
679 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
680 		if (TSTMP_GT(tstmp_touse, cts))
681 		    time_since_sent = cts - tstmp_touse;
682 		is_tlp_timer = 1;
683 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
684 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
685 		if (thresh > time_since_sent)
686 			to = thresh - time_since_sent;
687 		else
688 			to = bbr->r_ctl.rc_min_to;
689 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
690 			/*
691 			 * If the TLP time works out to larger than the max
692 			 * RTO lets not do TLP.. just RTO.
693 			 */
694 			goto activate_rxt;
695 		}
696 		if ((bbr->rc_tlp_rtx_out == 1) &&
697 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
698 			/*
699 			 * Second retransmit of the same TLP
700 			 * lets not.
701 			 */
702 			bbr->rc_tlp_rtx_out = 0;
703 			goto activate_rxt;
704 		}
705 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
706 			/*
707 			 * The tail is no longer the last one I did a probe
708 			 * on
709 			 */
710 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
711 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
712 		}
713 	}
714 	if (is_tlp_timer == 0) {
715 		BBR_STAT_INC(bbr_to_arm_rack);
716 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
717 	} else {
718 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
719 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
720 			/*
721 			 * We have exceeded how many times we can retran the
722 			 * current TLP timer, switch to the RTO timer.
723 			 */
724 			goto activate_rxt;
725 		} else {
726 			BBR_STAT_INC(bbr_to_arm_tlp);
727 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
728 		}
729 	}
730 	return (to);
731 }
732 
733 static inline int32_t
734 bbr_minseg(struct tcp_bbr *bbr)
735 {
736 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
737 }
738 
739 static void
740 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
741 {
742 	struct inpcb *inp;
743 	struct hpts_diag diag;
744 	uint32_t delayed_ack = 0;
745 	uint32_t left = 0;
746 	uint32_t hpts_timeout;
747 	uint8_t stopped;
748 	int32_t delay_calc = 0;
749 	uint32_t prev_delay = 0;
750 
751 	inp = tp->t_inpcb;
752 	if (inp->inp_in_hpts) {
753 		/* A previous call is already set up */
754 		return;
755 	}
756 	if ((tp->t_state == TCPS_CLOSED) ||
757 	    (tp->t_state == TCPS_LISTEN)) {
758 		return;
759 	}
760 	stopped = bbr->rc_tmr_stopped;
761 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
762 		left = bbr->r_ctl.rc_timer_exp - cts;
763 	}
764 	bbr->r_ctl.rc_hpts_flags = 0;
765 	bbr->r_ctl.rc_timer_exp = 0;
766 	prev_delay = bbr->r_ctl.rc_last_delay_val;
767 	if (bbr->r_ctl.rc_last_delay_val &&
768 	    (slot == 0)) {
769 		/*
770 		 * If a previous pacer delay was in place we
771 		 * are not coming from the output side (where
772 		 * we calculate a delay, more likely a timer).
773 		 */
774 		slot = bbr->r_ctl.rc_last_delay_val;
775 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
776 			/* Compensate for time passed  */
777 			delay_calc = cts - bbr->rc_pacer_started;
778 			if (delay_calc <= slot)
779 				slot -= delay_calc;
780 		}
781 	}
782 	/* Do we have early to make up for by pushing out the pacing time? */
783 	if (bbr->r_agg_early_set) {
784 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
785 		slot += bbr->r_ctl.rc_agg_early;
786 		bbr->r_ctl.rc_agg_early = 0;
787 		bbr->r_agg_early_set = 0;
788 	}
789 	/* Are we running a total debt that needs to be compensated for? */
790 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
791 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
792 			/* We nuke the delay */
793 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
794 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
795 		} else {
796 			/* We nuke some of the delay, put in a minimal 100usecs  */
797 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
798 			bbr->r_ctl.rc_last_delay_val = slot = 100;
799 		}
800 	}
801 	bbr->r_ctl.rc_last_delay_val = slot;
802 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
803 	if (tp->t_flags & TF_DELACK) {
804 		if (bbr->rc_in_persist == 0) {
805 			delayed_ack = bbr_delack_time;
806 		} else {
807 			/*
808 			 * We are in persists and have
809 			 * gotten a new data element.
810 			 */
811 			if (hpts_timeout > bbr_delack_time) {
812 				/*
813 				 * Lets make the persists timer (which acks)
814 				 * be the smaller of hpts_timeout and bbr_delack_time.
815 				 */
816 				hpts_timeout = bbr_delack_time;
817 			}
818 		}
819 	}
820 	if (delayed_ack &&
821 	    ((hpts_timeout == 0) ||
822 	     (delayed_ack < hpts_timeout))) {
823 		/* We need a Delayed ack timer */
824 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
825 		hpts_timeout = delayed_ack;
826 	}
827 	if (slot) {
828 		/* Mark that we have a pacing timer up */
829 		BBR_STAT_INC(bbr_paced_segments);
830 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
831 	}
832 	/*
833 	 * If no timers are going to run and we will fall off thfe hptsi
834 	 * wheel, we resort to a keep-alive timer if its configured.
835 	 */
836 	if ((hpts_timeout == 0) &&
837 	    (slot == 0)) {
838 		if ((tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
839 		    (tp->t_state <= TCPS_CLOSING)) {
840 			/*
841 			 * Ok we have no timer (persists, rack, tlp, rxt  or
842 			 * del-ack), we don't have segments being paced. So
843 			 * all that is left is the keepalive timer.
844 			 */
845 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
846 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
847 			} else {
848 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
849 			}
850 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
851 		}
852 	}
853 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
854 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
855 		/*
856 		 * RACK, TLP, persists and RXT timers all are restartable
857 		 * based on actions input .. i.e we received a packet (ack
858 		 * or sack) and that changes things (rw, or snd_una etc).
859 		 * Thus we can restart them with a new value. For
860 		 * keep-alive, delayed_ack we keep track of what was left
861 		 * and restart the timer with a smaller value.
862 		 */
863 		if (left < hpts_timeout)
864 			hpts_timeout = left;
865 	}
866 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
867 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
868 		/*
869 		 * If configured to do so, and the timer is either
870 		 * the TLP or RXT timer, we need to increase the timeout
871 		 * by the pacing time. Consider the bottleneck at my
872 		 * machine as an example, we are sending something
873 		 * to start a TLP on. The last packet won't be emitted
874 		 * fully until the pacing time (the bottleneck will hold
875 		 * the data in place). Once the packet is emitted that
876 		 * is when we want to start waiting for the TLP. This
877 		 * is most evident with hardware pacing (where the nic
878 		 * is holding the packet(s) before emitting). But it
879 		 * can also show up in the network so we do it for all
880 		 * cases. Technically we would take off one packet from
881 		 * this extra delay but this is easier and being more
882 		 * conservative is probably better.
883 		 */
884 		hpts_timeout += slot;
885 	}
886 	if (hpts_timeout) {
887 		/*
888 		 * Hack alert for now we can't time-out over 2147 seconds (a
889 		 * bit more than 35min)
890 		 */
891 		if (hpts_timeout > 0x7ffffffe)
892 			hpts_timeout = 0x7ffffffe;
893 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
894 	} else
895 		bbr->r_ctl.rc_timer_exp = 0;
896 	if ((slot) &&
897 	    (bbr->rc_use_google ||
898 	     bbr->output_error_seen ||
899 	     (slot <= hpts_timeout))  ) {
900 		/*
901 		 * Tell LRO that it can queue packets while
902 		 * we pace.
903 		 */
904 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
905 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
906 		    (bbr->rc_cwnd_limited == 0)) {
907 			/*
908 			 * If we are not cwnd limited and we
909 			 * are running a rack timer we put on
910 			 * the do not disturbe even for sack.
911 			 */
912 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
913 		} else
914 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
915 		bbr->rc_pacer_started = cts;
916 
917 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
918 					   __LINE__, &diag);
919 		bbr->rc_timer_first = 0;
920 		bbr->bbr_timer_src = frm;
921 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
922 		bbr_log_hpts_diag(bbr, cts, &diag);
923 	} else if (hpts_timeout) {
924 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
925 					   __LINE__, &diag);
926 		/*
927 		 * We add the flag here as well if the slot is set,
928 		 * since hpts will call in to clear the queue first before
929 		 * calling the output routine (which does our timers).
930 		 * We don't want to set the flag if its just a timer
931 		 * else the arrival of data might (that causes us
932 		 * to send more) might get delayed. Imagine being
933 		 * on a keep-alive timer and a request comes in for
934 		 * more data.
935 		 */
936 		if (slot)
937 			bbr->rc_pacer_started = cts;
938 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
939 		    (bbr->rc_cwnd_limited == 0)) {
940 			/*
941 			 * For a rack timer, don't wake us even
942 			 * if a sack arrives as long as we are
943 			 * not cwnd limited.
944 			 */
945 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
946 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
947 		} else {
948 			/* All other timers wake us up */
949 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
950 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
951 		}
952 		bbr->bbr_timer_src = frm;
953 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
954 		bbr_log_hpts_diag(bbr, cts, &diag);
955 		bbr->rc_timer_first = 1;
956 	}
957 	bbr->rc_tmr_stopped = 0;
958 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
959 }
960 
961 static void
962 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
963 {
964 	/*
965 	 * We received an ack, and then did not call send or were bounced
966 	 * out due to the hpts was running. Now a timer is up as well, is it
967 	 * the right timer?
968 	 */
969 	struct inpcb *inp;
970 	struct bbr_sendmap *rsm;
971 	uint32_t hpts_timeout;
972 	int tmr_up;
973 
974 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
975 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
976 		return;
977 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
978 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
979 	    (tmr_up == PACE_TMR_RXT)) {
980 		/* Should be an RXT */
981 		return;
982 	}
983 	inp = bbr->rc_inp;
984 	if (rsm == NULL) {
985 		/* Nothing outstanding? */
986 		if (tp->t_flags & TF_DELACK) {
987 			if (tmr_up == PACE_TMR_DELACK)
988 				/*
989 				 * We are supposed to have delayed ack up
990 				 * and we do
991 				 */
992 				return;
993 		} else if (sbavail(&inp->inp_socket->so_snd) &&
994 		    (tmr_up == PACE_TMR_RXT)) {
995 			/*
996 			 * if we hit enobufs then we would expect the
997 			 * possiblity of nothing outstanding and the RXT up
998 			 * (and the hptsi timer).
999 			 */
1000 			return;
1001 		} else if (((tcp_always_keepalive ||
1002 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
1003 			    (tp->t_state <= TCPS_CLOSING)) &&
1004 			    (tmr_up == PACE_TMR_KEEP) &&
1005 		    (tp->snd_max == tp->snd_una)) {
1006 			/* We should have keep alive up and we do */
1007 			return;
1008 		}
1009 	}
1010 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1011 		if ((tp->t_flags & TF_SENTFIN) &&
1012 		    ((tp->snd_max - tp->snd_una) == 1) &&
1013 		    (rsm->r_flags & BBR_HAS_FIN)) {
1014 			/* needs to be a RXT */
1015 			if (tmr_up == PACE_TMR_RXT)
1016 				return;
1017 			else
1018 				goto wrong_timer;
1019 		} else if (tmr_up == PACE_TMR_RACK)
1020 			return;
1021 		else
1022 			goto wrong_timer;
1023 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1024 		/* Rack timer has priority if we have data out */
1025 		return;
1026 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1027 		    ((tmr_up == PACE_TMR_TLP) ||
1028 	    (tmr_up == PACE_TMR_RXT))) {
1029 		/*
1030 		 * Either a TLP or RXT is fine if no sack-passed is in place
1031 		 * and data is outstanding.
1032 		 */
1033 		return;
1034 	} else if (tmr_up == PACE_TMR_DELACK) {
1035 		/*
1036 		 * If the delayed ack was going to go off before the
1037 		 * rtx/tlp/rack timer were going to expire, then that would
1038 		 * be the timer in control. Note we don't check the time
1039 		 * here trusting the code is correct.
1040 		 */
1041 		return;
1042 	}
1043 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1044 	    ((tmr_up == PACE_TMR_RXT) ||
1045 	     (tmr_up == PACE_TMR_TLP) ||
1046 	     (tmr_up == PACE_TMR_RACK))) {
1047 		/*
1048 		 * We have outstanding data and
1049 		 * we *do* have a RACK, TLP or RXT
1050 		 * timer running. We won't restart
1051 		 * anything here since thats probably ok we
1052 		 * will get called with some timer here shortly.
1053 		 */
1054 		return;
1055 	}
1056 	/*
1057 	 * Ok the timer originally started is not what we want now. We will
1058 	 * force the hpts to be stopped if any, and restart with the slot
1059 	 * set to what was in the saved slot.
1060 	 */
1061 wrong_timer:
1062 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1063 		if (inp->inp_in_hpts)
1064 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
1065 		bbr_timer_cancel(bbr, __LINE__, cts);
1066 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1067 		    0);
1068 	} else {
1069 		/*
1070 		 * Output is hptsi so we just need to switch the type of
1071 		 * timer. We don't bother with keep-alive, since when we
1072 		 * jump through the output, it will start the keep-alive if
1073 		 * nothing is sent.
1074 		 *
1075 		 * We only need a delayed-ack added and or the hpts_timeout.
1076 		 */
1077 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1078 		if (tp->t_flags & TF_DELACK) {
1079 			if (hpts_timeout == 0) {
1080 				hpts_timeout = bbr_delack_time;
1081 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1082 			}
1083 			else if (hpts_timeout > bbr_delack_time) {
1084 				hpts_timeout = bbr_delack_time;
1085 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1086 			}
1087 		}
1088 		if (hpts_timeout) {
1089 			if (hpts_timeout > 0x7ffffffe)
1090 				hpts_timeout = 0x7ffffffe;
1091 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1092 		}
1093 	}
1094 }
1095 
1096 int32_t bbr_clear_lost = 0;
1097 
1098 /*
1099  * Considers the two time values now (cts) and earlier.
1100  * If cts is smaller than earlier, we could have
1101  * had a sequence wrap (our counter wraps every
1102  * 70 min or so) or it could be just clock skew
1103  * getting us two differnt time values. Clock skew
1104  * will show up within 10ms or so. So in such
1105  * a case (where cts is behind earlier time by
1106  * less than 10ms) we return 0. Otherwise we
1107  * return the true difference between them.
1108  */
1109 static inline uint32_t
1110 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1111 	/*
1112 	 * Given two timestamps, the current time stamp cts, and some other
1113 	 * time-stamp taken in theory earlier return the difference. The
1114 	 * trick is here sometimes locking will get the other timestamp
1115 	 * after the cts. If this occurs we need to return 0.
1116 	 */
1117 	if (TSTMP_GEQ(cts, earlier_time))
1118 		return (cts - earlier_time);
1119 	/*
1120 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1121 	 * If its more than 10ms difference then we had a time wrap. Else
1122 	 * its just the normal locking foo. I wonder if we should not go to
1123 	 * 64bit TS and get rid of this issue.
1124 	 */
1125 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1126 		return (0);
1127 	/*
1128 	 * Ok the time must have wrapped. So we need to answer a large
1129 	 * amount of time, which the normal subtraction should do.
1130 	 */
1131 	return (cts - earlier_time);
1132 }
1133 
1134 
1135 
1136 static int
1137 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1138 {
1139 	uint32_t stat;
1140 	int32_t error;
1141 
1142 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1143 	if (error || req->newptr == NULL)
1144 		return error;
1145 
1146 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1147 	if (error)
1148 		return (error);
1149 	if (stat == 1) {
1150 #ifdef BBR_INVARIANTS
1151 		printf("Clearing BBR lost counters\n");
1152 #endif
1153 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1154 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1155 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1156 	} else if (stat == 2) {
1157 #ifdef BBR_INVARIANTS
1158 		printf("Clearing BBR option counters\n");
1159 #endif
1160 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1161 	} else if (stat == 3) {
1162 #ifdef BBR_INVARIANTS
1163 		printf("Clearing BBR stats counters\n");
1164 #endif
1165 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1166 	} else if (stat == 4) {
1167 #ifdef BBR_INVARIANTS
1168 		printf("Clearing BBR out-size counters\n");
1169 #endif
1170 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1171 	}
1172 	bbr_clear_lost = 0;
1173 	return (0);
1174 }
1175 
1176 static void
1177 bbr_init_sysctls(void)
1178 {
1179 	struct sysctl_oid *bbr_probertt;
1180 	struct sysctl_oid *bbr_hptsi;
1181 	struct sysctl_oid *bbr_measure;
1182 	struct sysctl_oid *bbr_cwnd;
1183 	struct sysctl_oid *bbr_timeout;
1184 	struct sysctl_oid *bbr_states;
1185 	struct sysctl_oid *bbr_startup;
1186 	struct sysctl_oid *bbr_policer;
1187 
1188 	/* Probe rtt controls */
1189 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1190 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1191 	    OID_AUTO,
1192 	    "probertt",
1193 	    CTLFLAG_RW, 0,
1194 	    "");
1195 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1196 	    SYSCTL_CHILDREN(bbr_probertt),
1197 	    OID_AUTO, "gain", CTLFLAG_RW,
1198 	    &bbr_rttprobe_gain, 192,
1199 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1200 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1201 	    SYSCTL_CHILDREN(bbr_probertt),
1202 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1203 	    &bbr_rtt_probe_cwndtarg, 4,
1204 	    "How many mss's are outstanding during probe-rtt");
1205 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1206 	    SYSCTL_CHILDREN(bbr_probertt),
1207 	    OID_AUTO, "int", CTLFLAG_RW,
1208 	    &bbr_rtt_probe_limit, 4000000,
1209 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1210 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1211 	    SYSCTL_CHILDREN(bbr_probertt),
1212 	    OID_AUTO, "mintime", CTLFLAG_RW,
1213 	    &bbr_rtt_probe_time, 200000,
1214 	    "How many microseconds in probe-rtt");
1215 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1216 	    SYSCTL_CHILDREN(bbr_probertt),
1217 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1218 	    &bbr_filter_len_sec, 6,
1219 	    "How long in seconds does the rttProp filter run?");
1220 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1221 	    SYSCTL_CHILDREN(bbr_probertt),
1222 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1223 	    &bbr_drain_rtt, BBR_SRTT,
1224 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1225 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1226 	    SYSCTL_CHILDREN(bbr_probertt),
1227 	    OID_AUTO, "can_force", CTLFLAG_RW,
1228 	    &bbr_can_force_probertt, 0,
1229 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1230 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1231 	    SYSCTL_CHILDREN(bbr_probertt),
1232 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1233 	    &bbr_probertt_sets_rtt, 0,
1234 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1235 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1236 	    SYSCTL_CHILDREN(bbr_probertt),
1237 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1238 	    &bbr_can_adjust_probertt, 1,
1239 	    "Can we dynamically adjust the probe-rtt limits and times?");
1240 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1241 	    SYSCTL_CHILDREN(bbr_probertt),
1242 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1243 	    &bbr_is_ratio, 0,
1244 	    "is the limit to filter a ratio?");
1245 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1246 	    SYSCTL_CHILDREN(bbr_probertt),
1247 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1248 	    &bbr_prtt_slam_cwnd, 0,
1249 	    "Should we set/recover cwnd?");
1250 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1251 	    SYSCTL_CHILDREN(bbr_probertt),
1252 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1253 	    &bbr_can_use_ts_for_rtt, 1,
1254 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1255 
1256 	/* Pacing controls */
1257 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1258 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1259 	    OID_AUTO,
1260 	    "pacing",
1261 	    CTLFLAG_RW, 0,
1262 	    "");
1263 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1264 	    SYSCTL_CHILDREN(bbr_hptsi),
1265 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1266 	    &bbr_allow_hdwr_pacing, 1,
1267 	    "Do we allow hardware pacing?");
1268 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1269 	    SYSCTL_CHILDREN(bbr_hptsi),
1270 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1271 	    &bbr_hardware_pacing_limit, 4000,
1272 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1273 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1274 	    SYSCTL_CHILDREN(bbr_hptsi),
1275 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1276 	    &bbr_hdwr_pace_adjust, 2,
1277 	    "Multiplier to calculated tso size?");
1278 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1279 	    SYSCTL_CHILDREN(bbr_hptsi),
1280 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1281 	    &bbr_hdwr_pace_floor, 1,
1282 	    "Do we invoke the hardware pacing floor?");
1283 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1284 	    SYSCTL_CHILDREN(bbr_hptsi),
1285 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1286 	    &bbr_hdwr_pacing_delay_cnt, 10,
1287 	    "How many packets must be sent after hdwr pacing is enabled");
1288 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1289 	    SYSCTL_CHILDREN(bbr_hptsi),
1290 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1291 	    &bbr_cross_over, 3000000,
1292 	    "What is the point where we cross over to linux like TSO size set");
1293 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1294 	    SYSCTL_CHILDREN(bbr_hptsi),
1295 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1296 	    &bbr_hptsi_segments_delay_tar, 7000,
1297 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1298 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1299 	    SYSCTL_CHILDREN(bbr_hptsi),
1300 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1301 	    &bbr_include_enet_oh, 0,
1302 	    "Do we include the ethernet overhead in calculating pacing delay?");
1303 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1304 	    SYSCTL_CHILDREN(bbr_hptsi),
1305 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1306 	    &bbr_include_ip_oh, 1,
1307 	    "Do we include the IP overhead in calculating pacing delay?");
1308 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1309 	    SYSCTL_CHILDREN(bbr_hptsi),
1310 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1311 	    &bbr_include_tcp_oh, 0,
1312 	    "Do we include the TCP overhead in calculating pacing delay?");
1313 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1314 	    SYSCTL_CHILDREN(bbr_hptsi),
1315 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1316 	    &bbr_google_discount, 10,
1317 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1318 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1319 	    SYSCTL_CHILDREN(bbr_hptsi),
1320 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1321 	    &bbr_all_get_min, 0,
1322 	    "If you are less than a MSS do you just get the min?");
1323 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1324 	    SYSCTL_CHILDREN(bbr_hptsi),
1325 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1326 	    &bbr_hptsi_bytes_min, 1460,
1327 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1328 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1329 	    SYSCTL_CHILDREN(bbr_hptsi),
1330 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1331 	    &bbr_hptsi_segments_max, 6,
1332 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1333 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1334 	    SYSCTL_CHILDREN(bbr_hptsi),
1335 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1336 	    &bbr_hptsi_segments_floor, 1,
1337 	    "Minimum TSO size we will fall too in segments");
1338 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1339 	    SYSCTL_CHILDREN(bbr_hptsi),
1340 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1341 	    &bbr_hptsi_utter_max, 0,
1342 	    "The absolute maximum that any pacing (outside of hardware) can be");
1343 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1344 	    SYSCTL_CHILDREN(bbr_hptsi),
1345 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1346 	    &bbr_hptsi_per_second, 100,
1347 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1348 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1349 	    SYSCTL_CHILDREN(bbr_hptsi),
1350 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1351 	    &bbr_hptsi_max_mul, 1,
1352 	    "The multiplier for pace len max");
1353 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1354 	    SYSCTL_CHILDREN(bbr_hptsi),
1355 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1356 	    &bbr_hptsi_max_div, 2,
1357 	    "The divisor for pace len max");
1358 	/* Measurement controls */
1359 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1360 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1361 	    OID_AUTO,
1362 	    "measure",
1363 	    CTLFLAG_RW, 0,
1364 	    "Measurement controls");
1365 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1366 	    SYSCTL_CHILDREN(bbr_measure),
1367 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1368 	    &bbr_initial_bw_bps, 62500,
1369 	    "Minimum initial b/w in bytes per second");
1370 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1371 	    SYSCTL_CHILDREN(bbr_measure),
1372 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1373 	    &bbr_sack_not_required, 0,
1374 	    "Do we allow bbr to run on connections not supporting SACK?");
1375 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1376 	    SYSCTL_CHILDREN(bbr_measure),
1377 	    OID_AUTO, "use_google", CTLFLAG_RW,
1378 	    &bbr_use_google_algo, 0,
1379 	    "Use has close to google V1.0 has possible?");
1380 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1381 	    SYSCTL_CHILDREN(bbr_measure),
1382 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1383 	    &bbr_ts_limiting, 1,
1384 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1385 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1386 	    SYSCTL_CHILDREN(bbr_measure),
1387 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1388 	    &bbr_ts_can_raise, 0,
1389 	    "Can we raise the b/w via timestamp b/w calculation?");
1390 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1391 	    SYSCTL_CHILDREN(bbr_measure),
1392 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1393 	    &bbr_min_usec_delta, 20000,
1394 	    "How long in usec between ts of our sends in ts validation code?");
1395 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1396 	    SYSCTL_CHILDREN(bbr_measure),
1397 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1398 	    &bbr_min_peer_delta, 20,
1399 	    "What min numerical value should be between the peer deltas?");
1400 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1401 	    SYSCTL_CHILDREN(bbr_measure),
1402 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1403 	    &bbr_delta_percent, 150,
1404 	    "What percentage (150 = 15.0) do we allow variance for?");
1405 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1406 	    SYSCTL_CHILDREN(bbr_measure),
1407 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1408 	    &bbr_min_measurements_req, 1,
1409 	    "What is the minimum measurment count we need before we switch to our b/w estimate");
1410 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1411 	    SYSCTL_CHILDREN(bbr_measure),
1412 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1413 	    &bbr_no_pacing_until, 4,
1414 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1415 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1416 	    SYSCTL_CHILDREN(bbr_measure),
1417 	    OID_AUTO, "quanta", CTLFLAG_RW,
1418 	    &bbr_quanta, 2,
1419 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1420 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1421 	    SYSCTL_CHILDREN(bbr_measure),
1422 	    OID_AUTO, "noretran", CTLFLAG_RW,
1423 	    &bbr_no_retran, 0,
1424 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1425 	/* State controls */
1426 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1427 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1428 	    OID_AUTO,
1429 	    "states",
1430 	    CTLFLAG_RW, 0,
1431 	    "State controls");
1432 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1433 	    SYSCTL_CHILDREN(bbr_states),
1434 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1435 	    &bbr_uses_idle_restart, 0,
1436 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1437 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1438 	    SYSCTL_CHILDREN(bbr_states),
1439 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1440 	    &bbr_idle_restart_threshold, 100000,
1441 	    "How long must we be idle before we restart??");
1442 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1443 	    SYSCTL_CHILDREN(bbr_states),
1444 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1445 	    &bbr_state_is_pkt_epoch, 0,
1446 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1447 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1448 	    SYSCTL_CHILDREN(bbr_states),
1449 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1450 	    &bbr_rtt_gain_thresh, 0,
1451 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1452 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1453 	    SYSCTL_CHILDREN(bbr_states),
1454 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1455 	    &bbr_drain_floor, 88,
1456 	    "What is the lowest we can drain (pg) too?");
1457 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1458 	    SYSCTL_CHILDREN(bbr_states),
1459 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1460 	    &bbr_state_drain_2_tar, 1,
1461 	    "Do we drain to target in drain substate?");
1462 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1463 	    SYSCTL_CHILDREN(bbr_states),
1464 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1465 	    &bbr_gain_to_target, 1,
1466 	    "Does probe bw gain to target??");
1467 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1468 	    SYSCTL_CHILDREN(bbr_states),
1469 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1470 	    &bbr_gain_gets_extra_too, 1,
1471 	    "Does probe bw gain get the extra time too?");
1472 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1473 	    SYSCTL_CHILDREN(bbr_states),
1474 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1475 	    &bbr_drain_drop_div, 5,
1476 	    "Long drain drop divider?");
1477 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1478 	    SYSCTL_CHILDREN(bbr_states),
1479 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1480 	    &bbr_drain_drop_mul, 4,
1481 	    "Long drain drop multiplier?");
1482 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1483 	    SYSCTL_CHILDREN(bbr_states),
1484 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1485 	    &bbr_rand_ot, 50,
1486 	    "Random discount of the ot?");
1487 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1488 	    SYSCTL_CHILDREN(bbr_states),
1489 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1490 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1491 	    "How many packet-epochs does the b/w delivery rate last?");
1492 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1493 	    SYSCTL_CHILDREN(bbr_states),
1494 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1495 	    &bbr_sub_drain_app_limit, 0,
1496 	    "Does our sub-state drain invoke app limited if its long?");
1497 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1498 	    SYSCTL_CHILDREN(bbr_states),
1499 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1500 	    &bbr_sub_drain_slam_cwnd, 0,
1501 	    "Should we set/recover cwnd for sub-state drain?");
1502 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1503 	    SYSCTL_CHILDREN(bbr_states),
1504 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1505 	    &bbr_slam_cwnd_in_main_drain, 0,
1506 	    "Should we set/recover cwnd for main-state drain?");
1507 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1508 	    SYSCTL_CHILDREN(bbr_states),
1509 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1510 	    &google_allow_early_out, 1,
1511 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1512 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1513 	    SYSCTL_CHILDREN(bbr_states),
1514 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1515 	    &google_consider_lost, 1,
1516 	    "Should we have losses exit gain of probebw in google mode??");
1517 	/* Startup controls */
1518 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1519 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1520 	    OID_AUTO,
1521 	    "startup",
1522 	    CTLFLAG_RW, 0,
1523 	    "Startup controls");
1524 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1525 	    SYSCTL_CHILDREN(bbr_startup),
1526 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1527 	    &bbr_sends_full_iwnd, 1,
1528 	    "Do we not pace but burst out initial windows has our TSO size?");
1529 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1530 	    SYSCTL_CHILDREN(bbr_startup),
1531 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1532 	    &bbr_startup_loss_thresh, 2000,
1533 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1534 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1535 	    SYSCTL_CHILDREN(bbr_startup),
1536 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1537 	    &bbr_use_lower_gain_in_startup, 1,
1538 	    "Should we use a lower hptsi gain if we see loss in startup?");
1539 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1540 	    SYSCTL_CHILDREN(bbr_startup),
1541 	    OID_AUTO, "gain", CTLFLAG_RW,
1542 	    &bbr_start_exit, 25,
1543 	    "What gain percent do we need to see to stay in startup??");
1544 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1545 	    SYSCTL_CHILDREN(bbr_startup),
1546 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1547 	    &bbr_low_start_exit, 15,
1548 	    "What gain percent do we need to see to stay in the lower gain startup??");
1549 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1550 	    SYSCTL_CHILDREN(bbr_startup),
1551 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1552 	    &bbr_exit_startup_at_loss, 1,
1553 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1554 	/* CWND controls */
1555 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1556 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1557 	    OID_AUTO,
1558 	    "cwnd",
1559 	    CTLFLAG_RW, 0,
1560 	    "Cwnd controls");
1561 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1562 	    SYSCTL_CHILDREN(bbr_cwnd),
1563 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1564 	    &bbr_cwndtarget_rtt_touse, 0,
1565 	    "Target cwnd rtt measurment to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1566 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1567 	    SYSCTL_CHILDREN(bbr_cwnd),
1568 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1569 	    &bbr_cwnd_may_shrink, 0,
1570 	    "Can the cwnd shrink if it would grow to more than the target?");
1571 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1572 	    SYSCTL_CHILDREN(bbr_cwnd),
1573 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1574 	    &bbr_target_cwnd_mult_limit, 8,
1575 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1576 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1577 	    SYSCTL_CHILDREN(bbr_cwnd),
1578 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1579 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1580 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1581 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1582 	    SYSCTL_CHILDREN(bbr_cwnd),
1583 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1584 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1585 	    "What is the min cwnd (rttProp > 1ms)");
1586 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1587 	    SYSCTL_CHILDREN(bbr_cwnd),
1588 	    OID_AUTO, "initwin", CTLFLAG_RW,
1589 	    &bbr_def_init_win, 10,
1590 	    "What is the BBR initial window, if 0 use tcp version");
1591 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1592 	    SYSCTL_CHILDREN(bbr_cwnd),
1593 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1594 	    &bbr_do_red, 600,
1595 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1596 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1597 	    SYSCTL_CHILDREN(bbr_cwnd),
1598 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1599 	    &bbr_red_scale, 20000,
1600 	    "What RTT do we scale with?");
1601 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1602 	    SYSCTL_CHILDREN(bbr_cwnd),
1603 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1604 	    &bbr_red_growth_restrict, 1,
1605 	    "Do we restrict cwnd growth for whats in flight?");
1606 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1607 	    SYSCTL_CHILDREN(bbr_cwnd),
1608 	    OID_AUTO, "red_div", CTLFLAG_RW,
1609 	    &bbr_red_div, 2,
1610 	    "If we reduce whats the divisor?");
1611 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1612 	    SYSCTL_CHILDREN(bbr_cwnd),
1613 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1614 	    &bbr_red_mul, 1,
1615 	    "If we reduce whats the mulitiplier?");
1616 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1617 	    SYSCTL_CHILDREN(bbr_cwnd),
1618 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1619 	    &bbr_target_is_bbunit, 0,
1620 	    "Is the state target the pacing_gain or BBR_UNIT?");
1621 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1622 	    SYSCTL_CHILDREN(bbr_cwnd),
1623 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1624 	    &bbr_drop_limit, 0,
1625 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1626 
1627         /* Timeout controls */
1628 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1629 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1630 	    OID_AUTO,
1631 	    "timeout",
1632 	    CTLFLAG_RW, 0,
1633 	    "Time out controls");
1634 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1635 	    SYSCTL_CHILDREN(bbr_timeout),
1636 	    OID_AUTO, "delack", CTLFLAG_RW,
1637 	    &bbr_delack_time, 100000,
1638 	    "BBR's delayed ack time");
1639 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1640 	    SYSCTL_CHILDREN(bbr_timeout),
1641 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1642 	    &bbr_tlp_type_to_use, 3,
1643 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1644 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1645 	    SYSCTL_CHILDREN(bbr_timeout),
1646 	    OID_AUTO, "persmin", CTLFLAG_RW,
1647 	    &bbr_persist_min, 250000,
1648 	    "What is the minimum time in microseconds between persists");
1649 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1650 	    SYSCTL_CHILDREN(bbr_timeout),
1651 	    OID_AUTO, "persmax", CTLFLAG_RW,
1652 	    &bbr_persist_max, 1000000,
1653 	    "What is the largest delay in microseconds between persists");
1654 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1655 	    SYSCTL_CHILDREN(bbr_timeout),
1656 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1657 	    &bbr_tlp_min, 10000,
1658 	    "TLP Min timeout in usecs");
1659 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1660 	    SYSCTL_CHILDREN(bbr_timeout),
1661 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1662 	    &bbr_delayed_ack_time, 200000,
1663 	    "TLP delayed ack compensation value");
1664 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1665 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1666 	    OID_AUTO, "minrto", CTLFLAG_RW,
1667 	    &bbr_rto_min_ms, 30,
1668 	    "Minimum RTO in ms");
1669 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1670 	    SYSCTL_CHILDREN(bbr_timeout),
1671 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1672 	    &bbr_rto_max_sec, 4,
1673 	    "Maxiumum RTO in seconds -- should be at least as large as min_rto");
1674 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1675 	    SYSCTL_CHILDREN(bbr_timeout),
1676 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1677 	    &bbr_tlp_max_resend, 2,
1678 	    "How many times does TLP retry a single segment or multiple with no ACK");
1679 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1680 	    SYSCTL_CHILDREN(bbr_timeout),
1681 	    OID_AUTO, "minto", CTLFLAG_RW,
1682 	    &bbr_min_to, 1000,
1683 	    "Minimum rack timeout in useconds");
1684 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1685 	    SYSCTL_CHILDREN(bbr_timeout),
1686 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1687 	    &bbr_pkt_delay, 1000,
1688 	    "Extra RACK time (in useconds) besides reordering thresh");
1689 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1690 	    SYSCTL_CHILDREN(bbr_timeout),
1691 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1692 	    &bbr_incr_timers, 1,
1693 	    "Increase the RXT/TLP timer by the pacing time used?");
1694 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1695 	    SYSCTL_CHILDREN(bbr_timeout),
1696 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1697 	    &bbr_marks_rxt_sack_passed, 0,
1698 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1699 	/* Policer controls */
1700 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1701 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1702 	    OID_AUTO,
1703 	    "policer",
1704 	    CTLFLAG_RW, 0,
1705 	    "Policer controls");
1706 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1707 	    SYSCTL_CHILDREN(bbr_policer),
1708 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1709 	    &bbr_policer_detection_enabled, 1,
1710 	    "Is policer detection enabled??");
1711 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1712 	    SYSCTL_CHILDREN(bbr_policer),
1713 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1714 	    &bbr_lt_intvl_min_rtts, 4,
1715 	    "Minimum number of PE's?");
1716 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1717 	    SYSCTL_CHILDREN(bbr_policer),
1718 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1719 	    &bbr_lt_bw_diff, (4000/8),
1720 	    "Minimal bw diff?");
1721 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1722 	    SYSCTL_CHILDREN(bbr_policer),
1723 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1724 	    &bbr_lt_bw_ratio, 8,
1725 	    "Minimal bw diff?");
1726 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1727 	    SYSCTL_CHILDREN(bbr_policer),
1728 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1729 	    &bbr_policer_call_from_rack_to, 0,
1730 	    "Do we call the policer detection code from a rack-timeout?");
1731 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1732 	    SYSCTL_CHILDREN(bbr_policer),
1733 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1734 	    &bbr_lt_intvl_fp, 0,
1735 	    "What packet epoch do we do false-postive detection at (0=no)?");
1736 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1737 	    SYSCTL_CHILDREN(bbr_policer),
1738 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1739 	    &bbr_lt_loss_thresh, 196,
1740 	    "Loss threshold 196 = 19.6%?");
1741 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1742 	    SYSCTL_CHILDREN(bbr_policer),
1743 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1744 	    &bbr_lt_fd_thresh, 100,
1745 	    "What percentage is the false detection threshold (150=15.0)?");
1746 	/* All the rest */
1747 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1748 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1749 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1750 	    &bbr_use_rack_resend_cheat, 0,
1751 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1752 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1753 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1754 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1755 	    &bbr_error_base_paceout, 10000,
1756 	    "When we hit an error what is the min to pace out in usec's?");
1757 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1758 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1759 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1760 	    &bbr_max_net_error_cnt, 10,
1761 	    "When we hit this many errors in a row, kill the session?");
1762 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1763 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1764 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1765 	    &bbr_ignore_data_after_close, 1,
1766 	    "Do we hold off sending a RST until all pending data is ack'd");
1767 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1768 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1769 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1770 	    &bbr_resends_use_tso, 0,
1771 	    "Can resends use TSO?");
1772 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1773 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1774 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1775 	    &bbr_sack_block_limit, 128,
1776 	    "When do we start ignoring small sack blocks");
1777 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1778 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1779 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1780 	    &bbr_verbose_logging, 0,
1781 	    "Should BBR black box logging be verbose");
1782 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1783 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1784 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1785 	    &bbr_reorder_thresh, 2,
1786 	    "What factor for rack will be added when seeing reordering (shift right)");
1787 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1788 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1789 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1790 	    &bbr_reorder_fade, 0,
1791 	    "Does reorder detection fade, if so how many ms (0 means never)");
1792 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1793 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1794 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1795 	    &bbr_tlp_thresh, 1,
1796 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1797 	/* Stats and counters */
1798 	/* The pacing counters for hdwr/software can't be in the array */
1799 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1800 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1801 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1802 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1803 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1804 	    &bbr_hdwr_pacing_enobuf,
1805 	    "Total number of enobufs for hardware paced flows");
1806 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1807 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1808 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1809 	    &bbr_nohdwr_pacing_enobuf,
1810 	    "Total number of enobufs for non-hardware paced flows");
1811 
1812 
1813 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1814 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1815 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1816 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1817 	    &bbr_flows_whdwr_pacing,
1818 	    "Total number of hardware paced flows");
1819 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1820 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1821 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1822 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1823 	    &bbr_flows_nohdwr_pacing,
1824 	    "Total number of software paced flows");
1825 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1826 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1827 	    OID_AUTO, "stats", CTLFLAG_RD,
1828 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1829 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1830 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1831 	    OID_AUTO, "opts", CTLFLAG_RD,
1832 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1833 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1834 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1835 	    OID_AUTO, "lost", CTLFLAG_RD,
1836 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1837 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1838 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1839 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1840 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1841 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1842 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1843 	    OID_AUTO, "statetime", CTLFLAG_RD,
1844 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1845 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1846 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1847 	    OID_AUTO, "outsize", CTLFLAG_RD,
1848 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1849 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1850 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1851 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1852 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1853 }
1854 
1855 static inline int32_t
1856 bbr_progress_timeout_check(struct tcp_bbr *bbr)
1857 {
1858 	if (bbr->rc_tp->t_maxunacktime && bbr->rc_tp->t_acktime &&
1859 	    TSTMP_GT(ticks, bbr->rc_tp->t_acktime)) {
1860 		if ((((uint32_t)ticks - bbr->rc_tp->t_acktime)) >= bbr->rc_tp->t_maxunacktime) {
1861 			/*
1862 			 * There is an assumption here that the caller will
1863 			 * drop the connection, so we increment the
1864 			 * statistics.
1865 			 */
1866 			bbr_log_progress_event(bbr, bbr->rc_tp, ticks, PROGRESS_DROP, __LINE__);
1867 			BBR_STAT_INC(bbr_progress_drops);
1868 #ifdef NETFLIX_STATS
1869 			TCPSTAT_INC(tcps_progdrops);
1870 #endif
1871 			return (1);
1872 		}
1873 	}
1874 	return (0);
1875 }
1876 
1877 static void
1878 bbr_counter_destroy(void)
1879 {
1880 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1881 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1882 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1883 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1884 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1885 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1886 	counter_u64_free(bbr_flows_whdwr_pacing);
1887 	counter_u64_free(bbr_flows_nohdwr_pacing);
1888 
1889 }
1890 
1891 static __inline void
1892 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1893 {
1894 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1895 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1896 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1897 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1898 	l->bw_inuse = bbr_get_bw(bbr);
1899 	l->inflight = ctf_flight_size(bbr->rc_tp,
1900 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1901 	l->applimited = bbr->r_ctl.r_app_limited_until;
1902 	l->delivered = bbr->r_ctl.rc_delivered;
1903 	l->timeStamp = cts;
1904 	l->lost = bbr->r_ctl.rc_lost;
1905 	l->bbr_state = bbr->rc_bbr_state;
1906 	l->bbr_substate = bbr_state_val(bbr);
1907 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1908 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1909 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1910 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1911 	l->inhpts = bbr->rc_inp->inp_in_hpts;
1912 	l->ininput = bbr->rc_inp->inp_in_input;
1913 	l->use_lt_bw = bbr->rc_lt_use_bw;
1914 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1915 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1916 }
1917 
1918 static void
1919 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1920 {
1921 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1922 		union tcp_log_stackspecific log;
1923 
1924 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1925 		log.u_bbr.flex1 = 0;
1926 		log.u_bbr.flex2 = 0;
1927 		log.u_bbr.flex5 = 0;
1928 		log.u_bbr.flex3 = 0;
1929 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1930 		log.u_bbr.flex7 = reason;
1931 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1932 		log.u_bbr.flex8 = 0;
1933 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1934 		    &bbr->rc_inp->inp_socket->so_rcv,
1935 		    &bbr->rc_inp->inp_socket->so_snd,
1936 		    BBR_LOG_BW_RED_EV, 0,
1937 		    0, &log, false, &bbr->rc_tv);
1938 	}
1939 }
1940 
1941 static void
1942 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1943 {
1944 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1945 		union tcp_log_stackspecific log;
1946 
1947 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1948 		log.u_bbr.flex1 = seq;
1949 		log.u_bbr.flex2 = count;
1950 		log.u_bbr.flex8 = mode;
1951 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1952 		    &bbr->rc_inp->inp_socket->so_rcv,
1953 		    &bbr->rc_inp->inp_socket->so_snd,
1954 		    BBR_LOG_LOWGAIN, 0,
1955 		    0, &log, false, &bbr->rc_tv);
1956 	}
1957 }
1958 
1959 
1960 
1961 static void
1962 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1963     uint8_t reason, uint32_t p_maxseg, int len)
1964 {
1965 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1966 		union tcp_log_stackspecific log;
1967 
1968 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1969 		log.u_bbr.flex1 = p_maxseg;
1970 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1971 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1972 		log.u_bbr.flex4 = reason;
1973 		log.u_bbr.flex5 = bbr->rc_in_persist;
1974 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1975 		log.u_bbr.flex7 = p_maxseg;
1976 		log.u_bbr.flex8 = bbr->rc_in_persist;
1977 		log.u_bbr.pkts_out = 0;
1978 		log.u_bbr.applimited = len;
1979 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1980 		    &bbr->rc_inp->inp_socket->so_rcv,
1981 		    &bbr->rc_inp->inp_socket->so_snd,
1982 		    BBR_LOG_JUSTRET, 0,
1983 		    tlen, &log, false, &bbr->rc_tv);
1984 	}
1985 }
1986 
1987 
1988 static void
1989 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1990 {
1991 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1992 		union tcp_log_stackspecific log;
1993 
1994 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1995 		log.u_bbr.flex1 = seq;
1996 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1997 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1998 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1999 		    &bbr->rc_inp->inp_socket->so_rcv,
2000 		    &bbr->rc_inp->inp_socket->so_snd,
2001 		    BBR_LOG_ENTREC, 0,
2002 		    0, &log, false, &bbr->rc_tv);
2003 	}
2004 }
2005 
2006 static void
2007 bbr_log_msgsize_fail(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t len, uint32_t maxseg, uint32_t mtu, int32_t csum_flags, int32_t tso, uint32_t cts)
2008 {
2009 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
2010 		union tcp_log_stackspecific log;
2011 
2012 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2013 		log.u_bbr.flex1 = tso;
2014 		log.u_bbr.flex2 = maxseg;
2015 		log.u_bbr.flex3 = mtu;
2016 		log.u_bbr.flex4 = csum_flags;
2017 		TCP_LOG_EVENTP(tp, NULL,
2018 		    &bbr->rc_inp->inp_socket->so_rcv,
2019 		    &bbr->rc_inp->inp_socket->so_snd,
2020 		    BBR_LOG_MSGSIZE, 0,
2021 		    0, &log, false, &bbr->rc_tv);
2022 	}
2023 }
2024 
2025 static void
2026 bbr_log_flowend(struct tcp_bbr *bbr)
2027 {
2028 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2029 		union tcp_log_stackspecific log;
2030 		struct sockbuf *r, *s;
2031 		struct timeval tv;
2032 
2033 		if (bbr->rc_inp->inp_socket) {
2034 			r = &bbr->rc_inp->inp_socket->so_rcv;
2035 			s = &bbr->rc_inp->inp_socket->so_snd;
2036 		} else {
2037 			r = s = NULL;
2038 		}
2039 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2040 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2041 		    r, s,
2042 		    TCP_LOG_FLOWEND, 0,
2043 		    0, &log, false, &tv);
2044 	}
2045 }
2046 
2047 static void
2048 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2049     uint32_t lost, uint32_t del)
2050 {
2051 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2052 		union tcp_log_stackspecific log;
2053 
2054 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2055 		log.u_bbr.flex1 = lost;
2056 		log.u_bbr.flex2 = del;
2057 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2058 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2059 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2060 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2061 		log.u_bbr.flex7 = line;
2062 		log.u_bbr.flex8 = 0;
2063 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2064 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2065 		    &bbr->rc_inp->inp_socket->so_rcv,
2066 		    &bbr->rc_inp->inp_socket->so_snd,
2067 		    BBR_LOG_PKT_EPOCH, 0,
2068 		    0, &log, false, &bbr->rc_tv);
2069 	}
2070 }
2071 
2072 static void
2073 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2074 {
2075 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2076 		union tcp_log_stackspecific log;
2077 
2078 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2079 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2080 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2081 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2082 		log.u_bbr.flex7 = line;
2083 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2084 		    &bbr->rc_inp->inp_socket->so_rcv,
2085 		    &bbr->rc_inp->inp_socket->so_snd,
2086 		    BBR_LOG_TIME_EPOCH, 0,
2087 		    0, &log, false, &bbr->rc_tv);
2088 	}
2089 }
2090 
2091 static void
2092 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2093 {
2094 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2095 		union tcp_log_stackspecific log;
2096 
2097 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2098 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2099 		log.u_bbr.flex2 = new_tar;
2100 		log.u_bbr.flex3 = line;
2101 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2102 		log.u_bbr.flex5 = bbr_quanta;
2103 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2104 		log.u_bbr.flex7 = bbr->rc_last_options;
2105 		log.u_bbr.flex8 = meth;
2106 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2107 		    &bbr->rc_inp->inp_socket->so_rcv,
2108 		    &bbr->rc_inp->inp_socket->so_snd,
2109 		    BBR_LOG_STATE_TARGET, 0,
2110 		    0, &log, false, &bbr->rc_tv);
2111 	}
2112 
2113 }
2114 
2115 static void
2116 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2117 {
2118 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2119 		union tcp_log_stackspecific log;
2120 
2121 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2122 		log.u_bbr.flex1 = line;
2123 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2124 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2125 		if (bbr_state_is_pkt_epoch)
2126 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2127 		else
2128 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2129 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2130 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2131 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2132 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2133 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2134 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2135 		    &bbr->rc_inp->inp_socket->so_rcv,
2136 		    &bbr->rc_inp->inp_socket->so_snd,
2137 		    BBR_LOG_STATE, 0,
2138 		    0, &log, false, &bbr->rc_tv);
2139 	}
2140 }
2141 
2142 static void
2143 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2144 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2145 {
2146 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2147 		union tcp_log_stackspecific log;
2148 
2149 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2150 		log.u_bbr.flex1 = line;
2151 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2152 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2153 		log.u_bbr.flex4 = applied;
2154 		log.u_bbr.flex5 = rtt;
2155 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2156 		log.u_bbr.flex7 = cond;
2157 		log.u_bbr.flex8 = reas;
2158 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2159 		    &bbr->rc_inp->inp_socket->so_rcv,
2160 		    &bbr->rc_inp->inp_socket->so_snd,
2161 		    BBR_LOG_RTT_SHRINKS, 0,
2162 		    0, &log, false, &bbr->rc_tv);
2163 	}
2164 }
2165 
2166 static void
2167 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2168 {
2169 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2170 		union tcp_log_stackspecific log;
2171 
2172 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2173 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2174 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2175 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2176 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2177 		    &bbr->rc_inp->inp_socket->so_rcv,
2178 		    &bbr->rc_inp->inp_socket->so_snd,
2179 		    BBR_LOG_EXITREC, 0,
2180 		    0, &log, false, &bbr->rc_tv);
2181 	}
2182 }
2183 
2184 static void
2185 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2186     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2187 {
2188 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2189 		union tcp_log_stackspecific log;
2190 
2191 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2192 		log.u_bbr.flex1 = line;
2193 		log.u_bbr.flex2 = prev_acked;
2194 		log.u_bbr.flex3 = bytes_this_ack;
2195 		log.u_bbr.flex4 = chg;
2196 		log.u_bbr.flex5 = th_ack;
2197 		log.u_bbr.flex6 = target;
2198 		log.u_bbr.flex8 = meth;
2199 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2200 		    &bbr->rc_inp->inp_socket->so_rcv,
2201 		    &bbr->rc_inp->inp_socket->so_snd,
2202 		    BBR_LOG_CWND, 0,
2203 		    0, &log, false, &bbr->rc_tv);
2204 	}
2205 }
2206 
2207 static void
2208 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2209 {
2210 	/*
2211 	 * Log the rtt sample we are applying to the srtt algorithm in
2212 	 * useconds.
2213 	 */
2214 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2215 		union tcp_log_stackspecific log;
2216 
2217 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2218 		log.u_bbr.flex1 = rtt;
2219 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2220 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2221 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2222 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2223 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2224 		log.u_bbr.flex6 = tsin;
2225 		log.u_bbr.flex7 = 0;
2226 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2227 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2228 		    &bbr->rc_inp->inp_socket->so_rcv,
2229 		    &bbr->rc_inp->inp_socket->so_snd,
2230 		    TCP_LOG_RTT, 0,
2231 		    0, &log, false, &bbr->rc_tv);
2232 	}
2233 }
2234 
2235 static void
2236 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2237 {
2238 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2239 		union tcp_log_stackspecific log;
2240 
2241 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2242 		log.u_bbr.flex1 = time_in;
2243 		log.u_bbr.flex2 = line;
2244 		log.u_bbr.flex8 = enter_exit;
2245 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2246 		    &bbr->rc_inp->inp_socket->so_rcv,
2247 		    &bbr->rc_inp->inp_socket->so_snd,
2248 		    BBR_LOG_PERSIST, 0,
2249 		    0, &log, false, &bbr->rc_tv);
2250 	}
2251 }
2252 static void
2253 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2254 {
2255 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2256 		union tcp_log_stackspecific log;
2257 
2258 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2259 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2260 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2261 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2262 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2263 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2264 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2265 		    &bbr->rc_inp->inp_socket->so_rcv,
2266 		    &bbr->rc_inp->inp_socket->so_snd,
2267 		    BBR_LOG_ACKCLEAR, 0,
2268 		    0, &log, false, &bbr->rc_tv);
2269 	}
2270 }
2271 
2272 static void
2273 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2274 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2275 {
2276 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2277 		union tcp_log_stackspecific log;
2278 		struct timeval tv;
2279 
2280 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2281 		log.u_bbr.flex1 = nsegs;
2282 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2283 		if (m) {
2284 			struct timespec ts;
2285 
2286 			log.u_bbr.flex3 = m->m_flags;
2287 			if (m->m_flags & M_TSTMP) {
2288 				mbuf_tstmp2timespec(m, &ts);
2289 				tv.tv_sec = ts.tv_sec;
2290 				tv.tv_usec = ts.tv_nsec / 1000;
2291 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2292 			} else {
2293 				log.u_bbr.lt_epoch = 0;
2294 			}
2295 			if (m->m_flags & M_TSTMP_LRO) {
2296 				tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2297 				tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2298 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2299 			} else {
2300 				/* No arrival timestamp */
2301 				log.u_bbr.flex5 = 0;
2302 			}
2303 
2304 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2305 		} else {
2306 			log.u_bbr.flex3 = 0;
2307 			log.u_bbr.flex5 = 0;
2308 			log.u_bbr.flex6 = 0;
2309 			log.u_bbr.pkts_out = 0;
2310 		}
2311 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2312 		log.u_bbr.flex7 = bbr->r_wanted_output;
2313 		log.u_bbr.flex8 = bbr->rc_in_persist;
2314 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2315 		    &bbr->rc_inp->inp_socket->so_rcv,
2316 		    &bbr->rc_inp->inp_socket->so_snd,
2317 		    TCP_LOG_IN, 0,
2318 		    tlen, &log, true, &bbr->rc_tv);
2319 	}
2320 }
2321 
2322 static void
2323 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2324 {
2325 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2326 		union tcp_log_stackspecific log;
2327 
2328 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2329 		log.u_bbr.flex1 = did_out;
2330 		log.u_bbr.flex2 = nxt_pkt;
2331 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2332 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2333 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2334 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2335 		log.u_bbr.flex7 = bbr->r_wanted_output;
2336 		log.u_bbr.flex8 = bbr->rc_in_persist;
2337 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2338 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2339 		    &bbr->rc_inp->inp_socket->so_rcv,
2340 		    &bbr->rc_inp->inp_socket->so_snd,
2341 		    BBR_LOG_DOSEG_DONE, 0,
2342 		    0, &log, true, &bbr->rc_tv);
2343 	}
2344 }
2345 
2346 static void
2347 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2348     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2349 {
2350 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2351 		union tcp_log_stackspecific log;
2352 
2353 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2354 		log.u_bbr.flex1 = line;
2355 		log.u_bbr.flex2 = o_len;
2356 		log.u_bbr.flex3 = segcnt;
2357 		log.u_bbr.flex4 = segsiz;
2358 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2359 		    &bbr->rc_inp->inp_socket->so_rcv,
2360 		    &bbr->rc_inp->inp_socket->so_snd,
2361 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2362 		    len, &log, true, &bbr->rc_tv);
2363 	}
2364 }
2365 
2366 static void
2367 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2368 {
2369 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2370 		union tcp_log_stackspecific log;
2371 
2372 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2373 		log.u_bbr.flex1 = timers;
2374 		log.u_bbr.flex2 = ret;
2375 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2376 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2377 		log.u_bbr.flex5 = cts;
2378 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2379 		log.u_bbr.flex8 = hpts_calling;
2380 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2381 		    &bbr->rc_inp->inp_socket->so_rcv,
2382 		    &bbr->rc_inp->inp_socket->so_snd,
2383 		    BBR_LOG_TO_PROCESS, 0,
2384 		    0, &log, false, &bbr->rc_tv);
2385 	}
2386 }
2387 
2388 static void
2389 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2390 {
2391 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2392 		union tcp_log_stackspecific log;
2393 		uint64_t ar;
2394 
2395 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2396 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2397 		log.u_bbr.flex2 = 0;
2398 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2399 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2400 		ar >>= 32;
2401 		ar &= 0x00000000ffffffff;
2402 		log.u_bbr.flex4 = (uint32_t)ar;
2403 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2404 		ar &= 0x00000000ffffffff;
2405 		log.u_bbr.flex5 = (uint32_t)ar;
2406 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2407 		log.u_bbr.flex8 = to_num;
2408 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2409 		    &bbr->rc_inp->inp_socket->so_rcv,
2410 		    &bbr->rc_inp->inp_socket->so_snd,
2411 		    BBR_LOG_RTO, 0,
2412 		    0, &log, false, &bbr->rc_tv);
2413 	}
2414 }
2415 
2416 static void
2417 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2418 {
2419 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2420 		union tcp_log_stackspecific log;
2421 
2422 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2423 		log.u_bbr.flex1 = flex1;
2424 		log.u_bbr.flex2 = flex2;
2425 		log.u_bbr.flex3 = flex3;
2426 		log.u_bbr.flex4 = 0;
2427 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2428 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2429 		log.u_bbr.flex8 = reason;
2430 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2431 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2432 		    &bbr->rc_inp->inp_socket->so_rcv,
2433 		    &bbr->rc_inp->inp_socket->so_snd,
2434 		    BBR_LOG_REDUCE, 0,
2435 		    0, &log, false, &bbr->rc_tv);
2436 	}
2437 }
2438 
2439 static void
2440 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2441 {
2442 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2443 		union tcp_log_stackspecific log;
2444 
2445 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2446 		log.u_bbr.flex1 = diag->p_nxt_slot;
2447 		log.u_bbr.flex2 = diag->p_cur_slot;
2448 		log.u_bbr.flex3 = diag->slot_req;
2449 		log.u_bbr.flex4 = diag->inp_hptsslot;
2450 		log.u_bbr.flex5 = diag->slot_remaining;
2451 		log.u_bbr.flex6 = diag->need_new_to;
2452 		log.u_bbr.flex7 = diag->p_hpts_active;
2453 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2454 		/* Hijack other fields as needed  */
2455 		log.u_bbr.epoch = diag->have_slept;
2456 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2457 		log.u_bbr.pkts_out = diag->co_ret;
2458 		log.u_bbr.applimited = diag->hpts_sleep_time;
2459 		log.u_bbr.delivered = diag->p_prev_slot;
2460 		log.u_bbr.inflight = diag->p_runningtick;
2461 		log.u_bbr.bw_inuse = diag->wheel_tick;
2462 		log.u_bbr.rttProp = diag->wheel_cts;
2463 		log.u_bbr.delRate = diag->maxticks;
2464 		log.u_bbr.cur_del_rate = diag->p_curtick;
2465 		log.u_bbr.cur_del_rate <<= 32;
2466 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2467 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2468 		    &bbr->rc_inp->inp_socket->so_rcv,
2469 		    &bbr->rc_inp->inp_socket->so_snd,
2470 		    BBR_LOG_HPTSDIAG, 0,
2471 		    0, &log, false, &bbr->rc_tv);
2472 	}
2473 }
2474 
2475 static void
2476 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2477     uint32_t thresh, uint32_t to)
2478 {
2479 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2480 		union tcp_log_stackspecific log;
2481 
2482 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2483 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2484 		log.u_bbr.flex2 = time_since_sent;
2485 		log.u_bbr.flex3 = srtt;
2486 		log.u_bbr.flex4 = thresh;
2487 		log.u_bbr.flex5 = to;
2488 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2489 		log.u_bbr.flex8 = mode;
2490 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2491 		    &bbr->rc_inp->inp_socket->so_rcv,
2492 		    &bbr->rc_inp->inp_socket->so_snd,
2493 		    BBR_LOG_TIMERPREP, 0,
2494 		    0, &log, false, &bbr->rc_tv);
2495 	}
2496 }
2497 
2498 static void
2499 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2500     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2501 {
2502 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2503 		union tcp_log_stackspecific log;
2504 
2505 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2506 		log.u_bbr.flex1 = usecs;
2507 		log.u_bbr.flex2 = len;
2508 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2509 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2510 		if (override)
2511 			log.u_bbr.flex5 = (1 << 2);
2512 		else
2513 			log.u_bbr.flex5 = 0;
2514 		log.u_bbr.flex6 = override;
2515 		log.u_bbr.flex7 = gain;
2516 		log.u_bbr.flex8 = mod;
2517 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2518 		    &bbr->rc_inp->inp_socket->so_rcv,
2519 		    &bbr->rc_inp->inp_socket->so_snd,
2520 		    BBR_LOG_HPTSI_CALC, 0,
2521 		    len, &log, false, &bbr->rc_tv);
2522 	}
2523 }
2524 
2525 static void
2526 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2527 {
2528 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2529 		union tcp_log_stackspecific log;
2530 
2531 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2532 
2533 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2534 		log.u_bbr.flex2 = to;
2535 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2536 		log.u_bbr.flex4 = slot;
2537 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2538 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2539 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2540 		log.u_bbr.flex8 = which;
2541 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2542 		    &bbr->rc_inp->inp_socket->so_rcv,
2543 		    &bbr->rc_inp->inp_socket->so_snd,
2544 		    BBR_LOG_TIMERSTAR, 0,
2545 		    0, &log, false, &bbr->rc_tv);
2546 	}
2547 }
2548 
2549 static void
2550 bbr_log_thresh_choice(struct tcp_bbr *bbr, uint32_t cts, uint32_t thresh, uint32_t lro, uint32_t srtt, struct bbr_sendmap *rsm, uint8_t frm)
2551 {
2552 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2553 		union tcp_log_stackspecific log;
2554 
2555 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2556 		log.u_bbr.flex1 = thresh;
2557 		log.u_bbr.flex2 = lro;
2558 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2559 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2560 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2561 		log.u_bbr.flex6 = srtt;
2562 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2563 		log.u_bbr.flex8 = frm;
2564 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2565 		    &bbr->rc_inp->inp_socket->so_rcv,
2566 		    &bbr->rc_inp->inp_socket->so_snd,
2567 		    BBR_LOG_THRESH_CALC, 0,
2568 		    0, &log, false, &bbr->rc_tv);
2569 	}
2570 }
2571 
2572 static void
2573 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2574 {
2575 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2576 		union tcp_log_stackspecific log;
2577 
2578 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2579 		log.u_bbr.flex1 = line;
2580 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2581 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2582 		log.u_bbr.flex4 = bbr->rc_in_persist;
2583 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2584 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2585 		log.u_bbr.flex8 = hpts_removed;
2586 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2587 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2588 		    &bbr->rc_inp->inp_socket->so_rcv,
2589 		    &bbr->rc_inp->inp_socket->so_snd,
2590 		    BBR_LOG_TIMERCANC, 0,
2591 		    0, &log, false, &bbr->rc_tv);
2592 	}
2593 }
2594 
2595 
2596 static void
2597 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2598 {
2599 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2600 		union tcp_log_stackspecific log;
2601 
2602 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2603 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2604 		log.u_bbr.flex2 = (peer_delta >> 32);
2605 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2606 		log.u_bbr.flex4 = (delta >> 32);
2607 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2608 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2609 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2610 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2611 		    &bbr->rc_inp->inp_socket->so_rcv,
2612 		    &bbr->rc_inp->inp_socket->so_snd,
2613 		    BBR_LOG_TSTMP_VAL, 0,
2614 		    0, &log, false, &bbr->rc_tv);
2615 
2616 	}
2617 }
2618 
2619 static void
2620 bbr_log_type_tsosize(struct tcp_bbr *bbr, uint32_t cts, uint32_t tsosz, uint32_t tls, uint32_t old_val, uint32_t maxseg, int hdwr)
2621 {
2622 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2623 		union tcp_log_stackspecific log;
2624 
2625 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2626 		log.u_bbr.flex1 = tsosz;
2627 		log.u_bbr.flex2 = tls;
2628 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2629 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2630 		log.u_bbr.flex5 = old_val;
2631 		log.u_bbr.flex6 = maxseg;
2632 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2633 		log.u_bbr.flex7 <<= 1;
2634 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2635 		if (hdwr)
2636 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2637 		else
2638 			log.u_bbr.flex8 = bbr->rc_use_google;
2639 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2640 		    &bbr->rc_inp->inp_socket->so_rcv,
2641 		    &bbr->rc_inp->inp_socket->so_snd,
2642 		    BBR_LOG_BBRTSO, 0,
2643 		    0, &log, false, &bbr->rc_tv);
2644 	}
2645 }
2646 
2647 static void
2648 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2649 		      uint32_t flags, uint32_t line)
2650 {
2651 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2652 		union tcp_log_stackspecific log;
2653 
2654 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2655 		log.u_bbr.flex1 = line;
2656 		log.u_bbr.flex2 = rsm->r_start;
2657 		log.u_bbr.flex3 = rsm->r_end;
2658 		log.u_bbr.flex4 = rsm->r_delivered;
2659 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2660 		log.u_bbr.flex6 = rsm->r_dupack;
2661 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2662 		log.u_bbr.flex8 = rsm->r_flags;
2663 		/* Hijack the pkts_out fids */
2664 		log.u_bbr.applimited = flags;
2665 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2666 		    &bbr->rc_inp->inp_socket->so_rcv,
2667 		    &bbr->rc_inp->inp_socket->so_snd,
2668 		    BBR_RSM_CLEARED, 0,
2669 		    0, &log, false, &bbr->rc_tv);
2670 	}
2671 }
2672 
2673 static void
2674 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2675     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2676     uint32_t flex6, uint32_t pkts_out, int flex7,
2677     uint32_t flex4, uint32_t flex1)
2678 {
2679 
2680 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2681 		union tcp_log_stackspecific log;
2682 
2683 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2684 		log.u_bbr.flex1 = flex1;
2685 		log.u_bbr.flex2 = flex2;
2686 		log.u_bbr.flex3 = flex3;
2687 		log.u_bbr.flex4 = flex4;
2688 		log.u_bbr.flex5 = flex5;
2689 		log.u_bbr.flex6 = flex6;
2690 		log.u_bbr.flex7 = flex7;
2691 		/* Hijack the pkts_out fids */
2692 		log.u_bbr.pkts_out = pkts_out;
2693 		log.u_bbr.flex8 = flex8;
2694 		if (bbr->rc_ack_was_delayed)
2695 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2696 		else
2697 			log.u_bbr.epoch = 0;
2698 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2699 		    &bbr->rc_inp->inp_socket->so_rcv,
2700 		    &bbr->rc_inp->inp_socket->so_snd,
2701 		    BBR_LOG_BBRUPD, 0,
2702 		    flex2, &log, false, &bbr->rc_tv);
2703 	}
2704 }
2705 
2706 
2707 static void
2708 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2709 	uint32_t newbw, uint32_t obw, uint32_t diff,
2710 	uint32_t tim)
2711 {
2712 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2713 		union tcp_log_stackspecific log;
2714 
2715 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2716 		log.u_bbr.flex1 = reason;
2717 		log.u_bbr.flex2 = newbw;
2718 		log.u_bbr.flex3 = obw;
2719 		log.u_bbr.flex4 = diff;
2720 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2721 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2722 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2723 		log.u_bbr.pkts_out = tim;
2724 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2725 		if (bbr->rc_lt_use_bw == 0)
2726 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2727 		else
2728 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2729 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2730 		    &bbr->rc_inp->inp_socket->so_rcv,
2731 		    &bbr->rc_inp->inp_socket->so_snd,
2732 		    BBR_LOG_BWSAMP, 0,
2733 		    0, &log, false, &bbr->rc_tv);
2734 	}
2735 }
2736 
2737 static inline void
2738 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2739 {
2740 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2741 		union tcp_log_stackspecific log;
2742 
2743 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2744 		log.u_bbr.flex1 = line;
2745 		log.u_bbr.flex2 = tick;
2746 		log.u_bbr.flex3 = tp->t_maxunacktime;
2747 		log.u_bbr.flex4 = tp->t_acktime;
2748 		log.u_bbr.flex8 = event;
2749 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2750 		    &bbr->rc_inp->inp_socket->so_rcv,
2751 		    &bbr->rc_inp->inp_socket->so_snd,
2752 		    BBR_LOG_PROGRESS, 0,
2753 		    0, &log, false, &bbr->rc_tv);
2754 	}
2755 }
2756 
2757 static void
2758 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2759 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2760 			 int error)
2761 {
2762 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2763 		union tcp_log_stackspecific log;
2764 
2765 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2766 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2767 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2768 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2769 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2770 		log.u_bbr.bw_inuse = rate;
2771 		log.u_bbr.flex5 = line;
2772 		log.u_bbr.flex6 = error;
2773 		log.u_bbr.flex8 = bbr->skip_gain;
2774 		log.u_bbr.flex8 <<= 1;
2775 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2776 		log.u_bbr.flex8 <<= 1;
2777 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2778 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2779 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2780 		    &bbr->rc_inp->inp_socket->so_rcv,
2781 		    &bbr->rc_inp->inp_socket->so_snd,
2782 		    BBR_LOG_HDWR_PACE, 0,
2783 		    0, &log, false, &bbr->rc_tv);
2784 	}
2785 }
2786 
2787 static void
2788 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot, uint32_t del_by, uint32_t cts, uint32_t line, uint32_t prev_delay)
2789 {
2790 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2791 		union tcp_log_stackspecific log;
2792 
2793 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2794 		log.u_bbr.flex1 = slot;
2795 		log.u_bbr.flex2 = del_by;
2796 		log.u_bbr.flex3 = prev_delay;
2797 		log.u_bbr.flex4 = line;
2798 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2799 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2800 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2801 		log.u_bbr.flex8 = bbr->rc_in_persist;
2802 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2803 		    &bbr->rc_inp->inp_socket->so_rcv,
2804 		    &bbr->rc_inp->inp_socket->so_snd,
2805 		    BBR_LOG_BBRSND, 0,
2806 		    len, &log, false, &bbr->rc_tv);
2807 	}
2808 }
2809 
2810 static void
2811 bbr_log_type_bbrrttprop(struct tcp_bbr *bbr, uint32_t t, uint32_t end, uint32_t tsconv, uint32_t cts, int32_t match, uint32_t seq, uint8_t flags)
2812 {
2813 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2814 		union tcp_log_stackspecific log;
2815 
2816 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2817 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2818 		log.u_bbr.flex2 = 0;
2819 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2820 		log.u_bbr.flex4 = end;
2821 		log.u_bbr.flex5 = seq;
2822 		log.u_bbr.flex6 = t;
2823 		log.u_bbr.flex7 = match;
2824 		log.u_bbr.flex8 = flags;
2825 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2826 		    &bbr->rc_inp->inp_socket->so_rcv,
2827 		    &bbr->rc_inp->inp_socket->so_snd,
2828 		    BBR_LOG_BBRRTT, 0,
2829 		    0, &log, false, &bbr->rc_tv);
2830 	}
2831 }
2832 
2833 static void
2834 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2835 {
2836 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2837 		union tcp_log_stackspecific log;
2838 
2839 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2840 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2841 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2842 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2843 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2844 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2845 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2846 		log.u_bbr.flex7 = 0;
2847 		log.u_bbr.flex8 = entry_method;
2848 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2849 		    &bbr->rc_inp->inp_socket->so_rcv,
2850 		    &bbr->rc_inp->inp_socket->so_snd,
2851 		    BBR_LOG_EXIT_GAIN, 0,
2852 		    0, &log, false, &bbr->rc_tv);
2853 	}
2854 }
2855 
2856 static void
2857 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2858 {
2859 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2860 		union tcp_log_stackspecific log;
2861 
2862 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2863 		/* R-HU */
2864 		log.u_bbr.flex1 = 0;
2865 		log.u_bbr.flex2 = 0;
2866 		log.u_bbr.flex3 = 0;
2867 		log.u_bbr.flex4 = 0;
2868 		log.u_bbr.flex7 = 0;
2869 		log.u_bbr.flex8 = settings_desired;
2870 
2871 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2872 		    &bbr->rc_inp->inp_socket->so_rcv,
2873 		    &bbr->rc_inp->inp_socket->so_snd,
2874 		    BBR_LOG_SETTINGS_CHG, 0,
2875 		    0, &log, false, &bbr->rc_tv);
2876 	}
2877 }
2878 
2879 /*
2880  * Returns the bw from the our filter.
2881  */
2882 static inline uint64_t
2883 bbr_get_full_bw(struct tcp_bbr *bbr)
2884 {
2885 	uint64_t bw;
2886 
2887 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2888 
2889 	return (bw);
2890 }
2891 
2892 static inline void
2893 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2894 {
2895 	uint64_t calclr;
2896 	uint32_t lost, del;
2897 
2898 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2899 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2900 	else
2901 		lost = 0;
2902 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2903 	if (lost == 0)  {
2904 		calclr = 0;
2905 	} else if (del) {
2906 		calclr = lost;
2907 		calclr *= (uint64_t)1000;
2908 		calclr /= (uint64_t)del;
2909 	} else {
2910 		/* Nothing delivered? 100.0% loss */
2911 		calclr = 1000;
2912 	}
2913 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2914 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2915 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2916 	bbr->r_ctl.rc_pkt_epoch++;
2917 	if (bbr->rc_no_pacing &&
2918 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2919 		bbr->rc_no_pacing = 0;
2920 		tcp_bbr_tso_size_check(bbr, cts);
2921 	}
2922 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2923 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2924 	/* What was our loss rate */
2925 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2926 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2927 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2928 }
2929 
2930 static inline void
2931 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2932 {
2933 	uint32_t epoch_time;
2934 
2935 	/* Tick the RTT clock */
2936 	bbr->r_ctl.rc_rtt_epoch++;
2937 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2938 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2939 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2940 }
2941 
2942 
2943 static inline void
2944 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2945 {
2946 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2947 		bbr->rc_is_pkt_epoch_now = 1;
2948 	}
2949 }
2950 
2951 /*
2952  * Returns the bw from either the b/w filter
2953  * or from the lt_bw (if the connection is being
2954  * policed).
2955  */
2956 static inline uint64_t
2957 __bbr_get_bw(struct tcp_bbr *bbr)
2958 {
2959 	uint64_t bw, min_bw;
2960 	uint64_t rtt;
2961 	int gm_measure_cnt = 1;
2962 
2963 	/*
2964 	 * For startup we make, like google, a
2965 	 * minimum b/w. This is generated from the
2966 	 * IW and the rttProp. We do fall back to srtt
2967 	 * if for some reason (initial handshake) we don't
2968 	 * have a rttProp. We, in the worst case, fall back
2969 	 * to the configured min_bw (rc_initial_hptsi_bw).
2970 	 */
2971 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2972 		/* Attempt first to use rttProp */
2973 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2974 		if (rtt && (rtt < 0xffffffff)) {
2975 measure:
2976 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2977 				((uint64_t)1000000);
2978 			min_bw /= rtt;
2979 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2980 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2981 			}
2982 
2983 		} else if (bbr->rc_tp->t_srtt != 0) {
2984 			/* No rttProp, use srtt? */
2985 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2986 			goto measure;
2987 		} else {
2988 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2989 		}
2990 	} else
2991 		min_bw = 0;
2992 
2993 	if ((bbr->rc_past_init_win == 0) &&
2994 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2995 		bbr->rc_past_init_win = 1;
2996 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2997 		gm_measure_cnt = 0;
2998 	if (gm_measure_cnt &&
2999 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
3000 	     (bbr->rc_past_init_win == 0))) {
3001 		/* For google we use our guess rate until we get 1 measurement */
3002 
3003 use_initial_window:
3004 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
3005 		if (rtt && (rtt < 0xffffffff)) {
3006 			/*
3007 			 * We have an RTT measurment. Use that in
3008 			 * combination with our initial window to calculate
3009 			 * a b/w.
3010 			 */
3011 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
3012 				((uint64_t)1000000);
3013 			bw /= rtt;
3014 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
3015 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
3016 			}
3017 		} else {
3018 			/* Drop back to the 40 and punt to a default */
3019 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
3020 		}
3021 		if (bw < 1)
3022 			/* Probably should panic */
3023 			bw = 1;
3024 		if (bw > min_bw)
3025 			return (bw);
3026 		else
3027 			return (min_bw);
3028 	}
3029 	if (bbr->rc_lt_use_bw)
3030 		bw = bbr->r_ctl.rc_lt_bw;
3031 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
3032 		bw = bbr->r_ctl.red_bw;
3033 	else
3034 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3035 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3036 		/*
3037 		 * Enforce user set rate limit, keep in mind that
3038 		 * t_peakrate_thr is in B/s already
3039 		 */
3040 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3041 	}
3042 	if (bw == 0) {
3043 		/* We should not be at 0, go to the initial window then  */
3044 		goto use_initial_window;
3045 	}
3046 	if (bw < 1)
3047 		/* Probably should panic */
3048 		bw = 1;
3049 	if (bw < min_bw)
3050 		bw = min_bw;
3051 	return (bw);
3052 }
3053 
3054 static inline uint64_t
3055 bbr_get_bw(struct tcp_bbr *bbr)
3056 {
3057 	uint64_t bw;
3058 
3059 	bw = __bbr_get_bw(bbr);
3060 	return (bw);
3061 }
3062 
3063 static inline void
3064 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3065 {
3066 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3067 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3068 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3069 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3070 }
3071 
3072 static inline void
3073 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3074 {
3075 	bbr->rc_lt_is_sampling = 0;
3076 	bbr->rc_lt_use_bw = 0;
3077 	bbr->r_ctl.rc_lt_bw = 0;
3078 	bbr_reset_lt_bw_interval(bbr, cts);
3079 }
3080 
3081 static inline void
3082 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3083 {
3084 	uint64_t diff;
3085 
3086 	/* Do we have a previous sample? */
3087 	if (bbr->r_ctl.rc_lt_bw) {
3088 		/* Get the diff in bytes per second */
3089 		if (bbr->r_ctl.rc_lt_bw > bw)
3090 			diff = bbr->r_ctl.rc_lt_bw - bw;
3091 		else
3092 			diff = bw - bbr->r_ctl.rc_lt_bw;
3093 		if ((diff <= bbr_lt_bw_diff) ||
3094 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3095 			/* Consider us policed */
3096 			uint32_t saved_bw;
3097 
3098 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3099 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3100 			bbr->rc_lt_use_bw = 1;
3101 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3102 			/*
3103 			 * Use pkt based epoch for measuring length of
3104 			 * policer up
3105 			 */
3106 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3107 			/*
3108 			 * reason 4 is we need to start consider being
3109 			 * policed
3110 			 */
3111 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3112 			return;
3113 		}
3114 	}
3115 	bbr->r_ctl.rc_lt_bw = bw;
3116 	bbr_reset_lt_bw_interval(bbr, cts);
3117 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3118 }
3119 
3120 /*
3121  * RRS: Copied from user space!
3122  * Calculate a uniformly distributed random number less than upper_bound
3123  * avoiding "modulo bias".
3124  *
3125  * Uniformity is achieved by generating new random numbers until the one
3126  * returned is outside the range [0, 2**32 % upper_bound).  This
3127  * guarantees the selected random number will be inside
3128  * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
3129  * after reduction modulo upper_bound.
3130  */
3131 static uint32_t
3132 arc4random_uniform(uint32_t upper_bound)
3133 {
3134 	uint32_t r, min;
3135 
3136 	if (upper_bound < 2)
3137 		return 0;
3138 
3139 	/* 2**32 % x == (2**32 - x) % x */
3140 	min = -upper_bound % upper_bound;
3141 
3142 	/*
3143 	 * This could theoretically loop forever but each retry has
3144 	 * p > 0.5 (worst case, usually far better) of selecting a
3145 	 * number inside the range we need, so it should rarely need
3146 	 * to re-roll.
3147 	 */
3148 	for (;;) {
3149 		r = arc4random();
3150 		if (r >= min)
3151 			break;
3152 	}
3153 
3154 	return r % upper_bound;
3155 }
3156 
3157 static void
3158 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3159 {
3160 	uint32_t ran, deduct;
3161 
3162 	ran = arc4random_uniform(bbr_rand_ot);
3163 	if (ran) {
3164 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3165 		bbr->r_ctl.rc_level_state_extra -= deduct;
3166 	}
3167 }
3168 /*
3169  * Return randomly the starting state
3170  * to use in probebw.
3171  */
3172 static uint8_t
3173 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3174 {
3175 	uint32_t ran;
3176 	uint8_t ret_val;
3177 
3178 	/* Initialize the offset to 0 */
3179 	bbr->r_ctl.rc_exta_time_gd = 0;
3180 	bbr->rc_hit_state_1 = 0;
3181 	bbr->r_ctl.rc_level_state_extra = 0;
3182 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3183 	/*
3184 	 * The math works funny here :) the return value is used to set the
3185 	 * substate and then the state change is called which increments by
3186 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3187 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3188 	 * we return 1 - 7, so we dont return 0 and end up starting in
3189 	 * state 1 (DRAIN).
3190 	 */
3191 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3192 	/* Set an epoch */
3193 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3194 		bbr_set_epoch(bbr, cts, __LINE__);
3195 
3196 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3197 	return (ret_val);
3198 }
3199 
3200 static void
3201 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3202 {
3203 	uint32_t diff, d_time;
3204 	uint64_t del_time, bw, lost, delivered;
3205 
3206 	if (bbr->r_use_policer == 0)
3207 		return;
3208 	if (bbr->rc_lt_use_bw) {
3209 		/* We are using lt bw do we stop yet? */
3210 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3211 		if (diff > bbr_lt_bw_max_rtts) {
3212 			/* Reset it all */
3213 reset_all:
3214 			bbr_reset_lt_bw_sampling(bbr, cts);
3215 			if (bbr->rc_filled_pipe) {
3216 				bbr_set_epoch(bbr, cts, __LINE__);
3217 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3218 				bbr_substate_change(bbr, cts, __LINE__, 0);
3219 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3220 				bbr_log_type_statechange(bbr, cts, __LINE__);
3221 			} else {
3222 				/*
3223 				 * This should not happen really
3224 				 * unless we remove the startup/drain
3225 				 * restrictions above.
3226 				 */
3227 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3228 				bbr_set_epoch(bbr, cts, __LINE__);
3229 				bbr->r_ctl.rc_bbr_state_time = cts;
3230 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3231 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3232 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3233 				bbr_set_state_target(bbr, __LINE__);
3234 				bbr_log_type_statechange(bbr, cts, __LINE__);
3235 			}
3236 			/* reason 0 is to stop using lt-bw */
3237 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3238 			return;
3239 		}
3240 		if (bbr_lt_intvl_fp == 0) {
3241 			/* Not doing false-postive detection */
3242 			return;
3243 		}
3244 		/* False positive detection */
3245 		if (diff == bbr_lt_intvl_fp) {
3246 			/* At bbr_lt_intvl_fp we record the lost */
3247 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3248 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3249 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3250 			/* Now is our loss rate still high? */
3251 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3252 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3253 			if ((delivered == 0) ||
3254 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3255 				/* No still below our threshold */
3256 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3257 			} else {
3258 				/* Yikes its still high, it must be a false positive */
3259 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3260 				goto reset_all;
3261 			}
3262 		}
3263 		return;
3264 	}
3265 	/*
3266 	 * Wait for the first loss before sampling, to let the policer
3267 	 * exhaust its tokens and estimate the steady-state rate allowed by
3268 	 * the policer. Starting samples earlier includes bursts that
3269 	 * over-estimate the bw.
3270 	 */
3271 	if (bbr->rc_lt_is_sampling == 0) {
3272 		/* reason 1 is to begin doing the sampling  */
3273 		if (loss_detected == 0)
3274 			return;
3275 		bbr_reset_lt_bw_interval(bbr, cts);
3276 		bbr->rc_lt_is_sampling = 1;
3277 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3278 		return;
3279 	}
3280 	/* Now how long were we delivering long term last> */
3281 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3282 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3283 	else
3284 		d_time = 0;
3285 
3286 	/* To avoid underestimates, reset sampling if we run out of data. */
3287 	if (bbr->r_ctl.r_app_limited_until) {
3288 		/* Can not measure in app-limited state */
3289 		bbr_reset_lt_bw_sampling(bbr, cts);
3290 		/* reason 2 is to reset sampling due to app limits  */
3291 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3292 		return;
3293 	}
3294 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3295 	if (diff < bbr_lt_intvl_min_rtts) {
3296 		/*
3297 		 * need more samples (we don't
3298 		 * start on a round like linux so
3299 		 * we need 1 more).
3300 		 */
3301 		/* 6 is not_enough time or no-loss */
3302 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3303 		return;
3304 	}
3305 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3306 		/*
3307 		 * For now if we wait too long, reset all sampling. We need
3308 		 * to do some research here, its possible that we should
3309 		 * base this on how much loss as occurred.. something like
3310 		 * if its under 10% (or some thresh) reset all otherwise
3311 		 * don't.  Thats for phase II I guess.
3312 		 */
3313 		bbr_reset_lt_bw_sampling(bbr, cts);
3314  		/* reason 3 is to reset sampling due too long of sampling */
3315 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3316 		return;
3317 	}
3318 	/*
3319 	 * End sampling interval when a packet is lost, so we estimate the
3320 	 * policer tokens were exhausted. Stopping the sampling before the
3321 	 * tokens are exhausted under-estimates the policed rate.
3322 	 */
3323 	if (loss_detected == 0) {
3324 		/* 6 is not_enough time or no-loss */
3325 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3326 		return;
3327 	}
3328 	/* Calculate packets lost and delivered in sampling interval. */
3329 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3330 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3331 	if ((delivered == 0) ||
3332 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3333 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3334 		return;
3335 	}
3336 	if (d_time < 1000) {
3337 		/* Not enough time. wait */
3338 		/* 6 is not_enough time or no-loss */
3339 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3340 		return;
3341 	}
3342 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3343 		/* Too long */
3344 		bbr_reset_lt_bw_sampling(bbr, cts);
3345  		/* reason 3 is to reset sampling due too long of sampling */
3346 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3347 		return;
3348 	}
3349 	del_time = d_time;
3350 	bw = delivered;
3351 	bw *= (uint64_t)USECS_IN_SECOND;
3352 	bw /= del_time;
3353 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3354 }
3355 
3356 /*
3357  * Allocate a sendmap from our zone.
3358  */
3359 static struct bbr_sendmap *
3360 bbr_alloc(struct tcp_bbr *bbr)
3361 {
3362 	struct bbr_sendmap *rsm;
3363 
3364 	BBR_STAT_INC(bbr_to_alloc);
3365 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3366 	if (rsm) {
3367 		bbr->r_ctl.rc_num_maps_alloced++;
3368 		return (rsm);
3369 	}
3370 	if (bbr->r_ctl.rc_free_cnt) {
3371 		BBR_STAT_INC(bbr_to_alloc_emerg);
3372 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3373 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3374 		bbr->r_ctl.rc_free_cnt--;
3375 		return (rsm);
3376 	}
3377 	BBR_STAT_INC(bbr_to_alloc_failed);
3378 	return (NULL);
3379 }
3380 
3381 static struct bbr_sendmap *
3382 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3383 {
3384 	if ((bbr_tcp_map_entries_limit > 0) &&
3385 	    (bbr->r_ctl.rc_num_maps_alloced >= bbr_tcp_map_entries_limit)) {
3386 		BBR_STAT_INC(bbr_alloc_limited);
3387 		if (!bbr->alloc_limit_reported) {
3388 			bbr->alloc_limit_reported = 1;
3389 			BBR_STAT_INC(bbr_alloc_limited_conns);
3390 		}
3391 		return (NULL);
3392 	}
3393 	return (bbr_alloc(bbr));
3394 }
3395 
3396 
3397 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3398 static struct bbr_sendmap *
3399 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3400 {
3401 	struct bbr_sendmap *rsm;
3402 
3403 	if (limit_type) {
3404 		/* currently there is only one limit type */
3405 		if (bbr_tcp_map_split_limit > 0 &&
3406 		    bbr->r_ctl.rc_num_split_allocs >= bbr_tcp_map_split_limit) {
3407 			BBR_STAT_INC(bbr_split_limited);
3408 			if (!bbr->alloc_limit_reported) {
3409 				bbr->alloc_limit_reported = 1;
3410 				BBR_STAT_INC(bbr_alloc_limited_conns);
3411 			}
3412 			return (NULL);
3413 		}
3414 	}
3415 
3416 	/* allocate and mark in the limit type, if set */
3417 	rsm = bbr_alloc(bbr);
3418 	if (rsm != NULL && limit_type) {
3419 		rsm->r_limit_type = limit_type;
3420 		bbr->r_ctl.rc_num_split_allocs++;
3421 	}
3422 	return (rsm);
3423 }
3424 
3425 static void
3426 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3427 {
3428 	if (rsm->r_limit_type) {
3429 		/* currently there is only one limit type */
3430 		bbr->r_ctl.rc_num_split_allocs--;
3431 	}
3432 	if (rsm->r_is_smallmap)
3433 		bbr->r_ctl.rc_num_small_maps_alloced--;
3434 	if (bbr->r_ctl.rc_tlp_send == rsm)
3435 		bbr->r_ctl.rc_tlp_send = NULL;
3436 	if (bbr->r_ctl.rc_resend == rsm) {
3437 		bbr->r_ctl.rc_resend = NULL;
3438 	}
3439 	if (bbr->r_ctl.rc_next == rsm)
3440 		bbr->r_ctl.rc_next = NULL;
3441 	if (bbr->r_ctl.rc_sacklast == rsm)
3442 		bbr->r_ctl.rc_sacklast = NULL;
3443 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3444 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3445 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3446 		rsm->r_limit_type = 0;
3447 		bbr->r_ctl.rc_free_cnt++;
3448 		return;
3449 	}
3450 	bbr->r_ctl.rc_num_maps_alloced--;
3451 	uma_zfree(bbr_zone, rsm);
3452 }
3453 
3454 /*
3455  * Returns the BDP.
3456  */
3457 static uint64_t
3458 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3459 	/*
3460 	 * Calculate the bytes in flight needed given the bw (in bytes per
3461 	 * second) and the specifyed rtt in useconds. We need to put out the
3462 	 * returned value per RTT to match that rate. Gain will normaly
3463 	 * raise it up from there.
3464 	 *
3465 	 * This should not overflow as long as the bandwidth is below 1
3466 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3467 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3468 	 */
3469 	uint64_t usec_per_sec;
3470 
3471 	usec_per_sec = USECS_IN_SECOND;
3472 	return ((rtt * bw) / usec_per_sec);
3473 }
3474 
3475 /*
3476  * Return the initial cwnd.
3477  */
3478 static uint32_t
3479 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3480 {
3481 	uint32_t i_cwnd;
3482 
3483 	if (bbr->rc_init_win) {
3484 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3485 	} else if (V_tcp_initcwnd_segments)
3486 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3487 		    max(2 * tp->t_maxseg, 14600));
3488 	else if (V_tcp_do_rfc3390)
3489 		i_cwnd = min(4 * tp->t_maxseg,
3490 		    max(2 * tp->t_maxseg, 4380));
3491 	else {
3492 		/* Per RFC5681 Section 3.1 */
3493 		if (tp->t_maxseg > 2190)
3494 			i_cwnd = 2 * tp->t_maxseg;
3495 		else if (tp->t_maxseg > 1095)
3496 			i_cwnd = 3 * tp->t_maxseg;
3497 		else
3498 			i_cwnd = 4 * tp->t_maxseg;
3499 	}
3500 	return (i_cwnd);
3501 }
3502 
3503 /*
3504  * Given a specified gain, return the target
3505  * cwnd based on that gain.
3506  */
3507 static uint32_t
3508 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3509 {
3510 	uint64_t bdp, rtt;
3511 	uint32_t cwnd;
3512 
3513 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3514 	    (bbr_get_full_bw(bbr) == 0)) {
3515 		/* No measurements yet */
3516 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3517 	}
3518 	/*
3519 	 * Get bytes per RTT needed (rttProp is normally in
3520 	 * bbr_cwndtarget_rtt_touse)
3521 	 */
3522 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3523 	/* Get the bdp from the two values */
3524 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3525 	/* Now apply the gain */
3526 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3527 
3528 	return (cwnd);
3529 }
3530 
3531 static uint32_t
3532 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3533 {
3534 	uint32_t cwnd, mss;
3535 
3536 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3537 	/* Get the base cwnd with gain rounded to a mss */
3538 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3539 	/*
3540 	 * Add in N (2 default since we do not have a
3541 	 * fq layer to trap packets in) quanta's per the I-D
3542 	 * section 4.2.3.2 quanta adjust.
3543 	 */
3544 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3545 	if (bbr->rc_use_google) {
3546 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3547 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3548 			/*
3549 			 * The linux implementation adds
3550 			 * an extra 2 x mss in gain cycle which
3551 			 * is documented no-where except in the code.
3552 			 * so we add more for Neal undocumented feature
3553 			 */
3554 			cwnd += 2 * mss;
3555 		}
3556  		if ((cwnd / mss) & 0x1) {
3557 			/* Round up for odd num mss */
3558 			cwnd += mss;
3559 		}
3560 	}
3561 	/* Are we below the min cwnd? */
3562 	if (cwnd < get_min_cwnd(bbr))
3563 		return (get_min_cwnd(bbr));
3564 	return (cwnd);
3565 }
3566 
3567 static uint16_t
3568 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3569 {
3570 	if (gain < 1)
3571 		gain = 1;
3572 	return (gain);
3573 }
3574 
3575 static uint32_t
3576 bbr_get_header_oh(struct tcp_bbr *bbr)
3577 {
3578 	int seg_oh;
3579 
3580 	seg_oh = 0;
3581 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3582 		/* Do we include TCP overhead? */
3583 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3584 	}
3585 	if (bbr->r_ctl.rc_inc_ip_oh) {
3586 		/* Do we include IP overhead? */
3587 #ifdef INET6
3588 		if (bbr->r_is_v6)
3589 			seg_oh += sizeof(struct ip6_hdr);
3590 		else
3591 #endif
3592 #ifdef INET
3593 			seg_oh += sizeof(struct ip);
3594 #endif
3595 	}
3596 	if (bbr->r_ctl.rc_inc_enet_oh) {
3597 		/* Do we include the ethernet overhead?  */
3598 		seg_oh += sizeof(struct ether_header);
3599 	}
3600 	return(seg_oh);
3601 }
3602 
3603 
3604 static uint32_t
3605 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3606 {
3607 	uint64_t divor, res, tim;
3608 
3609 	if (useconds_time == 0)
3610 		return (0);
3611 	gain = bbr_gain_adjust(bbr, gain);
3612 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3613 	tim = useconds_time;
3614 	res = (tim * bw * gain) / divor;
3615 	if (res == 0)
3616 		res = 1;
3617 	return ((uint32_t)res);
3618 }
3619 
3620 /*
3621  * Given a gain and a length return the delay in useconds that
3622  * should be used to evenly space out packets
3623  * on the connection (based on the gain factor).
3624  */
3625 static uint32_t
3626 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3627 {
3628 	uint64_t bw, lentim, res;
3629 	uint32_t usecs, srtt, over = 0;
3630 	uint32_t seg_oh, num_segs, maxseg;
3631 
3632 	if (len == 0)
3633 		return (0);
3634 
3635 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3636 	num_segs = (len + maxseg - 1) / maxseg;
3637 	if (bbr->rc_use_google == 0) {
3638 		seg_oh = bbr_get_header_oh(bbr);
3639 		len += (num_segs * seg_oh);
3640 	}
3641 	gain = bbr_gain_adjust(bbr, gain);
3642 	bw = bbr_get_bw(bbr);
3643 	if (bbr->rc_use_google) {
3644 		uint64_t cbw;
3645 
3646 		/*
3647 		 * Reduce the b/w by the google discount
3648 		 * factor 10 = 1%.
3649 		 */
3650 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3651 		cbw /= (uint64_t)1000;
3652 		/* We don't apply a discount if it results in 0 */
3653 		if (cbw > 0)
3654 			bw = cbw;
3655 	}
3656 	lentim = ((uint64_t)len *
3657 		  (uint64_t)USECS_IN_SECOND *
3658 		  (uint64_t)BBR_UNIT);
3659 	res = lentim / ((uint64_t)gain * bw);
3660 	if (res == 0)
3661 		res = 1;
3662 	usecs = (uint32_t)res;
3663 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3664 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3665 	    (bbr->rc_use_google == 0) &&
3666 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3667 		/*
3668 		 * We cannot let the delay be more than 1/2 the srtt time.
3669 		 * Otherwise we cannot pace out or send properly.
3670 		 */
3671 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3672 		BBR_STAT_INC(bbr_hpts_min_time);
3673 	}
3674 	if (!nolog)
3675 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3676 	return (usecs);
3677 }
3678 
3679 static void
3680 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3681 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3682 {
3683 	INP_WLOCK_ASSERT(tp->t_inpcb);
3684 	uint64_t bw;
3685 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3686 	int32_t meth;
3687 
3688 #ifdef NETFLIX_STATS
3689 	if ((tp->t_flags & TF_GPUTINPROG) &&
3690 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3691 		/*
3692 		 * Strech acks and compressed acks will cause this to
3693 		 * oscillate but we are doing it the same way as the main
3694 		 * stack so it will be compariable (though possibly not
3695 		 * ideal).
3696 		 */
3697 		int32_t cgput;
3698 		int64_t gput, time_stamp;
3699 
3700 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3701 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3702 		cgput = gput / time_stamp;
3703 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3704 					 cgput);
3705 		if (tp->t_stats_gput_prev > 0)
3706 			stats_voi_update_abs_s32(tp->t_stats,
3707 						 VOI_TCP_GPUT_ND,
3708 						 ((gput - tp->t_stats_gput_prev) * 100) /
3709 						 tp->t_stats_gput_prev);
3710 		tp->t_flags &= ~TF_GPUTINPROG;
3711 		tp->t_stats_gput_prev = cgput;
3712 	}
3713 #endif
3714 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3715 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3716 		/* We don't change anything in probe-rtt */
3717 		return;
3718 	}
3719 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3720 	saved_bytes = bytes_this_ack;
3721 	bytes_this_ack += sack_changed;
3722 	if (bytes_this_ack > prev_acked) {
3723 		bytes_this_ack -= prev_acked;
3724 		/*
3725 		 * A byte ack'd gives us a full mss
3726 		 * to be like linux i.e. they count packets.
3727 		 */
3728 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3729 			bytes_this_ack = maxseg;
3730 	} else {
3731 		/* Unlikely */
3732 		bytes_this_ack = 0;
3733 	}
3734 	cwnd = tp->snd_cwnd;
3735 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3736 	if (bw)
3737 		target_cwnd = bbr_get_target_cwnd(bbr,
3738 						  bw,
3739 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3740 	else
3741 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3742 	if (IN_RECOVERY(tp->t_flags) &&
3743 	    (bbr->bbr_prev_in_rec == 0)) {
3744 		/*
3745 		 * We are entering recovery and
3746 		 * thus packet conservation.
3747 		 */
3748 		bbr->pkt_conservation = 1;
3749 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3750 		cwnd = ctf_flight_size(tp,
3751 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3752 			bytes_this_ack;
3753 	}
3754 	if (IN_RECOVERY(tp->t_flags)) {
3755 		uint32_t flight;
3756 
3757 		bbr->bbr_prev_in_rec = 1;
3758 		if (cwnd > losses) {
3759 			cwnd -= losses;
3760 			if (cwnd < maxseg)
3761 				cwnd = maxseg;
3762 		} else
3763 			cwnd = maxseg;
3764 		flight = ctf_flight_size(tp,
3765 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3766 		bbr_log_type_cwndupd(bbr, flight, 0,
3767 				     losses, 10, 0, 0, line);
3768 		if (bbr->pkt_conservation) {
3769 			uint32_t time_in;
3770 
3771 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3772 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3773 			else
3774 				time_in = 0;
3775 
3776 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3777 				/* Clear packet conservation after an rttProp */
3778 				bbr->pkt_conservation = 0;
3779 			} else {
3780 				if ((flight + bytes_this_ack) > cwnd)
3781 					cwnd = flight + bytes_this_ack;
3782 				if (cwnd < get_min_cwnd(bbr))
3783 					cwnd = get_min_cwnd(bbr);
3784 				tp->snd_cwnd = cwnd;
3785 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3786 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3787 				return;
3788 			}
3789 		}
3790 	} else
3791 		bbr->bbr_prev_in_rec = 0;
3792 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3793 		bbr->r_ctl.restrict_growth--;
3794 		if (bytes_this_ack > maxseg)
3795 			bytes_this_ack = maxseg;
3796 	}
3797 	if (bbr->rc_filled_pipe) {
3798 		/*
3799 		 * Here we have exited startup and filled the pipe. We will
3800 		 * thus allow the cwnd to shrink to the target. We hit here
3801 		 * mostly.
3802 		 */
3803 		uint32_t s_cwnd;
3804 
3805 		meth = 2;
3806 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3807 		if (s_cwnd > cwnd)
3808 			cwnd = s_cwnd;
3809 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3810 			cwnd = s_cwnd;
3811 	} else {
3812 		/*
3813 		 * Here we are still in startup, we increase cwnd by what
3814 		 * has been acked.
3815 		 */
3816 		if ((cwnd < target_cwnd) ||
3817 		    (bbr->rc_past_init_win == 0)) {
3818 			meth = 3;
3819 			cwnd += bytes_this_ack;
3820 		} else {
3821 			/*
3822 			 * Method 4 means we are at target so no gain in
3823 			 * startup and past the initial window.
3824 			 */
3825 			meth = 4;
3826 		}
3827 	}
3828 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3829 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3830 }
3831 
3832 static void
3833 tcp_bbr_partialack(struct tcpcb *tp)
3834 {
3835 	struct tcp_bbr *bbr;
3836 
3837 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3838 	INP_WLOCK_ASSERT(tp->t_inpcb);
3839 	if (ctf_flight_size(tp,
3840 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3841 	    tp->snd_cwnd) {
3842 		bbr->r_wanted_output = 1;
3843 	}
3844 }
3845 
3846 static void
3847 bbr_post_recovery(struct tcpcb *tp)
3848 {
3849 	struct tcp_bbr *bbr;
3850 	uint32_t  flight;
3851 
3852 	INP_WLOCK_ASSERT(tp->t_inpcb);
3853 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3854 	/*
3855 	 * Here we just exit recovery.
3856 	 */
3857 	EXIT_RECOVERY(tp->t_flags);
3858 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3859 	bbr->r_recovery_bw = 0;
3860 	tp->snd_recover = tp->snd_una;
3861 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3862 	bbr->pkt_conservation = 0;
3863 	if (bbr->rc_use_google == 0) {
3864 		/*
3865 		 * For non-google mode lets
3866 		 * go ahead and make sure we clear
3867 		 * the recovery state so if we
3868 		 * bounce back in to recovery we
3869 		 * will do PC.
3870 		 */
3871 		bbr->bbr_prev_in_rec = 0;
3872 	}
3873 	bbr_log_type_exit_rec(bbr);
3874 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3875 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3876 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3877 	} else {
3878 		/* For probe-rtt case lets fix up its saved_cwnd */
3879 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3880 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3881 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3882 		}
3883 	}
3884 	flight = ctf_flight_size(tp,
3885 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3886 	if ((bbr->rc_use_google == 0) &&
3887 	    bbr_do_red) {
3888 		uint64_t val, lr2use;
3889 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3890 		uint32_t *cwnd_p;
3891 
3892 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3893 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3894 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3895 			ratio = (uint32_t)val;
3896 		} else
3897 			ratio = 1000;
3898 
3899 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3900 				     bbr->r_ctl.recovery_lr, 21,
3901 				     ratio,
3902 				     bbr->r_ctl.rc_red_cwnd_pe,
3903 				     __LINE__);
3904 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3905 			goto done;
3906 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3907 		     bbr_prtt_slam_cwnd) ||
3908 		    (bbr_sub_drain_slam_cwnd &&
3909 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3910 		     bbr->rc_hit_state_1 &&
3911 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3912 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3913 		     bbr_slam_cwnd_in_main_drain)) {
3914 			/*
3915 			 * Here we must poke at the saved cwnd
3916 			 * as well as the cwnd.
3917 			 */
3918 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3919 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3920 		} else {
3921  			cwnd = tp->snd_cwnd;
3922 			cwnd_p = &tp->snd_cwnd;
3923 		}
3924 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3925 		/* Add the overall lr with the recovery lr */
3926 		if (bbr->r_ctl.rc_lost == 0)
3927 			lr2use = 0;
3928 		else if (bbr->r_ctl.rc_delivered == 0)
3929 			lr2use = 1000;
3930 		else {
3931 			lr2use = bbr->r_ctl.rc_lost * 1000;
3932 			lr2use /= bbr->r_ctl.rc_delivered;
3933 		}
3934 		lr2use += bbr->r_ctl.recovery_lr;
3935 		acks_inflight = (flight / (maxseg * 2));
3936 		if (bbr_red_scale) {
3937 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3938 			lr2use /= bbr_red_scale;
3939 			if ((bbr_red_growth_restrict) &&
3940 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3941 			    bbr->r_ctl.restrict_growth += acks_inflight;
3942 		}
3943 		if (lr2use) {
3944 			val = (uint64_t)cwnd * lr2use;
3945 			val /= 1000;
3946 			if (cwnd > val)
3947 				newcwnd = roundup((cwnd - val), maxseg);
3948 			else
3949 				newcwnd = maxseg;
3950 		} else {
3951 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3952 			val /= (uint64_t)bbr_red_div;
3953 			newcwnd = roundup((uint32_t)val, maxseg);
3954 		}
3955 		/* with standard delayed acks how many acks can I expect? */
3956 		if (bbr_drop_limit == 0) {
3957 			/*
3958 			 * Anticpate how much we will
3959 			 * raise the cwnd based on the acks.
3960 			 */
3961 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3962 				/* We do enforce the min (with the acks) */
3963 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3964 			}
3965 		} else {
3966 			/*
3967 			 * A strict drop limit of N is is inplace
3968 			 */
3969 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3970 				newcwnd = bbr_drop_limit * maxseg;
3971 			}
3972 		}
3973 		/* For the next N acks do we restrict the growth */
3974 		*cwnd_p = newcwnd;
3975 		if (tp->snd_cwnd > newcwnd)
3976 			tp->snd_cwnd = newcwnd;
3977 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3978 				     (uint32_t)lr2use,
3979 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3980 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3981 	}
3982 done:
3983 	bbr->r_ctl.recovery_lr = 0;
3984 	if (flight <= tp->snd_cwnd) {
3985 		bbr->r_wanted_output = 1;
3986 	}
3987 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3988 }
3989 
3990 static void
3991 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3992 {
3993 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3994 	/* Limit the drop in b/w to 1/2 our current filter. */
3995 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3996 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3997 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3998 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3999 	tcp_bbr_tso_size_check(bbr, cts);
4000 }
4001 
4002 static void
4003 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
4004 {
4005 	struct tcp_bbr *bbr;
4006 
4007 	INP_WLOCK_ASSERT(tp->t_inpcb);
4008 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4009 	switch (type) {
4010 	case CC_NDUPACK:
4011 		if (!IN_RECOVERY(tp->t_flags)) {
4012 			tp->snd_recover = tp->snd_max;
4013 			/* Start a new epoch */
4014 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
4015 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
4016 				/*
4017 				 * Move forward the lt epoch
4018 				 * so it won't count the truncated
4019 				 * epoch.
4020 				 */
4021 				bbr->r_ctl.rc_lt_epoch++;
4022 			}
4023 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
4024 				/*
4025 				 * Just like the policer detection code
4026 				 * if we are in startup we must push
4027 				 * forward the last startup epoch
4028 				 * to hide the truncated PE.
4029 				 */
4030 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
4031 			}
4032 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
4033 			ENTER_RECOVERY(tp->t_flags);
4034 			bbr->rc_tlp_rtx_out = 0;
4035 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
4036 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
4037 			if (bbr->rc_inp->inp_in_hpts &&
4038 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
4039 				/*
4040 				 * When we enter recovery, we need to restart
4041 				 * any timers. This may mean we gain an agg
4042 				 * early, which will be made up for at the last
4043 				 * rxt out.
4044 				 */
4045 				bbr->rc_timer_first = 1;
4046 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
4047 			}
4048 			/*
4049 			 * Calculate a new cwnd based on to the current
4050 			 * delivery rate with no gain. We get the bdp
4051 			 * without gaining it up like we normally would and
4052 			 * we use the last cur_del_rate.
4053 			 */
4054 			if ((bbr->rc_use_google == 0) &&
4055 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
4056 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
4057 				tp->snd_cwnd = ctf_flight_size(tp,
4058 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
4059 					(tp->t_maxseg - bbr->rc_last_options);
4060 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
4061 					/* We always gate to min cwnd */
4062 					tp->snd_cwnd = get_min_cwnd(bbr);
4063 				}
4064 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
4065 			}
4066 			bbr_log_type_enter_rec(bbr, rsm->r_start);
4067 		}
4068 		break;
4069 	case CC_RTO_ERR:
4070 		TCPSTAT_INC(tcps_sndrexmitbad);
4071 		/* RTO was unnecessary, so reset everything. */
4072 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4073 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4074 			tp->snd_cwnd = tp->snd_cwnd_prev;
4075 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4076 			tp->snd_recover = tp->snd_recover_prev;
4077 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4078 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4079 		}
4080 		tp->t_badrxtwin = 0;
4081 		break;
4082 	}
4083 }
4084 
4085 /*
4086  * Indicate whether this ack should be delayed.  We can delay the ack if
4087  * following conditions are met:
4088  *	- There is no delayed ack timer in progress.
4089  *	- Our last ack wasn't a 0-sized window. We never want to delay
4090  *	  the ack that opens up a 0-sized window.
4091  *	- LRO wasn't used for this segment. We make sure by checking that the
4092  *	  segment size is not larger than the MSS.
4093  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4094  *	  connection.
4095  *	- The data being acked is less than a full segment (a stretch ack
4096  *        of more than a segment we should ack.
4097  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4098  */
4099 #define DELAY_ACK(tp, bbr, nsegs)				\
4100 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4101 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4102 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4103 
4104 /*
4105  * Return the lowest RSM in the map of
4106  * packets still in flight that is not acked.
4107  * This should normally find on the first one
4108  * since we remove packets from the send
4109  * map after they are marked ACKED.
4110  */
4111 static struct bbr_sendmap *
4112 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4113 {
4114 	struct bbr_sendmap *rsm;
4115 
4116 	/*
4117 	 * Walk the time-order transmitted list looking for an rsm that is
4118 	 * not acked. This will be the one that was sent the longest time
4119 	 * ago that is still outstanding.
4120 	 */
4121 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4122 		if (rsm->r_flags & BBR_ACKED) {
4123 			continue;
4124 		}
4125 		goto finish;
4126 	}
4127 finish:
4128 	return (rsm);
4129 }
4130 
4131 static struct bbr_sendmap *
4132 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4133 {
4134 	struct bbr_sendmap *prsm;
4135 
4136 	/*
4137 	 * Walk the sequence order list backward until we hit and arrive at
4138 	 * the highest seq not acked. In theory when this is called it
4139 	 * should be the last segment (which it was not).
4140 	 */
4141 	prsm = rsm;
4142 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4143 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4144 			continue;
4145 		}
4146 		return (prsm);
4147 	}
4148 	return (NULL);
4149 }
4150 
4151 /*
4152  * Returns to the caller the number of microseconds that
4153  * the packet can be outstanding before we think we
4154  * should have had an ack returned.
4155  */
4156 static uint32_t
4157 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4158 {
4159 	/*
4160 	 * lro is the flag we use to determine if we have seen reordering.
4161 	 * If it gets set we have seen reordering. The reorder logic either
4162 	 * works in one of two ways:
4163 	 *
4164 	 * If reorder-fade is configured, then we track the last time we saw
4165 	 * re-ordering occur. If we reach the point where enough time as
4166 	 * passed we no longer consider reordering has occuring.
4167 	 *
4168 	 * Or if reorder-face is 0, then once we see reordering we consider
4169 	 * the connection to alway be subject to reordering and just set lro
4170 	 * to 1.
4171 	 *
4172 	 * In the end if lro is non-zero we add the extra time for
4173 	 * reordering in.
4174 	 */
4175 	int32_t lro;
4176 	uint32_t thresh, t_rxtcur;
4177 
4178 	if (srtt == 0)
4179 		srtt = 1;
4180 	if (bbr->r_ctl.rc_reorder_ts) {
4181 		if (bbr->r_ctl.rc_reorder_fade) {
4182 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4183 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4184 				if (lro == 0) {
4185 					/*
4186 					 * No time as passed since the last
4187 					 * reorder, mark it as reordering.
4188 					 */
4189 					lro = 1;
4190 				}
4191 			} else {
4192 				/* Negative time? */
4193 				lro = 0;
4194 			}
4195 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4196 				/* Turn off reordering seen too */
4197 				bbr->r_ctl.rc_reorder_ts = 0;
4198 				lro = 0;
4199 			}
4200 		} else {
4201 			/* Reodering does not fade */
4202 			lro = 1;
4203 		}
4204 	} else {
4205 		lro = 0;
4206 	}
4207 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4208 	if (lro) {
4209 		/* It must be set, if not you get 1/4 rtt */
4210 		if (bbr->r_ctl.rc_reorder_shift)
4211 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4212 		else
4213 			thresh += (srtt >> 2);
4214 	} else {
4215 		thresh += 1000;
4216 	}
4217 	/* We don't let the rack timeout be above a RTO */
4218 	if ((bbr->rc_tp)->t_srtt == 0)
4219 		t_rxtcur = BBR_INITIAL_RTO;
4220 	else
4221 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4222 	if (thresh > t_rxtcur) {
4223 		thresh = t_rxtcur;
4224 	}
4225 	/* And we don't want it above the RTO max either */
4226 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4227 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4228 	}
4229 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4230 	return (thresh);
4231 }
4232 
4233 /*
4234  * Return to the caller the amount of time in mico-seconds
4235  * that should be used for the TLP timer from the last
4236  * send time of this packet.
4237  */
4238 static uint32_t
4239 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4240     struct bbr_sendmap *rsm, uint32_t srtt,
4241     uint32_t cts)
4242 {
4243 	uint32_t thresh, len, maxseg, t_rxtcur;
4244 	struct bbr_sendmap *prsm;
4245 
4246 	if (srtt == 0)
4247 		srtt = 1;
4248 	if (bbr->rc_tlp_threshold)
4249 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4250 	else
4251 		thresh = (srtt * 2);
4252 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4253 	/* Get the previous sent packet, if any  */
4254 	len = rsm->r_end - rsm->r_start;
4255 
4256 	/* 2.1 behavior */
4257 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4258 	if (prsm && (len <= maxseg)) {
4259 		/*
4260 		 * Two packets outstanding, thresh should be (2*srtt) +
4261 		 * possible inter-packet delay (if any).
4262 		 */
4263 		uint32_t inter_gap = 0;
4264 		int idx, nidx;
4265 
4266 		idx = rsm->r_rtr_cnt - 1;
4267 		nidx = prsm->r_rtr_cnt - 1;
4268 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4269 			/* Yes it was sent later (or at the same time) */
4270 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4271 		}
4272 		thresh += inter_gap;
4273 	} else if (len <= maxseg) {
4274 		/*
4275 		 * Possibly compensate for delayed-ack.
4276 		 */
4277 		uint32_t alt_thresh;
4278 
4279 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4280 		if (alt_thresh > thresh)
4281 			thresh = alt_thresh;
4282 	}
4283 	/* Not above the current  RTO */
4284 	if (tp->t_srtt == 0)
4285 		t_rxtcur = BBR_INITIAL_RTO;
4286 	else
4287 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4288 
4289 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4290 	/* Not above an RTO */
4291 	if (thresh > t_rxtcur) {
4292 		thresh = t_rxtcur;
4293 	}
4294 	/* Not above a RTO max */
4295 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4296 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4297 	}
4298 	/* And now apply the user TLP min */
4299 	if (thresh < bbr_tlp_min) {
4300 		thresh = bbr_tlp_min;
4301 	}
4302 	return (thresh);
4303 }
4304 
4305 /*
4306  * Return one of three RTTs to use (in microseconds).
4307  */
4308 static __inline uint32_t
4309 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4310 {
4311 	uint32_t f_rtt;
4312 	uint32_t srtt;
4313 
4314 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4315 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4316 		/* We have no rtt at all */
4317 		if (bbr->rc_tp->t_srtt == 0)
4318 			f_rtt = BBR_INITIAL_RTO;
4319 		else
4320 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4321 		/*
4322 		 * Since we don't know how good the rtt is apply a
4323 		 * delayed-ack min
4324 		 */
4325 		if (f_rtt < bbr_delayed_ack_time) {
4326 			f_rtt = bbr_delayed_ack_time;
4327 		}
4328 	}
4329 	/* Take the filter version or last measured pkt-rtt */
4330 	if (rtt_type == BBR_RTT_PROP) {
4331 		srtt = f_rtt;
4332 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4333 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4334 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4335 		} else {
4336 			/* No pkt rtt yet */
4337 			srtt = f_rtt;
4338 		}
4339 	} else if (rtt_type == BBR_RTT_RACK) {
4340 		srtt = bbr->r_ctl.rc_last_rtt;
4341 		/* We need to add in any internal delay for our timer */
4342 		if (bbr->rc_ack_was_delayed)
4343 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4344 	} else if (rtt_type == BBR_SRTT) {
4345 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4346 	} else {
4347 		/* TSNH */
4348 		srtt = f_rtt;
4349 #ifdef BBR_INVARIANTS
4350 		panic("Unknown rtt request type %d", rtt_type);
4351 #endif
4352 	}
4353 	return (srtt);
4354 }
4355 
4356 static int
4357 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4358 {
4359 	uint32_t thresh;
4360 
4361 
4362 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4363 				      cts, rsm);
4364 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4365 		/* It is lost (past time) */
4366 		return (1);
4367 	}
4368 	return (0);
4369 }
4370 
4371 /*
4372  * Return a sendmap if we need to retransmit something.
4373  */
4374 static struct bbr_sendmap *
4375 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4376 {
4377 	/*
4378 	 * Check to see that we don't need to fall into recovery. We will
4379 	 * need to do so if our oldest transmit is past the time we should
4380 	 * have had an ack.
4381 	 */
4382 
4383 	struct bbr_sendmap *rsm;
4384 	int32_t idx;
4385 
4386 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4387 		/* Nothing outstanding that we know of */
4388 		return (NULL);
4389 	}
4390 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4391 	if (rsm == NULL) {
4392 		/* Nothing in the transmit map */
4393 		return (NULL);
4394 	}
4395 	if (tp->t_flags & TF_SENTFIN) {
4396 		/* Fin restricted, don't find anything once a fin is sent */
4397 		return (NULL);
4398 	}
4399 	if (rsm->r_flags & BBR_ACKED) {
4400 		/*
4401 		 * Ok the first one is acked (this really should not happen
4402 		 * since we remove the from the tmap once they are acked)
4403 		 */
4404 		rsm = bbr_find_lowest_rsm(bbr);
4405 		if (rsm == NULL)
4406 			return (NULL);
4407 	}
4408 	idx = rsm->r_rtr_cnt - 1;
4409 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4410 		/* Send timestamp is the same or less? can't be ready */
4411 		return (NULL);
4412 	}
4413 	/* Get our RTT time */
4414 	if (bbr_is_lost(bbr, rsm, cts) &&
4415 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4416 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4417 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4418 			rsm->r_flags |= BBR_MARKED_LOST;
4419 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4420 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4421 		}
4422 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4423 #ifdef BBR_INVARIANTS
4424 		if ((rsm->r_end - rsm->r_start) == 0)
4425 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4426 #endif
4427 		return (rsm);
4428 	}
4429 	return (NULL);
4430 }
4431 
4432 /*
4433  * RACK Timer, here we simply do logging and house keeping.
4434  * the normal bbr_output_wtime() function will call the
4435  * appropriate thing to check if we need to do a RACK retransmit.
4436  * We return 1, saying don't proceed with bbr_output_wtime only
4437  * when all timers have been stopped (destroyed PCB?).
4438  */
4439 static int
4440 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4441 {
4442 	/*
4443 	 * This timer simply provides an internal trigger to send out data.
4444 	 * The check_recovery_mode call will see if there are needed
4445 	 * retransmissions, if so we will enter fast-recovery. The output
4446 	 * call may or may not do the same thing depending on sysctl
4447 	 * settings.
4448 	 */
4449 	uint32_t lost;
4450 
4451 	if (bbr->rc_all_timers_stopped) {
4452 		return (1);
4453 	}
4454 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4455 		/* Its not time yet */
4456 		return (0);
4457 	}
4458 	BBR_STAT_INC(bbr_to_tot);
4459 	lost = bbr->r_ctl.rc_lost;
4460 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4461 		bbr_set_state(tp, bbr, 0);
4462 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4463 	if (bbr->r_ctl.rc_resend == NULL) {
4464 		/* Lets do the check here */
4465 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4466 	}
4467 	if (bbr_policer_call_from_rack_to)
4468 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4469 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4470 	return (0);
4471 }
4472 
4473 static __inline void
4474 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4475 {
4476 	int idx;
4477 
4478 	nrsm->r_start = start;
4479 	nrsm->r_end = rsm->r_end;
4480 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4481 	nrsm->r_flags = rsm->r_flags;
4482 	/* We don't transfer forward the SYN flag */
4483 	nrsm->r_flags &= ~BBR_HAS_SYN;
4484 	/* We move forward the FIN flag, not that this should happen */
4485 	rsm->r_flags &= ~BBR_HAS_FIN;
4486 	nrsm->r_dupack = rsm->r_dupack;
4487 	nrsm->r_rtr_bytes = 0;
4488 	nrsm->r_is_gain = rsm->r_is_gain;
4489 	nrsm->r_is_drain = rsm->r_is_drain;
4490 	nrsm->r_delivered = rsm->r_delivered;
4491 	nrsm->r_ts_valid = rsm->r_ts_valid;
4492 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4493 	nrsm->r_del_time = rsm->r_del_time;
4494 	nrsm->r_app_limited = rsm->r_app_limited;
4495 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4496 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4497 	/* We split a piece the lower section looses any just_ret flag. */
4498 	nrsm->r_bbr_state = rsm->r_bbr_state;
4499 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4500 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4501 	}
4502 	rsm->r_end = nrsm->r_start;
4503 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4504 	idx /= 8;
4505 	/* Check if we got too small */
4506 	if ((rsm->r_is_smallmap == 0) &&
4507 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4508 		bbr->r_ctl.rc_num_small_maps_alloced++;
4509 		rsm->r_is_smallmap = 1;
4510 	}
4511 	/* Check the new one as well */
4512 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4513 		bbr->r_ctl.rc_num_small_maps_alloced++;
4514 		nrsm->r_is_smallmap = 1;
4515 	}
4516 }
4517 
4518 static int
4519 bbr_sack_mergable(struct bbr_sendmap *at,
4520 		  uint32_t start, uint32_t end)
4521 {
4522 	/*
4523 	 * Given a sack block defined by
4524 	 * start and end, and a current postion
4525 	 * at. Return 1 if either side of at
4526 	 * would show that the block is mergable
4527 	 * to that side. A block to be mergable
4528 	 * must have overlap with the start/end
4529 	 * and be in the SACK'd state.
4530 	 */
4531 	struct bbr_sendmap *l_rsm;
4532 	struct bbr_sendmap *r_rsm;
4533 
4534 	/* first get the either side blocks */
4535 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4536 	r_rsm = TAILQ_NEXT(at, r_next);
4537 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4538 		/* Potentially mergeable */
4539 		if ((l_rsm->r_end == start) ||
4540 		    (SEQ_LT(start, l_rsm->r_end) &&
4541 		     SEQ_GT(end, l_rsm->r_end))) {
4542 			    /*
4543 			     * map blk   |------|
4544 			     * sack blk         |------|
4545 			     * <or>
4546 			     * map blk   |------|
4547 			     * sack blk      |------|
4548 			     */
4549 			    return (1);
4550 		    }
4551 	}
4552 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4553 		/* Potentially mergeable */
4554 		if ((r_rsm->r_start == end) ||
4555 		    (SEQ_LT(start, r_rsm->r_start) &&
4556 		     SEQ_GT(end, r_rsm->r_start))) {
4557 			/*
4558 			 * map blk          |---------|
4559 			 * sack blk    |----|
4560 			 * <or>
4561 			 * map blk          |---------|
4562 			 * sack blk    |-------|
4563 			 */
4564 			return (1);
4565 		}
4566 	}
4567 	return (0);
4568 }
4569 
4570 static struct bbr_sendmap *
4571 bbr_merge_rsm(struct tcp_bbr *bbr,
4572 	      struct bbr_sendmap *l_rsm,
4573 	      struct bbr_sendmap *r_rsm)
4574 {
4575 	/*
4576 	 * We are merging two ack'd RSM's,
4577 	 * the l_rsm is on the left (lower seq
4578 	 * values) and the r_rsm is on the right
4579 	 * (higher seq value). The simplest way
4580 	 * to merge these is to move the right
4581 	 * one into the left. I don't think there
4582 	 * is any reason we need to try to find
4583 	 * the oldest (or last oldest retransmitted).
4584 	 */
4585 	l_rsm->r_end = r_rsm->r_end;
4586 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4587 		l_rsm->r_dupack = r_rsm->r_dupack;
4588 	if (r_rsm->r_rtr_bytes)
4589 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4590 	if (r_rsm->r_in_tmap) {
4591 		/* This really should not happen */
4592 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4593 	}
4594 	if (r_rsm->r_app_limited)
4595 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4596 	/* Now the flags */
4597 	if (r_rsm->r_flags & BBR_HAS_FIN)
4598 		l_rsm->r_flags |= BBR_HAS_FIN;
4599 	if (r_rsm->r_flags & BBR_TLP)
4600 		l_rsm->r_flags |= BBR_TLP;
4601 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4602 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4603 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4604 		/* This really should not happen */
4605 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4606 	}
4607 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4608 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4609 		/* Transfer the split limit to the map we free */
4610 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4611 		l_rsm->r_limit_type = 0;
4612 	}
4613 	bbr_free(bbr, r_rsm);
4614 	return(l_rsm);
4615 }
4616 
4617 /*
4618  * TLP Timer, here we simply setup what segment we want to
4619  * have the TLP expire on, the normal bbr_output_wtime() will then
4620  * send it out.
4621  *
4622  * We return 1, saying don't proceed with bbr_output_wtime only
4623  * when all timers have been stopped (destroyed PCB?).
4624  */
4625 static int
4626 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4627 {
4628 	/*
4629 	 * Tail Loss Probe.
4630 	 */
4631 	struct bbr_sendmap *rsm = NULL;
4632 	struct socket *so;
4633 	uint32_t amm;
4634 	uint32_t out, avail;
4635 	uint32_t maxseg;
4636 	int collapsed_win = 0;
4637 
4638 	if (bbr->rc_all_timers_stopped) {
4639 		return (1);
4640 	}
4641 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4642 		/* Its not time yet */
4643 		return (0);
4644 	}
4645 	if (bbr_progress_timeout_check(bbr)) {
4646 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4647 		return (1);
4648 	}
4649 	/* Did we somehow get into persists? */
4650 	if (bbr->rc_in_persist) {
4651 		return (0);
4652 	}
4653 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4654 		bbr_set_state(tp, bbr, 0);
4655 	BBR_STAT_INC(bbr_tlp_tot);
4656 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4657 #ifdef KERN_TLS
4658 	if (bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) {
4659 		/*
4660 		 * For hardware TLS we do *not* want to send
4661 		 * new data.
4662 		 */
4663 		goto need_retran;
4664 	}
4665 #endif
4666 	/*
4667 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4668 	 * need to figure out how to force a full MSS segment out.
4669 	 */
4670 	so = tp->t_inpcb->inp_socket;
4671 	avail = sbavail(&so->so_snd);
4672 	out = ctf_outstanding(tp);
4673 	if (out > tp->snd_wnd) {
4674 		/* special case, we need a retransmission */
4675 		collapsed_win = 1;
4676 		goto need_retran;
4677 	}
4678 	if (avail > out) {
4679 		/* New data is available */
4680 		amm = avail - out;
4681 		if (amm > maxseg) {
4682 			amm = maxseg;
4683 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4684 			/* not enough to fill a MTU and no-delay is off */
4685 			goto need_retran;
4686 		}
4687 		/* Set the send-new override */
4688 		if ((out + amm) <= tp->snd_wnd) {
4689 			bbr->rc_tlp_new_data = 1;
4690 		} else {
4691 			goto need_retran;
4692 		}
4693 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4694 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4695 		bbr->r_ctl.rc_tlp_send = NULL;
4696 		/* cap any slots */
4697 		BBR_STAT_INC(bbr_tlp_newdata);
4698 		goto send;
4699 	}
4700 need_retran:
4701 	/*
4702 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4703 	 * optionally the first un-acked segment.
4704 	 */
4705 	if (collapsed_win == 0) {
4706 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4707 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4708 			rsm = bbr_find_high_nonack(bbr, rsm);
4709 		}
4710 		if (rsm == NULL) {
4711 			goto restore;
4712 		}
4713 	} else {
4714 		/*
4715 		 * We must find the last segment
4716 		 * that was acceptable by the client.
4717 		 */
4718 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4719 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4720 				/* Found one */
4721 				break;
4722 			}
4723 		}
4724 		if (rsm == NULL) {
4725 			/* None? if so send the first */
4726 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4727 			if (rsm == NULL)
4728 				goto restore;
4729 		}
4730 	}
4731 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4732 		/*
4733 		 * We need to split this the last segment in two.
4734 		 */
4735 		struct bbr_sendmap *nrsm;
4736 
4737 		nrsm = bbr_alloc_full_limit(bbr);
4738 		if (nrsm == NULL) {
4739 			/*
4740 			 * We can't get memory to split, we can either just
4741 			 * not split it. Or retransmit the whole piece, lets
4742 			 * do the large send (BTLP :-) ).
4743 			 */
4744 			goto go_for_it;
4745 		}
4746 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4747 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4748 		if (rsm->r_in_tmap) {
4749 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4750 			nrsm->r_in_tmap = 1;
4751 		}
4752 		rsm->r_flags &= (~BBR_HAS_FIN);
4753 		rsm = nrsm;
4754 	}
4755 go_for_it:
4756 	bbr->r_ctl.rc_tlp_send = rsm;
4757 	bbr->rc_tlp_rtx_out = 1;
4758 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4759 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4760 		tp->t_rxtshift++;
4761 	} else {
4762 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4763 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4764 	}
4765 send:
4766 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4767 		/*
4768 		 * Can't [re]/transmit a segment we have retranmitted the
4769 		 * max times. We need the retransmit timer to take over.
4770 		 */
4771 restore:
4772 		bbr->rc_tlp_new_data = 0;
4773 		bbr->r_ctl.rc_tlp_send = NULL;
4774 		if (rsm)
4775 			rsm->r_flags &= ~BBR_TLP;
4776 		BBR_STAT_INC(bbr_tlp_retran_fail);
4777 		return (0);
4778 	} else if (rsm) {
4779 		rsm->r_flags |= BBR_TLP;
4780 	}
4781 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4782 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4783 		/*
4784 		 * We have retransmitted to many times for TLP. Switch to
4785 		 * the regular RTO timer
4786 		 */
4787 		goto restore;
4788 	}
4789 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4790 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4791 	return (0);
4792 }
4793 
4794 /*
4795  * Delayed ack Timer, here we simply need to setup the
4796  * ACK_NOW flag and remove the DELACK flag. From there
4797  * the output routine will send the ack out.
4798  *
4799  * We only return 1, saying don't proceed, if all timers
4800  * are stopped (destroyed PCB?).
4801  */
4802 static int
4803 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4804 {
4805 	if (bbr->rc_all_timers_stopped) {
4806 		return (1);
4807 	}
4808 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4809 	tp->t_flags &= ~TF_DELACK;
4810 	tp->t_flags |= TF_ACKNOW;
4811 	TCPSTAT_INC(tcps_delack);
4812 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4813 	return (0);
4814 }
4815 
4816 /*
4817  * Persists timer, here we simply need to setup the
4818  * FORCE-DATA flag the output routine will send
4819  * the one byte send.
4820  *
4821  * We only return 1, saying don't proceed, if all timers
4822  * are stopped (destroyed PCB?).
4823  */
4824 static int
4825 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4826 {
4827 	struct tcptemp *t_template;
4828 	int32_t retval = 1;
4829 
4830 	if (bbr->rc_all_timers_stopped) {
4831 		return (1);
4832 	}
4833 	if (bbr->rc_in_persist == 0)
4834 		return (0);
4835 	KASSERT(tp->t_inpcb != NULL,
4836 	    ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4837 	/*
4838 	 * Persistence timer into zero window. Force a byte to be output, if
4839 	 * possible.
4840 	 */
4841 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4842 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4843 	TCPSTAT_INC(tcps_persisttimeo);
4844 	/*
4845 	 * Have we exceeded the user specified progress time?
4846 	 */
4847 	if (bbr_progress_timeout_check(bbr)) {
4848 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4849 		goto out;
4850 	}
4851 	/*
4852 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4853 	 * window is closed.  After a full backoff, drop the connection if
4854 	 * the idle time (no responses to probes) reaches the maximum
4855 	 * backoff that we would use if retransmitting.
4856 	 */
4857 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4858 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4859 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4860 		TCPSTAT_INC(tcps_persistdrop);
4861 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4862 		goto out;
4863 	}
4864 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4865 	    tp->snd_una == tp->snd_max) {
4866 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4867 		retval = 0;
4868 		goto out;
4869 	}
4870 	/*
4871 	 * If the user has closed the socket then drop a persisting
4872 	 * connection after a much reduced timeout.
4873 	 */
4874 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4875 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4876 		TCPSTAT_INC(tcps_persistdrop);
4877 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4878 		goto out;
4879 	}
4880 	t_template = tcpip_maketemplate(bbr->rc_inp);
4881 	if (t_template) {
4882 		tcp_respond(tp, t_template->tt_ipgen,
4883 			    &t_template->tt_t, (struct mbuf *)NULL,
4884 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4885 		/* This sends an ack */
4886 		if (tp->t_flags & TF_DELACK)
4887 			tp->t_flags &= ~TF_DELACK;
4888 		free(t_template, M_TEMP);
4889 	}
4890 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4891 		tp->t_rxtshift++;
4892 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4893 out:
4894 	return (retval);
4895 }
4896 
4897 /*
4898  * If a keepalive goes off, we had no other timers
4899  * happening. We always return 1 here since this
4900  * routine either drops the connection or sends
4901  * out a segment with respond.
4902  */
4903 static int
4904 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4905 {
4906 	struct tcptemp *t_template;
4907 	struct inpcb *inp;
4908 
4909 	if (bbr->rc_all_timers_stopped) {
4910 		return (1);
4911 	}
4912 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4913 	inp = tp->t_inpcb;
4914 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4915 	/*
4916 	 * Keep-alive timer went off; send something or drop connection if
4917 	 * idle for too long.
4918 	 */
4919 	TCPSTAT_INC(tcps_keeptimeo);
4920 	if (tp->t_state < TCPS_ESTABLISHED)
4921 		goto dropit;
4922 	if ((tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4923 	    tp->t_state <= TCPS_CLOSING) {
4924 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4925 			goto dropit;
4926 		/*
4927 		 * Send a packet designed to force a response if the peer is
4928 		 * up and reachable: either an ACK if the connection is
4929 		 * still alive, or an RST if the peer has closed the
4930 		 * connection due to timeout or reboot. Using sequence
4931 		 * number tp->snd_una-1 causes the transmitted zero-length
4932 		 * segment to lie outside the receive window; by the
4933 		 * protocol spec, this requires the correspondent TCP to
4934 		 * respond.
4935 		 */
4936 		TCPSTAT_INC(tcps_keepprobe);
4937 		t_template = tcpip_maketemplate(inp);
4938 		if (t_template) {
4939 			tcp_respond(tp, t_template->tt_ipgen,
4940 			    &t_template->tt_t, (struct mbuf *)NULL,
4941 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4942 			free(t_template, M_TEMP);
4943 		}
4944 	}
4945 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4946 	return (1);
4947 dropit:
4948 	TCPSTAT_INC(tcps_keepdrops);
4949 	tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4950 	return (1);
4951 }
4952 
4953 /*
4954  * Retransmit helper function, clear up all the ack
4955  * flags and take care of important book keeping.
4956  */
4957 static void
4958 bbr_remxt_tmr(struct tcpcb *tp)
4959 {
4960 	/*
4961 	 * The retransmit timer went off, all sack'd blocks must be
4962 	 * un-acked.
4963 	 */
4964 	struct bbr_sendmap *rsm, *trsm = NULL;
4965 	struct tcp_bbr *bbr;
4966 	uint32_t cts, lost;
4967 
4968 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4969 	cts = tcp_get_usecs(&bbr->rc_tv);
4970 	lost = bbr->r_ctl.rc_lost;
4971 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4972 		bbr_set_state(tp, bbr, 0);
4973 
4974 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4975 		if (rsm->r_flags & BBR_ACKED) {
4976 			uint32_t old_flags;
4977 
4978 			rsm->r_dupack = 0;
4979 			if (rsm->r_in_tmap == 0) {
4980 				/* We must re-add it back to the tlist */
4981 				if (trsm == NULL) {
4982 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4983 				} else {
4984 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4985 				}
4986 				rsm->r_in_tmap = 1;
4987 			}
4988 			old_flags = rsm->r_flags;
4989 			rsm->r_flags |= BBR_RXT_CLEARED;
4990 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4991 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4992 		} else {
4993 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4994 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4995 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4996 			}
4997 			if (bbr_marks_rxt_sack_passed) {
4998 				/*
4999 				 * With this option, we will rack out
5000 				 * in 1ms increments the rest of the packets.
5001 				 */
5002 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
5003 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
5004 			} else {
5005 				/*
5006 				 * With this option we only mark them lost
5007 				 * and remove all sack'd markings. We will run
5008 				 * another RXT or a TLP. This will cause
5009 				 * us to eventually send more based on what
5010 				 * ack's come in.
5011 				 */
5012 				rsm->r_flags |= BBR_MARKED_LOST;
5013 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
5014 				rsm->r_flags &= ~BBR_SACK_PASSED;
5015 			}
5016 		}
5017 		trsm = rsm;
5018 	}
5019 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
5020 	/* Clear the count (we just un-acked them) */
5021 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
5022 	bbr->rc_tlp_new_data = 0;
5023 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
5024 	/* zap the behindness on a rxt */
5025 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
5026 	bbr->r_agg_early_set = 0;
5027 	bbr->r_ctl.rc_agg_early = 0;
5028 	bbr->rc_tlp_rtx_out = 0;
5029 	bbr->r_ctl.rc_sacked = 0;
5030 	bbr->r_ctl.rc_sacklast = NULL;
5031 	bbr->r_timer_override = 1;
5032 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
5033 }
5034 
5035 /*
5036  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
5037  * we will setup to retransmit the lowest seq number outstanding.
5038  */
5039 static int
5040 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
5041 {
5042 	int32_t rexmt;
5043 	int32_t retval = 0;
5044 
5045 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
5046 	if (bbr->rc_all_timers_stopped) {
5047 		return (1);
5048 	}
5049 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
5050 	    (tp->snd_una == tp->snd_max)) {
5051 		/* Nothing outstanding .. nothing to do */
5052 		return (0);
5053 	}
5054 	/*
5055 	 * Retransmission timer went off.  Message has not been acked within
5056 	 * retransmit interval.  Back off to a longer retransmit interval
5057 	 * and retransmit one segment.
5058 	 */
5059 	if (bbr_progress_timeout_check(bbr)) {
5060 		retval = 1;
5061 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
5062 		goto out;
5063 	}
5064 	bbr_remxt_tmr(tp);
5065 	if ((bbr->r_ctl.rc_resend == NULL) ||
5066 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
5067 		/*
5068 		 * If the rwnd collapsed on
5069 		 * the one we are retransmitting
5070 		 * it does not count against the
5071 		 * rxt count.
5072 		 */
5073 		tp->t_rxtshift++;
5074 	}
5075 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5076 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5077 		TCPSTAT_INC(tcps_timeoutdrop);
5078 		retval = 1;
5079 		tcp_set_inp_to_drop(bbr->rc_inp,
5080 		    (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
5081 		goto out;
5082 	}
5083 	if (tp->t_state == TCPS_SYN_SENT) {
5084 		/*
5085 		 * If the SYN was retransmitted, indicate CWND to be limited
5086 		 * to 1 segment in cc_conn_init().
5087 		 */
5088 		tp->snd_cwnd = 1;
5089 	} else if (tp->t_rxtshift == 1) {
5090 		/*
5091 		 * first retransmit; record ssthresh and cwnd so they can be
5092 		 * recovered if this turns out to be a "bad" retransmit. A
5093 		 * retransmit is considered "bad" if an ACK for this segment
5094 		 * is received within RTT/2 interval; the assumption here is
5095 		 * that the ACK was already in flight.  See "On Estimating
5096 		 * End-to-End Network Path Properties" by Allman and Paxson
5097 		 * for more details.
5098 		 */
5099 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5100 		if (!IN_RECOVERY(tp->t_flags)) {
5101 			tp->snd_cwnd_prev = tp->snd_cwnd;
5102 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5103 			tp->snd_recover_prev = tp->snd_recover;
5104 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5105 			tp->t_flags |= TF_PREVVALID;
5106 		} else {
5107 			tp->t_flags &= ~TF_PREVVALID;
5108 		}
5109 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5110 	} else {
5111 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5112 		tp->t_flags &= ~TF_PREVVALID;
5113 	}
5114 	TCPSTAT_INC(tcps_rexmttimeo);
5115 	if ((tp->t_state == TCPS_SYN_SENT) ||
5116 	    (tp->t_state == TCPS_SYN_RECEIVED))
5117 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5118 	else
5119 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5120 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5121 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5122 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5123 	/*
5124 	 * We enter the path for PLMTUD if connection is established or, if
5125 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5126 	 * amount of data we send is very small, we could send it in couple
5127 	 * of packets and process straight to FIN. In that case we won't
5128 	 * catch ESTABLISHED state.
5129 	 */
5130 	if (V_tcp_pmtud_blackhole_detect && (((tp->t_state == TCPS_ESTABLISHED))
5131 	    || (tp->t_state == TCPS_FIN_WAIT_1))) {
5132 #ifdef INET6
5133 		int32_t isipv6;
5134 #endif
5135 
5136 		/*
5137 		 * Idea here is that at each stage of mtu probe (usually,
5138 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5139 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5140 		 * should take care of that.
5141 		 */
5142 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5143 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5144 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5145 		    tp->t_rxtshift % 2 == 0)) {
5146 			/*
5147 			 * Enter Path MTU Black-hole Detection mechanism: -
5148 			 * Disable Path MTU Discovery (IP "DF" bit). -
5149 			 * Reduce MTU to lower value than what we negotiated
5150 			 * with peer.
5151 			 */
5152 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5153 				/*
5154 				 * Record that we may have found a black
5155 				 * hole.
5156 				 */
5157 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5158 				/* Keep track of previous MSS. */
5159 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5160 			}
5161 			/*
5162 			 * Reduce the MSS to blackhole value or to the
5163 			 * default in an attempt to retransmit.
5164 			 */
5165 #ifdef INET6
5166 			isipv6 = bbr->r_is_v6;
5167 			if (isipv6 &&
5168 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5169 				/* Use the sysctl tuneable blackhole MSS. */
5170 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5171 				TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5172 			} else if (isipv6) {
5173 				/* Use the default MSS. */
5174 				tp->t_maxseg = V_tcp_v6mssdflt;
5175 				/*
5176 				 * Disable Path MTU Discovery when we switch
5177 				 * to minmss.
5178 				 */
5179 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5180 				TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5181 			}
5182 #endif
5183 #if defined(INET6) && defined(INET)
5184 			else
5185 #endif
5186 #ifdef INET
5187 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5188 				/* Use the sysctl tuneable blackhole MSS. */
5189 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5190 				TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5191 			} else {
5192 				/* Use the default MSS. */
5193 				tp->t_maxseg = V_tcp_mssdflt;
5194 				/*
5195 				 * Disable Path MTU Discovery when we switch
5196 				 * to minmss.
5197 				 */
5198 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5199 				TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5200 			}
5201 #endif
5202 		} else {
5203 			/*
5204 			 * If further retransmissions are still unsuccessful
5205 			 * with a lowered MTU, maybe this isn't a blackhole
5206 			 * and we restore the previous MSS and blackhole
5207 			 * detection flags. The limit '6' is determined by
5208 			 * giving each probe stage (1448, 1188, 524) 2
5209 			 * chances to recover.
5210 			 */
5211 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5212 			    (tp->t_rxtshift >= 6)) {
5213 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5214 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5215 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5216 				TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5217 			}
5218 		}
5219 	}
5220 	/*
5221 	 * Disable RFC1323 and SACK if we haven't got any response to our
5222 	 * third SYN to work-around some broken terminal servers (most of
5223 	 * which have hopefully been retired) that have bad VJ header
5224 	 * compression code which trashes TCP segments containing
5225 	 * unknown-to-them TCP options.
5226 	 */
5227 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5228 	    (tp->t_rxtshift == 3))
5229 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5230 	/*
5231 	 * If we backed off this far, our srtt estimate is probably bogus.
5232 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5233 	 * move the current srtt into rttvar to keep the current retransmit
5234 	 * times until then.
5235 	 */
5236 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5237 #ifdef INET6
5238 		if (bbr->r_is_v6)
5239 			in6_losing(tp->t_inpcb);
5240 		else
5241 #endif
5242 			in_losing(tp->t_inpcb);
5243 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5244 		tp->t_srtt = 0;
5245 	}
5246 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5247 	tp->snd_recover = tp->snd_max;
5248 	tp->t_flags |= TF_ACKNOW;
5249 	tp->t_rtttime = 0;
5250 out:
5251 	return (retval);
5252 }
5253 
5254 static int
5255 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5256 {
5257 	int32_t ret = 0;
5258 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5259 
5260 	if (timers == 0) {
5261 		return (0);
5262 	}
5263 	if (tp->t_state == TCPS_LISTEN) {
5264 		/* no timers on listen sockets */
5265 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5266 			return (0);
5267 		return (1);
5268 	}
5269 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5270 		uint32_t left;
5271 
5272 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5273 			ret = -1;
5274 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5275 			return (0);
5276 		}
5277 		if (hpts_calling == 0) {
5278 			ret = -2;
5279 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5280 			return (0);
5281 		}
5282 		/*
5283 		 * Ok our timer went off early and we are not paced false
5284 		 * alarm, go back to sleep.
5285 		 */
5286 		left = bbr->r_ctl.rc_timer_exp - cts;
5287 		ret = -3;
5288 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5289 		tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5290 		return (1);
5291 	}
5292 	bbr->rc_tmr_stopped = 0;
5293 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5294 	if (timers & PACE_TMR_DELACK) {
5295 		ret = bbr_timeout_delack(tp, bbr, cts);
5296 	} else if (timers & PACE_TMR_PERSIT) {
5297 		ret = bbr_timeout_persist(tp, bbr, cts);
5298 	} else if (timers & PACE_TMR_RACK) {
5299 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5300 		ret = bbr_timeout_rack(tp, bbr, cts);
5301 	} else if (timers & PACE_TMR_TLP) {
5302 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5303 		ret = bbr_timeout_tlp(tp, bbr, cts);
5304 	} else if (timers & PACE_TMR_RXT) {
5305 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5306 		ret = bbr_timeout_rxt(tp, bbr, cts);
5307 	} else if (timers & PACE_TMR_KEEP) {
5308 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5309 	}
5310 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5311 	return (ret);
5312 }
5313 
5314 static void
5315 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5316 {
5317 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5318 		uint8_t hpts_removed = 0;
5319 
5320 		if (bbr->rc_inp->inp_in_hpts &&
5321 		    (bbr->rc_timer_first == 1)) {
5322 			/*
5323 			 * If we are canceling timer's when we have the
5324 			 * timer ahead of the output being paced. We also
5325 			 * must remove ourselves from the hpts.
5326 			 */
5327 			hpts_removed = 1;
5328 			tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
5329 			if (bbr->r_ctl.rc_last_delay_val) {
5330 				/* Update the last hptsi delay too */
5331 				uint32_t time_since_send;
5332 
5333 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5334 					time_since_send = cts - bbr->rc_pacer_started;
5335 				else
5336 					time_since_send = 0;
5337 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5338 					/* Cut down our slot time */
5339 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5340 				} else {
5341 					bbr->r_ctl.rc_last_delay_val = 0;
5342 				}
5343 				bbr->rc_pacer_started = cts;
5344 			}
5345 		}
5346 		bbr->rc_timer_first = 0;
5347 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5348 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5349 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5350 	}
5351 }
5352 
5353 static void
5354 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5355 {
5356 	struct tcp_bbr *bbr;
5357 
5358 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5359 	bbr->rc_all_timers_stopped = 1;
5360 	return;
5361 }
5362 
5363 /*
5364  * stop all timers always returning 0.
5365  */
5366 static int
5367 bbr_stopall(struct tcpcb *tp)
5368 {
5369 	return (0);
5370 }
5371 
5372 static void
5373 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5374 {
5375 	return;
5376 }
5377 
5378 /*
5379  * return true if a bbr timer (rack or tlp) is active.
5380  */
5381 static int
5382 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5383 {
5384 	return (0);
5385 }
5386 
5387 static uint32_t
5388 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5389 {
5390 	struct bbr_sendmap *rsm;
5391 
5392 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5393 	if ((rsm == NULL) || (u_rsm == rsm))
5394 		return (cts);
5395 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5396 }
5397 
5398 static void
5399 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5400      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5401 {
5402 	int32_t idx;
5403 
5404 	rsm->r_rtr_cnt++;
5405 	rsm->r_dupack = 0;
5406 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5407 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5408 		rsm->r_flags |= BBR_OVERMAX;
5409 	}
5410 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5411 		/* Take off the collapsed flag at rxt */
5412 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5413 	}
5414 	if (rsm->r_flags & BBR_MARKED_LOST) {
5415 		/* We have retransmitted, its no longer lost */
5416 		rsm->r_flags &= ~BBR_MARKED_LOST;
5417 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5418 	}
5419 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5420 		/*
5421 		 * We hit a RXT timer on it and
5422 		 * we cleared the "acked" flag.
5423 		 * We now have it going back into
5424 		 * flight, we can remove the cleared
5425 		 * flag and possibly do accounting on
5426 		 * this piece.
5427 		 */
5428 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5429 	}
5430 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5431 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5432 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5433 	}
5434 	idx = rsm->r_rtr_cnt - 1;
5435 	rsm->r_tim_lastsent[idx] = cts;
5436 	rsm->r_pacing_delay = pacing_time;
5437 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5438 	rsm->r_ts_valid = bbr->rc_ts_valid;
5439 	if (bbr->rc_ts_valid)
5440 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5441 	if (bbr->r_ctl.r_app_limited_until)
5442 		rsm->r_app_limited = 1;
5443 	else
5444 		rsm->r_app_limited = 0;
5445 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5446 		rsm->r_bbr_state = bbr_state_val(bbr);
5447 	else
5448 		rsm->r_bbr_state = 8;
5449 	if (rsm->r_flags & BBR_ACKED) {
5450 		/* Problably MTU discovery messing with us */
5451 		uint32_t old_flags;
5452 
5453 		old_flags = rsm->r_flags;
5454 		rsm->r_flags &= ~BBR_ACKED;
5455 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5456 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5457 		if (bbr->r_ctl.rc_sacked == 0)
5458 			bbr->r_ctl.rc_sacklast = NULL;
5459 	}
5460 	if (rsm->r_in_tmap) {
5461 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5462 	}
5463 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5464 	rsm->r_in_tmap = 1;
5465 	if (rsm->r_flags & BBR_SACK_PASSED) {
5466 		/* We have retransmitted due to the SACK pass */
5467 		rsm->r_flags &= ~BBR_SACK_PASSED;
5468 		rsm->r_flags |= BBR_WAS_SACKPASS;
5469 	}
5470 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5471 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5472 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5473 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5474 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5475 		rsm->r_is_gain = 1;
5476 		rsm->r_is_drain = 0;
5477 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5478 		rsm->r_is_drain = 1;
5479 		rsm->r_is_gain = 0;
5480 	} else {
5481 		rsm->r_is_drain = 0;
5482 		rsm->r_is_gain = 0;
5483 	}
5484 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5485 }
5486 
5487 /*
5488  * Returns 0, or the sequence where we stopped
5489  * updating. We also update the lenp to be the amount
5490  * of data left.
5491  */
5492 
5493 static uint32_t
5494 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5495     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5496 {
5497 	/*
5498 	 * We (re-)transmitted starting at rsm->r_start for some length
5499 	 * (possibly less than r_end.
5500 	 */
5501 	struct bbr_sendmap *nrsm;
5502 	uint32_t c_end;
5503 	int32_t len;
5504 
5505 	len = *lenp;
5506 	c_end = rsm->r_start + len;
5507 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5508 		/*
5509 		 * We retransmitted the whole piece or more than the whole
5510 		 * slopping into the next rsm.
5511 		 */
5512 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5513 		if (c_end == rsm->r_end) {
5514 			*lenp = 0;
5515 			return (0);
5516 		} else {
5517 			int32_t act_len;
5518 
5519 			/* Hangs over the end return whats left */
5520 			act_len = rsm->r_end - rsm->r_start;
5521 			*lenp = (len - act_len);
5522 			return (rsm->r_end);
5523 		}
5524 		/* We don't get out of this block. */
5525 	}
5526 	/*
5527 	 * Here we retransmitted less than the whole thing which means we
5528 	 * have to split this into what was transmitted and what was not.
5529 	 */
5530 	nrsm = bbr_alloc_full_limit(bbr);
5531 	if (nrsm == NULL) {
5532 		*lenp = 0;
5533 		return (0);
5534 	}
5535 	/*
5536 	 * So here we are going to take the original rsm and make it what we
5537 	 * retransmitted. nrsm will be the tail portion we did not
5538 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5539 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5540 	 * 1, 6 and the new piece will be 6, 11.
5541 	 */
5542 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5543 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5544 	nrsm->r_dupack = 0;
5545 	if (rsm->r_in_tmap) {
5546 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5547 		nrsm->r_in_tmap = 1;
5548 	}
5549 	rsm->r_flags &= (~BBR_HAS_FIN);
5550 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5551 	*lenp = 0;
5552 	return (0);
5553 }
5554 
5555 static uint64_t
5556 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5557 {
5558 	uint64_t bw;
5559 
5560 	bw = bbr_get_bw(bbr);
5561 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5562 	bw /= (uint64_t)BBR_UNIT;
5563 	return(bw);
5564 }
5565 
5566 static void
5567 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5568 		       uint64_t act_rate, uint64_t rate_wanted)
5569 {
5570 	/*
5571 	 * We could not get a full gains worth
5572 	 * of rate.
5573 	 */
5574 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5575 		/* we can't even get the real rate */
5576 		uint64_t red;
5577 
5578 		bbr->skip_gain = 1;
5579 		bbr->gain_is_limited = 0;
5580 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5581 		if (red)
5582 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5583 	} else {
5584 		/* We can use a lower gain */
5585 		bbr->skip_gain = 0;
5586 		bbr->gain_is_limited = 1;
5587 	}
5588 }
5589 
5590 static void
5591 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5592 {
5593 	const struct tcp_hwrate_limit_table *nrte;
5594 	int error, rate = -1;
5595 
5596 	if (bbr->r_ctl.crte == NULL)
5597 		return;
5598 	if ((bbr->rc_inp->inp_route.ro_rt == NULL) ||
5599 	    (bbr->rc_inp->inp_route.ro_rt->rt_ifp == NULL)) {
5600 		/* Lost our routes? */
5601 		/* Clear the way for a re-attempt */
5602 		bbr->bbr_attempt_hdwr_pace = 0;
5603 lost_rate:
5604 		bbr->gain_is_limited = 0;
5605 		bbr->skip_gain = 0;
5606 		bbr->bbr_hdrw_pacing = 0;
5607 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5608 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5609 		tcp_bbr_tso_size_check(bbr, cts);
5610 		return;
5611 	}
5612 	rate = bbr_get_hardware_rate(bbr);
5613 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5614 				   bbr->rc_tp,
5615 				   bbr->rc_inp->inp_route.ro_rt->rt_ifp,
5616 				   rate,
5617 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5618 				   &error);
5619 	if (nrte == NULL) {
5620 		goto lost_rate;
5621 	}
5622 	if (nrte != bbr->r_ctl.crte) {
5623 		bbr->r_ctl.crte = nrte;
5624 		if (error == 0)  {
5625 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5626 			if (bbr->r_ctl.crte->rate < rate) {
5627 				/* We have a problem */
5628 				bbr_setup_less_of_rate(bbr, cts,
5629 						       bbr->r_ctl.crte->rate, rate);
5630 			} else {
5631 				/* We are good */
5632 				bbr->gain_is_limited = 0;
5633 				bbr->skip_gain = 0;
5634 			}
5635 		} else {
5636 			/* A failure should release the tag */
5637 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5638 			bbr->gain_is_limited = 0;
5639 			bbr->skip_gain = 0;
5640 			bbr->bbr_hdrw_pacing = 0;
5641 		}
5642 		bbr_type_log_hdwr_pacing(bbr,
5643 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5644 					 rate,
5645 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5646 					 __LINE__,
5647 					 cts,
5648 					 error);
5649 	}
5650 }
5651 
5652 static void
5653 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5654 {
5655 	/*
5656 	 * If we have hardware pacing support
5657 	 * we need to factor that in for our
5658 	 * TSO size.
5659 	 */
5660 	const struct tcp_hwrate_limit_table *rlp;
5661 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5662 
5663 	if ((bbr->bbr_hdrw_pacing == 0) ||
5664 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5665 	    (bbr->r_ctl.crte == NULL))
5666 		return;
5667 	if (bbr->hw_pacing_set == 0) {
5668 		/* Not yet by the hdwr pacing count delay */
5669 		return;
5670 	}
5671 	if (bbr_hdwr_pace_adjust == 0) {
5672 		/* No adjustment */
5673 		return;
5674 	}
5675 	rlp = bbr->r_ctl.crte;
5676 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5677 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5678 	else
5679 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5680 	/*
5681 	 * So lets first get the
5682 	 * time we will take between
5683 	 * TSO sized sends currently without
5684 	 * hardware help.
5685 	 */
5686 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5687 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5688 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5689 	hdwr_delay *= rlp->time_between;
5690 	if (cur_delay > hdwr_delay)
5691 		delta = cur_delay - hdwr_delay;
5692 	else
5693 		delta = 0;
5694 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5695 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5696 			     1);
5697 	if (delta &&
5698 	    (delta < (max(rlp->time_between,
5699 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5700 		/*
5701 		 * Now lets divide by the pacing
5702 		 * time between each segment the
5703 		 * hardware sends rounding up and
5704 		 * derive a bytes from that. We multiply
5705 		 * that by bbr_hdwr_pace_adjust to get
5706 		 * more bang for our buck.
5707 		 *
5708 		 * The goal is to have the software pacer
5709 		 * waiting no more than an additional
5710 		 * pacing delay if we can (without the
5711 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5712 		 */
5713 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5714 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5715 		seg_sz *= bbr_hdwr_pace_adjust;
5716 		if (bbr_hdwr_pace_floor &&
5717 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5718 			/* Currently hardware paces
5719 			 * out rs_min_seg segments at a time.
5720 			 * We need to make sure we always send at least
5721 			 * a full burst of bbr_hdwr_pace_floor down.
5722 			 */
5723 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5724 		}
5725 		seg_sz *= maxseg;
5726 	} else if (delta == 0) {
5727 		/*
5728 		 * The highest pacing rate is
5729 		 * above our b/w gained. This means
5730 		 * we probably are going quite fast at
5731 		 * the hardware highest rate. Lets just multiply
5732 		 * the calculated TSO size by the
5733 		 * multiplier factor (its probably
5734 		 * 4 segments in the default config for
5735 		 * mlx).
5736 		 */
5737 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5738 		if (bbr_hdwr_pace_floor &&
5739 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5740 			/* Currently hardware paces
5741 			 * out rs_min_seg segments at a time.
5742 			 * We need to make sure we always send at least
5743 			 * a full burst of bbr_hdwr_pace_floor down.
5744 			 */
5745 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5746 		}
5747 	} else {
5748 		/*
5749 		 * The pacing time difference is so
5750 		 * big that the hardware will
5751 		 * pace out more rapidly then we
5752 		 * really want and then we
5753 		 * will have a long delay. Lets just keep
5754 		 * the same TSO size so its as if
5755 		 * we were not using hdwr pacing (we
5756 		 * just gain a bit of spacing from the
5757 		 * hardware if seg_sz > 1).
5758 		 */
5759 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5760 	}
5761 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5762 		new_tso = seg_sz;
5763 	else
5764 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5765 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5766 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5767 
5768 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5769 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5770 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5771 	}
5772 }
5773 
5774 static void
5775 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5776 {
5777 	uint64_t bw;
5778 	uint32_t old_tso = 0, new_tso;
5779 	uint32_t maxseg, bytes;
5780 	uint32_t tls_seg=0;
5781 	/*
5782 	 * Google/linux uses the following algorithm to determine
5783 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5784 	 *
5785 	 *  bytes = bw_in_bytes_per_second / 1000
5786 	 *  bytes = min(bytes, 64k)
5787 	 *  tso_segs = bytes / MSS
5788 	 *  if (bw < 1.2Mbs)
5789 	 *      min_tso_segs = 1
5790 	 *  else
5791 	 *	min_tso_segs = 2
5792 	 * tso_segs = max(tso_segs, min_tso_segs)
5793 	 *
5794 	 * * Note apply a device specific limit (we apply this in the
5795 	 *   tcp_m_copym).
5796 	 * Note that before the initial measurement is made google bursts out
5797 	 * a full iwnd just like new-reno/cubic.
5798 	 *
5799 	 * We do not use this algorithm. Instead we
5800 	 * use a two phased approach:
5801 	 *
5802 	 *  if ( bw <= per-tcb-cross-over)
5803 	 *     goal_tso =  calculate how much with this bw we
5804 	 *                 can send in goal-time seconds.
5805 	 *     if (goal_tso > mss)
5806 	 *         seg = goal_tso / mss
5807 	 *         tso = seg * mss
5808 	 *     else
5809          *         tso = mss
5810 	 *     if (tso > per-tcb-max)
5811 	 *         tso = per-tcb-max
5812 	 *  else if ( bw > 512Mbps)
5813 	 *     tso = max-tso (64k/mss)
5814 	 *  else
5815 	 *     goal_tso = bw / per-tcb-divsor
5816 	 *     seg = (goal_tso + mss-1)/mss
5817 	 *     tso = seg * mss
5818 	 *
5819 	 * if (tso < per-tcb-floor)
5820 	 *    tso = per-tcb-floor
5821 	 * if (tso > per-tcb-utter_max)
5822 	 *    tso = per-tcb-utter_max
5823 	 *
5824 	 * Note the default per-tcb-divisor is 1000 (same as google).
5825 	 * the goal cross over is 30Mbps however. To recreate googles
5826 	 * algorithm you need to set:
5827 	 *
5828 	 * cross-over = 23,168,000 bps
5829 	 * goal-time = 18000
5830 	 * per-tcb-max = 2
5831 	 * per-tcb-divisor = 1000
5832 	 * per-tcb-floor = 1
5833 	 *
5834 	 * This will get you "google bbr" behavior with respect to tso size.
5835 	 *
5836 	 * Note we do set anything TSO size until we are past the initial
5837 	 * window. Before that we gnerally use either a single MSS
5838 	 * or we use the full IW size (so we burst a IW at a time)
5839 	 * Also note that Hardware-TLS is special and does alternate
5840 	 * things to minimize PCI Bus Bandwidth use.
5841 	 */
5842 
5843 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5844 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5845 	} else {
5846 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5847 	}
5848 #ifdef KERN_TLS
5849 	if (bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) {
5850 		tls_seg =  ctf_get_opt_tls_size(bbr->rc_inp->inp_socket, bbr->rc_tp->snd_wnd);
5851 		bbr->r_ctl.rc_pace_min_segs = (tls_seg + bbr->rc_last_options);
5852 	}
5853 #endif
5854 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5855 	if (bbr->rc_past_init_win == 0) {
5856 		/*
5857 		 * Not enough data has been acknowledged to make a
5858 		 * judgement unless we are hardware TLS. Set up
5859 		 * the inital TSO based on if we are sending a
5860 		 * full IW at once or not.
5861 		 */
5862 		if (bbr->rc_use_google)
5863 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5864 		else if (bbr->bbr_init_win_cheat)
5865 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5866 		else
5867 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5868 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5869 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5870 #ifdef KERN_TLS
5871 		if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) && tls_seg) {
5872 			/*
5873 			 * For hardware TLS we set our min to the tls_seg size.
5874 			 */
5875 			bbr->r_ctl.rc_pace_max_segs = tls_seg;
5876 			bbr->r_ctl.rc_pace_min_segs = tls_seg + bbr->rc_last_options;
5877 		}
5878 #endif
5879 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5880 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5881 		}
5882 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5883 #ifdef KERN_TLS
5884 		if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) == 0)
5885 #endif
5886 			bbr_adjust_for_hw_pacing(bbr, cts);
5887 		return;
5888 	}
5889 	/**
5890 	 * Now lets set the TSO goal based on our delivery rate in
5891 	 * bytes per second. Note we only do this if
5892 	 * we have acked at least the initial cwnd worth of data.
5893 	 */
5894 	bw = bbr_get_bw(bbr);
5895 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5896 	     (bbr->rc_use_google == 0)) {
5897 		/* We clamp to one MSS in recovery */
5898 		new_tso = maxseg;
5899 	} else if (bbr->rc_use_google) {
5900 		int min_tso_segs;
5901 
5902 		/* Google considers the gain too */
5903 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5904 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5905 			bw /= BBR_UNIT;
5906 		}
5907 		bytes = bw / 1024;
5908 		if (bytes > (64 * 1024))
5909 			bytes = 64 * 1024;
5910 		new_tso = bytes / maxseg;
5911 		if (bw < ONE_POINT_TWO_MEG)
5912 			min_tso_segs = 1;
5913 		else
5914 			min_tso_segs = 2;
5915 		if (new_tso < min_tso_segs)
5916 			new_tso = min_tso_segs;
5917 		new_tso *= maxseg;
5918 	} else if (bbr->rc_no_pacing) {
5919 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5920 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5921 		/*
5922 		 * Calculate the worse case b/w TSO if we are inserting no
5923 		 * more than a delay_target number of TSO's.
5924 		 */
5925 		uint32_t tso_len, min_tso;
5926 
5927 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5928 		if (tso_len > maxseg) {
5929 			new_tso = tso_len / maxseg;
5930 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5931 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5932 			new_tso *= maxseg;
5933 		} else {
5934 			/*
5935 			 * less than a full sized frame yikes.. long rtt or
5936 			 * low bw?
5937 			 */
5938 			min_tso = bbr_minseg(bbr);
5939 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5940 				new_tso = rounddown(tso_len, min_tso);
5941 			else
5942 				new_tso = min_tso;
5943 		}
5944 	} else if (bw > FIVETWELVE_MBPS) {
5945 		/*
5946 		 * This guy is so fast b/w wise that we can TSO as large as
5947 		 * possible of segments that the NIC will allow.
5948 		 */
5949 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5950 	} else {
5951 		/*
5952 		 * This formula is based on attempting to send a segment or
5953 		 * more every bbr_hptsi_per_second. The default is 1000
5954 		 * which means you are targeting what you can send every 1ms
5955 		 * based on the peers bw.
5956 		 *
5957 		 * If the number drops to say 500, then you are looking more
5958 		 * at 2ms and you will raise how much we send in a single
5959 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5960 		 * trade off of course is you will send more at once and
5961 		 * thus tend to clump up the sends into larger "bursts"
5962 		 * building a queue.
5963 		 */
5964 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5965 		new_tso = roundup(bw, (uint64_t)maxseg);
5966 		/*
5967 		 * Gate the floor to match what our lower than 48Mbps
5968 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5969 		 * becomes the floor for this calculation.
5970 		 */
5971 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5972 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5973 	}
5974 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5975 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5976 	if (new_tso > PACE_MAX_IP_BYTES)
5977 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5978 	/* Enforce an utter maximum if we are not HW-TLS */
5979 #ifdef KERN_TLS
5980 	if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) == 0)
5981 #endif
5982 		if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5983 			new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5984 		}
5985 #ifdef KERN_TLS
5986 	if (tls_seg) {
5987 		/*
5988 		 * Lets move the output size
5989 		 * up to 1 or more TLS record sizes.
5990 		 */
5991 		uint32_t temp;
5992 
5993 		temp = roundup(new_tso, tls_seg);
5994 		new_tso = temp;
5995 		/* Back down if needed to under a full frame */
5996 		while (new_tso > PACE_MAX_IP_BYTES)
5997 			new_tso -= tls_seg;
5998 	}
5999 #endif
6000 	if (old_tso != new_tso) {
6001 		/* Only log changes */
6002 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
6003 		bbr->r_ctl.rc_pace_max_segs = new_tso;
6004 	}
6005 #ifdef KERN_TLS
6006 	if ((bbr->rc_inp->inp_socket->so_snd.sb_flags & SB_TLS_IFNET) &&
6007 	     tls_seg) {
6008 		bbr->r_ctl.rc_pace_min_segs = tls_seg + bbr->rc_last_options;
6009 	} else
6010 #endif
6011 		/* We have hardware pacing and not hardware TLS! */
6012 		bbr_adjust_for_hw_pacing(bbr, cts);
6013 }
6014 
6015 static void
6016 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
6017     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t cts,
6018     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
6019     struct sockbuf *sb)
6020 {
6021 
6022 	struct bbr_sendmap *rsm, *nrsm;
6023 	register uint32_t snd_max, snd_una;
6024 	uint32_t pacing_time;
6025 	/*
6026 	 * Add to the RACK log of packets in flight or retransmitted. If
6027 	 * there is a TS option we will use the TS echoed, if not we will
6028 	 * grab a TS.
6029 	 *
6030 	 * Retransmissions will increment the count and move the ts to its
6031 	 * proper place. Note that if options do not include TS's then we
6032 	 * won't be able to effectively use the ACK for an RTT on a retran.
6033 	 *
6034 	 * Notes about r_start and r_end. Lets consider a send starting at
6035 	 * sequence 1 for 10 bytes. In such an example the r_start would be
6036 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
6037 	 * This means that r_end is actually the first sequence for the next
6038 	 * slot (11).
6039 	 *
6040 	 */
6041 	INP_WLOCK_ASSERT(tp->t_inpcb);
6042 	if (err) {
6043 		/*
6044 		 * We don't log errors -- we could but snd_max does not
6045 		 * advance in this case either.
6046 		 */
6047 		return;
6048 	}
6049 	if (th_flags & TH_RST) {
6050 		/*
6051 		 * We don't log resets and we return immediately from
6052 		 * sending
6053 		 */
6054 		*abandon = 1;
6055 		return;
6056 	}
6057 	snd_una = tp->snd_una;
6058 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
6059 		/*
6060 		 * The call to bbr_log_output is made before bumping
6061 		 * snd_max. This means we can record one extra byte on a SYN
6062 		 * or FIN if seq_out is adding more on and a FIN is present
6063 		 * (and we are not resending).
6064 		 */
6065 		if (th_flags & TH_SYN)
6066 			len++;
6067 		if (th_flags & TH_FIN)
6068 			len++;
6069 	}
6070 	if (SEQ_LEQ((seq_out + len), snd_una)) {
6071 		/* Are sending an old segment to induce an ack (keep-alive)? */
6072 		return;
6073 	}
6074 	if (SEQ_LT(seq_out, snd_una)) {
6075 		/* huh? should we panic? */
6076 		uint32_t end;
6077 
6078 		end = seq_out + len;
6079 		seq_out = snd_una;
6080 		len = end - seq_out;
6081 	}
6082 	snd_max = tp->snd_max;
6083 	if (len == 0) {
6084 		/* We don't log zero window probes */
6085 		return;
6086 	}
6087 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
6088 	/* First question is it a retransmission? */
6089 	if (seq_out == snd_max) {
6090 again:
6091 		rsm = bbr_alloc(bbr);
6092 		if (rsm == NULL) {
6093 			return;
6094 		}
6095 		rsm->r_flags = 0;
6096 		if (th_flags & TH_SYN)
6097 			rsm->r_flags |= BBR_HAS_SYN;
6098 		if (th_flags & TH_FIN)
6099 			rsm->r_flags |= BBR_HAS_FIN;
6100 		rsm->r_tim_lastsent[0] = cts;
6101 		rsm->r_rtr_cnt = 1;
6102 		rsm->r_rtr_bytes = 0;
6103 		rsm->r_start = seq_out;
6104 		rsm->r_end = rsm->r_start + len;
6105 		rsm->r_dupack = 0;
6106 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
6107 		rsm->r_pacing_delay = pacing_time;
6108 		rsm->r_ts_valid = bbr->rc_ts_valid;
6109 		if (bbr->rc_ts_valid)
6110 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6111 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
6112 		if (bbr->r_ctl.r_app_limited_until)
6113 			rsm->r_app_limited = 1;
6114 		else
6115 			rsm->r_app_limited = 0;
6116 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6117 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6118 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6119 		/*
6120 		 * Here we must also add in this rsm since snd_max
6121 		 * is updated after we return from a new send.
6122 		 */
6123 		rsm->r_flight_at_send += len;
6124 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6125 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6126 		rsm->r_in_tmap = 1;
6127 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6128 			rsm->r_bbr_state = bbr_state_val(bbr);
6129 		else
6130 			rsm->r_bbr_state = 8;
6131 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6132 			rsm->r_is_gain = 1;
6133 			rsm->r_is_drain = 0;
6134 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6135 			rsm->r_is_drain = 1;
6136 			rsm->r_is_gain = 0;
6137 		} else {
6138 			rsm->r_is_drain = 0;
6139 			rsm->r_is_gain = 0;
6140 		}
6141 		return;
6142 	}
6143 	/*
6144 	 * If we reach here its a retransmission and we need to find it.
6145 	 */
6146 more:
6147 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6148 		rsm = hintrsm;
6149 		hintrsm = NULL;
6150 	} else if (bbr->r_ctl.rc_next) {
6151 		/* We have a hint from a previous run */
6152 		rsm = bbr->r_ctl.rc_next;
6153 	} else {
6154 		/* No hints sorry */
6155 		rsm = NULL;
6156 	}
6157 	if ((rsm) && (rsm->r_start == seq_out)) {
6158 		/*
6159 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6160 		 * likely case.
6161 		 */
6162 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6163 		if (len == 0) {
6164 			return;
6165 		} else {
6166 			goto more;
6167 		}
6168 	}
6169 	/* Ok it was not the last pointer go through it the hard way. */
6170 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6171 		if (rsm->r_start == seq_out) {
6172 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6173 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6174 			if (len == 0) {
6175 				return;
6176 			} else {
6177 				continue;
6178 			}
6179 		}
6180 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6181 			/* Transmitted within this piece */
6182 			/*
6183 			 * Ok we must split off the front and then let the
6184 			 * update do the rest
6185 			 */
6186 			nrsm = bbr_alloc_full_limit(bbr);
6187 			if (nrsm == NULL) {
6188 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6189 				return;
6190 			}
6191 			/*
6192 			 * copy rsm to nrsm and then trim the front of rsm
6193 			 * to not include this part.
6194 			 */
6195 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6196 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6197 			if (rsm->r_in_tmap) {
6198 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6199 				nrsm->r_in_tmap = 1;
6200 			}
6201 			rsm->r_flags &= (~BBR_HAS_FIN);
6202 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6203 			if (len == 0) {
6204 				return;
6205 			}
6206 		}
6207 	}
6208 	/*
6209 	 * Hmm not found in map did they retransmit both old and on into the
6210 	 * new?
6211 	 */
6212 	if (seq_out == tp->snd_max) {
6213 		goto again;
6214 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6215 #ifdef BBR_INVARIANTS
6216 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6217 		    seq_out, len, tp->snd_una, tp->snd_max);
6218 		printf("Starting Dump of all rack entries\n");
6219 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6220 			printf("rsm:%p start:%u end:%u\n",
6221 			    rsm, rsm->r_start, rsm->r_end);
6222 		}
6223 		printf("Dump complete\n");
6224 		panic("seq_out not found rack:%p tp:%p",
6225 		    bbr, tp);
6226 #endif
6227 	} else {
6228 #ifdef BBR_INVARIANTS
6229 		/*
6230 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6231 		 * flag)
6232 		 */
6233 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6234 		    seq_out, len, tp->snd_max, tp);
6235 #endif
6236 	}
6237 }
6238 
6239 static void
6240 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6241 {
6242 	/*
6243 	 * Collapse timeout back the cum-ack moved.
6244 	 */
6245 	tp->t_rxtshift = 0;
6246 	tp->t_softerror = 0;
6247 }
6248 
6249 
6250 static void
6251 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6252 {
6253 	bbr->rtt_valid = 1;
6254 	bbr->r_ctl.cur_rtt = rtt_usecs;
6255 	bbr->r_ctl.ts_in = tsin;
6256 	if (rsm_send_time)
6257 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6258 }
6259 
6260 static void
6261 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6262 {
6263 	/**
6264 	 * We have in our bbr control:
6265 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6266 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6267 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6268 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6269 	 *
6270 	 * Now we can calculate the time between the sends by doing:
6271 	 *
6272 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6273 	 *
6274 	 * And the peer's time between receiving them by doing:
6275 	 *
6276 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6277 	 *
6278 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6279 	 * We also may find that we can't use the timestamps if say we see
6280 	 * that the peer_delta indicates that though we may have taken 10ms to
6281 	 * pace out the data, it only saw 1ms between the two packets. This would
6282 	 * indicate that somewhere on the path is a batching entity that is giving
6283 	 * out time-slices of the actual b/w. This would mean we could not use
6284 	 * reliably the peers timestamps.
6285 	 *
6286 	 * We expect delta > peer_delta initially. Until we figure out the
6287 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6288 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6289 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6290 	 * put a 1 there. If the value is faster then ours, we will disable the
6291 	 * use of timestamps (though we could revist this later if we find it to be not
6292 	 * just an isolated one or two flows)).
6293 	 *
6294 	 * To detect the batching middle boxes we will come up with our compensation and
6295 	 * if with it in place, we find the peer is drastically off (by some margin) in
6296 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6297 	 *
6298 	 */
6299 	uint64_t delta, peer_delta, delta_up;
6300 
6301 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6302 	if (delta < bbr_min_usec_delta) {
6303 		/*
6304 		 * Have not seen a min amount of time
6305 		 * between our send times so we can
6306 		 * make a determination of the timestamp
6307 		 * yet.
6308 		 */
6309 		return;
6310 	}
6311 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6312 	if (peer_delta < bbr_min_peer_delta) {
6313 		/*
6314 		 * We may have enough in the form of
6315 		 * our delta but the peers number
6316 		 * has not changed that much. It could
6317 		 * be its clock ratio is such that
6318 		 * we need more data (10ms tick) or
6319 		 * there may be other compression scenarios
6320 		 * going on. In any event we need the
6321 		 * spread to be larger.
6322 		 */
6323 		return;
6324 	}
6325 	/* Ok lets first see which way our delta is going */
6326 	if (peer_delta > delta) {
6327 		/* Very unlikely, the peer without
6328 		 * compensation shows that it saw
6329 		 * the two sends arrive further apart
6330 		 * then we saw then in micro-seconds.
6331 		 */
6332 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6333 			/* well it looks like the peer is a micro-second clock. */
6334 			bbr->rc_ts_clock_set = 1;
6335 			bbr->r_ctl.bbr_peer_tsratio = 1;
6336 		} else {
6337 			bbr->rc_ts_cant_be_used = 1;
6338 			bbr->rc_ts_clock_set = 1;
6339 		}
6340 		return;
6341 	}
6342 	/* Ok we know that the peer_delta is smaller than our send distance */
6343 	bbr->rc_ts_clock_set = 1;
6344 	/* First question is it within the percentage that they are using usec time? */
6345 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6346 	if ((peer_delta + delta_up) >= delta) {
6347 		/* Its a usec clock */
6348 		bbr->r_ctl.bbr_peer_tsratio = 1;
6349 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6350 		return;
6351 	}
6352 	/* Ok if not usec, what about 10usec (though unlikely)? */
6353 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6354 	if (((peer_delta * 10) + delta_up) >= delta) {
6355 		bbr->r_ctl.bbr_peer_tsratio = 10;
6356 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6357 		return;
6358 	}
6359 	/* And what about 100usec (though again unlikely)? */
6360 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6361 	if (((peer_delta * 100) + delta_up) >= delta) {
6362 		bbr->r_ctl.bbr_peer_tsratio = 100;
6363 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6364 		return;
6365 	}
6366 	/* And how about 1 msec (the most likely one)? */
6367 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6368 	if (((peer_delta * 1000) + delta_up) >= delta) {
6369 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6370 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6371 		return;
6372 	}
6373 	/* Ok if not msec could it be 10 msec? */
6374 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6375 	if (((peer_delta * 10000) + delta_up) >= delta) {
6376 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6377 		return;
6378 	}
6379 	/* If we fall down here the clock tick so slowly we can't use it */
6380 	bbr->rc_ts_cant_be_used = 1;
6381 	bbr->r_ctl.bbr_peer_tsratio = 0;
6382 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6383 }
6384 
6385 /*
6386  * Collect new round-trip time estimate
6387  * and update averages and current timeout.
6388  */
6389 static void
6390 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6391 {
6392 	int32_t delta;
6393 	uint32_t rtt, tsin;
6394 	int32_t rtt_ticks;
6395 
6396 
6397 	if (bbr->rtt_valid == 0)
6398 		/* No valid sample */
6399 		return;
6400 
6401 	rtt = bbr->r_ctl.cur_rtt;
6402 	tsin = bbr->r_ctl.ts_in;
6403 	if (bbr->rc_prtt_set_ts) {
6404 		/*
6405 		 * We are to force feed the rttProp filter due
6406 		 * to an entry into PROBE_RTT. This assures
6407 		 * that the times are sync'd between when we
6408 		 * go into PROBE_RTT and the filter expiration.
6409 		 *
6410 		 * Google does not use a true filter, so they do
6411 		 * this implicitly since they only keep one value
6412 		 * and when they enter probe-rtt they update the
6413 		 * value to the newest rtt.
6414 		 */
6415 		uint32_t rtt_prop;
6416 
6417 		bbr->rc_prtt_set_ts = 0;
6418 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6419 		if (rtt > rtt_prop)
6420 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6421 		else
6422 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6423 	}
6424 	if (bbr->rc_ack_was_delayed)
6425 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6426 
6427 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6428 		bbr->r_ctl.rc_lowest_rtt = rtt;
6429 	bbr_log_rtt_sample(bbr, rtt, tsin);
6430 	if (bbr->r_init_rtt) {
6431 		/*
6432 		 * The initial rtt is not-trusted, nuke it and lets get
6433 		 * our first valid measurement in.
6434 		 */
6435 		bbr->r_init_rtt = 0;
6436 		tp->t_srtt = 0;
6437 	}
6438 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6439 		/*
6440 		 * So we have not yet figured out
6441 		 * what the peers TSTMP value is
6442 		 * in (most likely ms). We need a
6443 		 * series of cum-ack's to determine
6444 		 * this reliably.
6445 		 */
6446 		if (bbr->rc_ack_is_cumack) {
6447 			if (bbr->rc_ts_data_set) {
6448 				/* Lets attempt to determine the timestamp granularity. */
6449 				bbr_make_timestamp_determination(bbr);
6450 			} else {
6451 				bbr->rc_ts_data_set = 1;
6452 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6453 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6454 			}
6455 		} else {
6456 			/*
6457 			 * We have to have consecutive acks
6458 			 * reset any "filled" state to none.
6459 			 */
6460 			bbr->rc_ts_data_set = 0;
6461 		}
6462 	}
6463 	/* Round it up */
6464 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6465 	if (rtt_ticks == 0)
6466 		rtt_ticks = 1;
6467 	if (tp->t_srtt != 0) {
6468 		/*
6469 		 * srtt is stored as fixed point with 5 bits after the
6470 		 * binary point (i.e., scaled by 8).  The following magic is
6471 		 * equivalent to the smoothing algorithm in rfc793 with an
6472 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6473 		 * Adjust rtt to origin 0.
6474 		 */
6475 
6476 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6477 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6478 
6479 		tp->t_srtt += delta;
6480 		if (tp->t_srtt <= 0)
6481 			tp->t_srtt = 1;
6482 
6483 		/*
6484 		 * We accumulate a smoothed rtt variance (actually, a
6485 		 * smoothed mean difference), then set the retransmit timer
6486 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6487 		 * is stored as fixed point with 4 bits after the binary
6488 		 * point (scaled by 16).  The following is equivalent to
6489 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6490 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6491 		 * wired-in beta.
6492 		 */
6493 		if (delta < 0)
6494 			delta = -delta;
6495 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6496 		tp->t_rttvar += delta;
6497 		if (tp->t_rttvar <= 0)
6498 			tp->t_rttvar = 1;
6499 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6500 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6501 	} else {
6502 		/*
6503 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6504 		 * variance to half the rtt (so our first retransmit happens
6505 		 * at 3*rtt).
6506 		 */
6507 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6508 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6509 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6510 	}
6511 	TCPSTAT_INC(tcps_rttupdated);
6512 	tp->t_rttupdated++;
6513 #ifdef NETFLIX_STATS
6514 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6515 #endif
6516 	/*
6517 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6518 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6519 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6520 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6521 	 * uncertainty in the firing of the timer.  The bias will give us
6522 	 * exactly the 1.5 tick we need.  But, because the bias is
6523 	 * statistical, we have to test that we don't drop below the minimum
6524 	 * feasible timer (which is 2 ticks).
6525 	 */
6526 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6527 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6528 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6529 
6530 	/*
6531 	 * We received an ack for a packet that wasn't retransmitted; it is
6532 	 * probably safe to discard any error indications we've received
6533 	 * recently.  This isn't quite right, but close enough for now (a
6534 	 * route might have failed after we sent a segment, and the return
6535 	 * path might not be symmetrical).
6536 	 */
6537 	tp->t_softerror = 0;
6538 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6539 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6540 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6541 }
6542 
6543 static void
6544 bbr_earlier_retran(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm,
6545 		   uint32_t t, uint32_t cts, int ack_type)
6546 {
6547 	/*
6548 	 * For this RSM, we acknowledged the data from a previous
6549 	 * transmission, not the last one we made. This means we did a false
6550 	 * retransmit.
6551 	 */
6552 	if (rsm->r_flags & BBR_HAS_FIN) {
6553 		/*
6554 		 * The sending of the FIN often is multiple sent when we
6555 		 * have everything outstanding ack'd. We ignore this case
6556 		 * since its over now.
6557 		 */
6558 		return;
6559 	}
6560 	if (rsm->r_flags & BBR_TLP) {
6561 		/*
6562 		 * We expect TLP's to have this occur often
6563 		 */
6564 		bbr->rc_tlp_rtx_out = 0;
6565 		return;
6566 	}
6567 	if (ack_type != BBR_CUM_ACKED) {
6568 		/*
6569 		 * If it was not a cum-ack we
6570 		 * don't really know for sure since
6571 		 * the timestamp could be from some
6572 		 * other transmission.
6573 		 */
6574 		return;
6575 	}
6576 
6577 	if (rsm->r_flags & BBR_WAS_SACKPASS) {
6578 		/*
6579 		 * We retransmitted based on a sack and the earlier
6580 		 * retransmission ack'd it - re-ordering is occuring.
6581 		 */
6582 		BBR_STAT_INC(bbr_reorder_seen);
6583 		bbr->r_ctl.rc_reorder_ts = cts;
6584 	}
6585 	/* Back down the loss count */
6586 	if (rsm->r_flags & BBR_MARKED_LOST) {
6587 		bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
6588 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
6589 		rsm->r_flags &= ~BBR_MARKED_LOST;
6590 		if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
6591 			/* LT sampling also needs adjustment */
6592 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
6593 	}
6594 	/***** RRS HERE ************************/
6595 	/* Do we need to do this???            */
6596 	/* bbr_reset_lt_bw_sampling(bbr, cts); */
6597 	/***** RRS HERE ************************/
6598 	BBR_STAT_INC(bbr_badfr);
6599 	BBR_STAT_ADD(bbr_badfr_bytes, (rsm->r_end - rsm->r_start));
6600 }
6601 
6602 
6603 static void
6604 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6605 {
6606 	bbr->r_ctl.rc_rtt_shrinks = cts;
6607 	if (bbr_can_force_probertt &&
6608 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6609 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6610 		/*
6611 		 * We should enter probe-rtt its been too long
6612 		 * since we have been there.
6613 		 */
6614 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6615 	} else
6616 		bbr_check_probe_rtt_limits(bbr, cts);
6617 }
6618 
6619 static void
6620 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6621 {
6622 	uint64_t orig_bw;
6623 
6624 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6625 		/* We never apply a zero measurment */
6626 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6627 				    0, 0, 0, 0, 0, 0);
6628 		return;
6629 	}
6630 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6631 		bbr->r_ctl.r_measurement_count++;
6632 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6633 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6634 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6635 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6636 			    0, 0, 0, 0, 0, 0);
6637 	if (orig_bw &&
6638 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6639 		if (bbr->bbr_hdrw_pacing) {
6640 			/*
6641 			 * Apply a new rate to the hardware
6642 			 * possibly.
6643 			 */
6644 			bbr_update_hardware_pacing_rate(bbr, cts);
6645 		}
6646 		bbr_set_state_target(bbr, __LINE__);
6647 		tcp_bbr_tso_size_check(bbr, cts);
6648 		if (bbr->r_recovery_bw)  {
6649 			bbr_setup_red_bw(bbr, cts);
6650 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6651 		}
6652 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6653 		tcp_bbr_tso_size_check(bbr, cts);
6654 }
6655 
6656 static void
6657 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6658 {
6659 	if (bbr->rc_in_persist == 0) {
6660 		/* We log only when not in persist */
6661 		/* Translate to a Bytes Per Second */
6662 		uint64_t tim, bw, ts_diff, ts_bw;
6663 		uint32_t upper, lower, delivered;
6664 
6665 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6666 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6667 		else
6668 			tim = 1;
6669 		/*
6670 		 * Now that we have processed the tim (skipping the sample
6671 		 * or possibly updating the time, go ahead and
6672 		 * calculate the cdr.
6673 		 */
6674 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6675 		bw = (uint64_t)delivered;
6676 		bw *= (uint64_t)USECS_IN_SECOND;
6677 		bw /= tim;
6678 		if (bw == 0) {
6679 			/* We must have a calculatable amount */
6680 			return;
6681 		}
6682 		upper = (bw >> 32) & 0x00000000ffffffff;
6683 		lower = bw & 0x00000000ffffffff;
6684 		/*
6685 		 * If we are using this b/w shove it in now so we
6686 		 * can see in the trace viewer if it gets over-ridden.
6687 		 */
6688 		if (rsm->r_ts_valid &&
6689 		    bbr->rc_ts_valid &&
6690 		    bbr->rc_ts_clock_set &&
6691 		    (bbr->rc_ts_cant_be_used == 0) &&
6692 		    bbr->rc_use_ts_limit) {
6693 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6694 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6695 			if ((delivered == 0) ||
6696 			    (rtt < 1000)) {
6697 				/* Can't use the ts */
6698 				bbr_log_type_bbrupd(bbr, 61, cts,
6699 						    ts_diff,
6700 						    bbr->r_ctl.last_inbound_ts,
6701 						    rsm->r_del_ack_ts, 0,
6702 						    0, 0, 0, delivered);
6703 			} else {
6704 				ts_bw = (uint64_t)delivered;
6705 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6706 				ts_bw /= ts_diff;
6707 				bbr_log_type_bbrupd(bbr, 62, cts,
6708 						    (ts_bw >> 32),
6709 						    (ts_bw & 0xffffffff), 0, 0,
6710 						    0, 0, ts_diff, delivered);
6711 				if ((bbr->ts_can_raise) &&
6712 				    (ts_bw > bw)) {
6713 					bbr_log_type_bbrupd(bbr, 8, cts,
6714 							    delivered,
6715 							    ts_diff,
6716 							    (bw >> 32),
6717 							    (bw & 0x00000000ffffffff),
6718 							    0, 0, 0, 0);
6719 					bw = ts_bw;
6720 				} else if (ts_bw && (ts_bw < bw)) {
6721 					bbr_log_type_bbrupd(bbr, 7, cts,
6722 							    delivered,
6723 							    ts_diff,
6724 							    (bw >> 32),
6725 							    (bw & 0x00000000ffffffff),
6726 							    0, 0, 0, 0);
6727 					bw = ts_bw;
6728 				}
6729 			}
6730 		}
6731 		if (rsm->r_first_sent_time &&
6732 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6733 			uint64_t sbw, sti;
6734 			/*
6735 			 * We use what was in flight at the time of our
6736 			 * send  and the size of this send to figure
6737 			 * out what we have been sending at (amount).
6738 			 * For the time we take from the time of
6739 			 * the send of the first send outstanding
6740 			 * until this send plus this sends pacing
6741 			 * time. This gives us a good calculation
6742 			 * as to the rate we have been sending at.
6743 			 */
6744 
6745 			sbw = (uint64_t)(rsm->r_flight_at_send);
6746 			sbw *= (uint64_t)USECS_IN_SECOND;
6747 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6748 			sti += rsm->r_pacing_delay;
6749 			sbw /= sti;
6750 			if (sbw < bw) {
6751 				bbr_log_type_bbrupd(bbr, 6, cts,
6752 						    delivered,
6753 						    (uint32_t)sti,
6754 						    (bw >> 32),
6755 						    (uint32_t)bw,
6756 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6757 						    (uint32_t)sbw);
6758 				bw = sbw;
6759 			}
6760 		}
6761 		/* Use the google algorithm for b/w measurements */
6762 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6763 		if ((rsm->r_app_limited == 0) ||
6764 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6765 			tcp_bbr_commit_bw(bbr, cts);
6766 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6767 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6768 		}
6769 	}
6770 }
6771 
6772 static void
6773 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6774 {
6775 	if (bbr->rc_in_persist == 0) {
6776 		/* We log only when not in persist */
6777 		/* Translate to a Bytes Per Second */
6778 		uint64_t tim, bw;
6779 		uint32_t upper, lower, delivered;
6780 		int no_apply = 0;
6781 
6782 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6783 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6784 		else
6785 			tim = 1;
6786 		/*
6787 		 * Now that we have processed the tim (skipping the sample
6788 		 * or possibly updating the time, go ahead and
6789 		 * calculate the cdr.
6790 		 */
6791 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6792 		bw = (uint64_t)delivered;
6793 		bw *= (uint64_t)USECS_IN_SECOND;
6794 		bw /= tim;
6795 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6796 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6797 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6798 
6799 			no_apply = 1;
6800 		}
6801 		upper = (bw >> 32) & 0x00000000ffffffff;
6802 		lower = bw & 0x00000000ffffffff;
6803 		/*
6804 		 * If we are using this b/w shove it in now so we
6805 		 * can see in the trace viewer if it gets over-ridden.
6806 		 */
6807 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6808 		/* Gate by the sending rate */
6809 		if (rsm->r_first_sent_time &&
6810 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6811 			uint64_t sbw, sti;
6812 			/*
6813 			 * We use what was in flight at the time of our
6814 			 * send  and the size of this send to figure
6815 			 * out what we have been sending at (amount).
6816 			 * For the time we take from the time of
6817 			 * the send of the first send outstanding
6818 			 * until this send plus this sends pacing
6819 			 * time. This gives us a good calculation
6820 			 * as to the rate we have been sending at.
6821 			 */
6822 
6823 			sbw = (uint64_t)(rsm->r_flight_at_send);
6824 			sbw *= (uint64_t)USECS_IN_SECOND;
6825 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6826 			sti += rsm->r_pacing_delay;
6827 			sbw /= sti;
6828 			if (sbw < bw) {
6829 				bbr_log_type_bbrupd(bbr, 6, cts,
6830 						    delivered,
6831 						    (uint32_t)sti,
6832 						    (bw >> 32),
6833 						    (uint32_t)bw,
6834 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6835 						    (uint32_t)sbw);
6836 				bw = sbw;
6837 			}
6838 			if ((sti > tim) &&
6839 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6840 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6841 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6842 				no_apply = 1;
6843 			} else
6844 				no_apply = 0;
6845 		}
6846 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6847 		if ((no_apply == 0) &&
6848 		    ((rsm->r_app_limited == 0) ||
6849 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6850 			tcp_bbr_commit_bw(bbr, cts);
6851 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6852 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6853 		}
6854 	}
6855 }
6856 
6857 
6858 static void
6859 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6860     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6861 {
6862 	uint64_t old_rttprop;
6863 
6864 	/* Update our delivery time and amount */
6865 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6866 	bbr->r_ctl.rc_del_time = cts;
6867 	if (rtt == 0) {
6868 		/*
6869 		 * 0 means its a retransmit, for now we don't use these for
6870 		 * the rest of BBR.
6871 		 */
6872 		return;
6873 	}
6874 	if ((bbr->rc_use_google == 0) &&
6875 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6876 	    (match != BBR_RTT_BY_TIMESTAMP)){
6877 		/*
6878 		 * We get a lot of rtt updates, lets not pay attention to
6879 		 * any that are not an exact match. That way we don't have
6880 		 * to worry about timestamps and the whole nonsense of
6881 		 * unsure if its a retransmission etc (if we ever had the
6882 		 * timestamp fixed to always have the last thing sent this
6883 		 * would not be a issue).
6884 		 */
6885 		return;
6886 	}
6887 	if ((bbr_no_retran && bbr->rc_use_google) &&
6888 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6889 	    (match != BBR_RTT_BY_TIMESTAMP)){
6890 		/*
6891 		 * We only do measurements in google mode
6892 		 * with bbr_no_retran on for sure things.
6893 		 */
6894 		return;
6895 	}
6896 	/* Only update srtt if we know by exact match */
6897 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6898 	if (ack_type == BBR_CUM_ACKED)
6899 		bbr->rc_ack_is_cumack = 1;
6900 	else
6901 		bbr->rc_ack_is_cumack = 0;
6902 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6903         /*
6904 	 * Note the following code differs to the original
6905 	 * BBR spec. It calls for <= not <. However after a
6906 	 * long discussion in email with Neal, he acknowledged
6907 	 * that it should be < than so that we will have flows
6908 	 * going into probe-rtt (we were seeing cases where that
6909 	 * did not happen and caused ugly things to occur). We
6910 	 * have added this agreed upon fix to our code base.
6911 	 */
6912 	if (rtt < old_rttprop) {
6913 		/* Update when we last saw a rtt drop */
6914 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6915 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6916 	}
6917 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6918 	    match, rsm->r_start, rsm->r_flags);
6919 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6920 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6921 		/*
6922 		 * The RTT-prop moved, reset the target (may be a
6923 		 * nop for some states).
6924 		 */
6925 		bbr_set_state_target(bbr, __LINE__);
6926 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6927 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6928 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6929 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6930 			/* It went up */
6931 			bbr_check_probe_rtt_limits(bbr, cts);
6932 	}
6933 	if ((bbr->rc_use_google == 0) &&
6934 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6935 		/*
6936 		 * We don't do b/w update with
6937 		 * these since they are not really
6938 		 * reliable.
6939 		 */
6940 		return;
6941 	}
6942 	if (bbr->r_ctl.r_app_limited_until &&
6943 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6944 		/* We are no longer app-limited */
6945 		bbr->r_ctl.r_app_limited_until = 0;
6946 	}
6947 	if (bbr->rc_use_google) {
6948 		bbr_google_measurement(bbr, rsm, rtt, cts);
6949 	} else {
6950 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6951 	}
6952 }
6953 
6954 /*
6955  * Convert a timestamp that the main stack
6956  * uses (milliseconds) into one that bbr uses
6957  * (microseconds). Return that converted timestamp.
6958  */
6959 static uint32_t
6960 bbr_ts_convert(uint32_t cts) {
6961 	uint32_t sec, msec;
6962 
6963 	sec = cts / MS_IN_USEC;
6964 	msec = cts - (MS_IN_USEC * sec);
6965 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6966 }
6967 
6968 /*
6969  * Return 0 if we did not update the RTT time, return
6970  * 1 if we did.
6971  */
6972 static int
6973 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6974     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6975 {
6976 	int32_t i;
6977 	uint32_t t, uts = 0;
6978 
6979 	if ((rsm->r_flags & BBR_ACKED) ||
6980 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6981 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6982 		/* Already done */
6983 		return (0);
6984 	}
6985 	if (rsm->r_rtr_cnt == 1) {
6986 		/*
6987 		 * Only one transmit. Hopefully the normal case.
6988 		 */
6989 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6990 			t = cts - rsm->r_tim_lastsent[0];
6991 		else
6992 			t = 1;
6993 		if ((int)t <= 0)
6994 			t = 1;
6995 		bbr->r_ctl.rc_last_rtt = t;
6996 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6997 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6998 		return (1);
6999 	}
7000 	/* Convert to usecs */
7001 	if ((bbr_can_use_ts_for_rtt == 1) &&
7002 	    (bbr->rc_use_google == 1) &&
7003 	    (ack_type == BBR_CUM_ACKED) &&
7004 	    (to->to_flags & TOF_TS) &&
7005 	    (to->to_tsecr != 0)) {
7006 
7007 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
7008 		if (t < 1)
7009 			t = 1;
7010 		t *= MS_IN_USEC;
7011 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
7012 				    BBR_RTT_BY_TIMESTAMP,
7013 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
7014 				    ack_type, to);
7015 		return (1);
7016 	}
7017 	uts = bbr_ts_convert(to->to_tsecr);
7018 	if ((to->to_flags & TOF_TS) &&
7019 	    (to->to_tsecr != 0) &&
7020 	    (ack_type == BBR_CUM_ACKED) &&
7021 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
7022 		/*
7023 		 * Now which timestamp does it match? In this block the ACK
7024 		 * may be coming from a previous transmission.
7025 		 */
7026 		uint32_t fudge;
7027 
7028 		fudge = BBR_TIMER_FUDGE;
7029 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
7030 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
7031 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
7032 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
7033 					t = cts - rsm->r_tim_lastsent[i];
7034 				else
7035 					t = 1;
7036 				if ((int)t <= 0)
7037 					t = 1;
7038 				bbr->r_ctl.rc_last_rtt = t;
7039 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
7040 						    rsm->r_tim_lastsent[i], ack_type, to);
7041 				if ((i + 1) < rsm->r_rtr_cnt) {
7042 					/* Likely */
7043 					bbr_earlier_retran(tp, bbr, rsm, t, cts, ack_type);
7044 				} else if (rsm->r_flags & BBR_TLP) {
7045 					bbr->rc_tlp_rtx_out = 0;
7046 				}
7047 				return (1);
7048 			}
7049 		}
7050 		/* Fall through if we can't find a matching timestamp */
7051 	}
7052 	/*
7053 	 * Ok its a SACK block that we retransmitted. or a windows
7054 	 * machine without timestamps. We can tell nothing from the
7055 	 * time-stamp since its not there or the time the peer last
7056 	 * recieved a segment that moved forward its cum-ack point.
7057 	 *
7058 	 * Lets look at the last retransmit and see what we can tell
7059 	 * (with BBR for space we only keep 2 note we have to keep
7060 	 * at least 2 so the map can not be condensed more).
7061 	 */
7062 	i = rsm->r_rtr_cnt - 1;
7063 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
7064 		t = cts - rsm->r_tim_lastsent[i];
7065 	else
7066 		goto not_sure;
7067 	if (t < bbr->r_ctl.rc_lowest_rtt) {
7068 		/*
7069 		 * We retransmitted and the ack came back in less
7070 		 * than the smallest rtt we have observed in the
7071 		 * windowed rtt. We most likey did an improper
7072 		 * retransmit as outlined in 4.2 Step 3 point 2 in
7073 		 * the rack-draft.
7074 		 *
7075 		 * Use the prior transmission to update all the
7076 		 * information as long as there is only one prior
7077 		 * transmission.
7078 		 */
7079 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
7080 #ifdef BBR_INVARIANTS
7081 			if (rsm->r_rtr_cnt == 1)
7082 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
7083 #endif
7084 			i = rsm->r_rtr_cnt - 2;
7085 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
7086 				t = cts - rsm->r_tim_lastsent[i];
7087 			else
7088 				t = 1;
7089 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
7090 					    rsm->r_tim_lastsent[i], ack_type, to);
7091 			bbr_earlier_retran(tp, bbr, rsm, t, cts, ack_type);
7092 		} else {
7093 			/*
7094 			 * Too many prior transmissions, just
7095 			 * updated BBR delivered
7096 			 */
7097 not_sure:
7098 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
7099 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
7100 		}
7101 	} else {
7102 		/*
7103 		 * We retransmitted it and the retransmit did the
7104 		 * job.
7105 		 */
7106 		if (rsm->r_flags & BBR_TLP)
7107 			bbr->rc_tlp_rtx_out = 0;
7108 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
7109 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
7110 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
7111 		else
7112 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
7113 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
7114 		return (1);
7115 	}
7116 	return (0);
7117 }
7118 
7119 /*
7120  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
7121  */
7122 static void
7123 bbr_log_sack_passed(struct tcpcb *tp,
7124     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
7125 {
7126 	struct bbr_sendmap *nrsm;
7127 
7128 	nrsm = rsm;
7129 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
7130 	    bbr_head, r_tnext) {
7131 		if (nrsm == rsm) {
7132 			/* Skip orginal segment he is acked */
7133 			continue;
7134 		}
7135 		if (nrsm->r_flags & BBR_ACKED) {
7136 			/* Skip ack'd segments */
7137 			continue;
7138 		}
7139 		if (nrsm->r_flags & BBR_SACK_PASSED) {
7140 			/*
7141 			 * We found one that is already marked
7142 			 * passed, we have been here before and
7143 			 * so all others below this are marked.
7144 			 */
7145 			break;
7146 		}
7147 		BBR_STAT_INC(bbr_sack_passed);
7148 		nrsm->r_flags |= BBR_SACK_PASSED;
7149 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
7150 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
7151 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
7152 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
7153 			nrsm->r_flags |= BBR_MARKED_LOST;
7154 		}
7155 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
7156 	}
7157 }
7158 
7159 /*
7160  * Returns the number of bytes that were
7161  * newly ack'd by sack blocks.
7162  */
7163 static uint32_t
7164 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
7165     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
7166 {
7167 	int32_t times = 0;
7168 	uint32_t start, end, maxseg, changed = 0;
7169 	struct bbr_sendmap *rsm, *nrsm;
7170 	int32_t used_ref = 1;
7171 	uint8_t went_back = 0, went_fwd = 0;
7172 
7173 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7174 	start = sack->start;
7175 	end = sack->end;
7176 	rsm = *prsm;
7177 	if (rsm == NULL)
7178 		used_ref = 0;
7179 
7180 	/* Do we locate the block behind where we last were? */
7181 	if (rsm && SEQ_LT(start, rsm->r_start)) {
7182 		went_back = 1;
7183 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7184 			if (SEQ_GEQ(start, rsm->r_start) &&
7185 			    SEQ_LT(start, rsm->r_end)) {
7186 				goto do_rest_ofb;
7187 			}
7188 		}
7189 	}
7190 start_at_beginning:
7191 	went_fwd = 1;
7192 	/*
7193 	 * Ok lets locate the block where this guy is fwd from rsm (if its
7194 	 * set)
7195 	 */
7196 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7197 		if (SEQ_GEQ(start, rsm->r_start) &&
7198 		    SEQ_LT(start, rsm->r_end)) {
7199 			break;
7200 		}
7201 	}
7202 do_rest_ofb:
7203 	if (rsm == NULL) {
7204 		/*
7205 		 * This happens when we get duplicate sack blocks with the
7206 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7207 		 * will not change there location so we would just start at
7208 		 * the end of the first one and get lost.
7209 		 */
7210 		if (tp->t_flags & TF_SENTFIN) {
7211 			/*
7212 			 * Check to see if we have not logged the FIN that
7213 			 * went out.
7214 			 */
7215 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7216 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7217 				/*
7218 				 * Ok we did not get the FIN logged.
7219 				 */
7220 				nrsm->r_end++;
7221 				rsm = nrsm;
7222 				goto do_rest_ofb;
7223 			}
7224 		}
7225 		if (times == 1) {
7226 #ifdef BBR_INVARIANTS
7227 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7228 			    tp, bbr, sack, to, prsm);
7229 #else
7230 			goto out;
7231 #endif
7232 		}
7233 		times++;
7234 		BBR_STAT_INC(bbr_sack_proc_restart);
7235 		rsm = NULL;
7236 		goto start_at_beginning;
7237 	}
7238 	/* Ok we have an ACK for some piece of rsm */
7239 	if (rsm->r_start != start) {
7240 		/*
7241 		 * Need to split this in two pieces the before and after.
7242 		 */
7243 		if (bbr_sack_mergable(rsm, start, end))
7244 			nrsm = bbr_alloc_full_limit(bbr);
7245 		else
7246 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7247 		if (nrsm == NULL) {
7248 			/* We could not allocate ignore the sack */
7249 			struct sackblk blk;
7250 
7251 			blk.start = start;
7252 			blk.end = end;
7253 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7254 			goto out;
7255 		}
7256 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7257 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7258 		if (rsm->r_in_tmap) {
7259 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7260 			nrsm->r_in_tmap = 1;
7261 		}
7262 		rsm->r_flags &= (~BBR_HAS_FIN);
7263 		rsm = nrsm;
7264 	}
7265 	if (SEQ_GEQ(end, rsm->r_end)) {
7266 		/*
7267 		 * The end of this block is either beyond this guy or right
7268 		 * at this guy.
7269 		 */
7270 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7271 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7272 			changed += (rsm->r_end - rsm->r_start);
7273 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7274 			bbr_log_sack_passed(tp, bbr, rsm);
7275 			if (rsm->r_flags & BBR_MARKED_LOST) {
7276 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7277 			}
7278 			/* Is Reordering occuring? */
7279 			if (rsm->r_flags & BBR_SACK_PASSED) {
7280 				BBR_STAT_INC(bbr_reorder_seen);
7281 				bbr->r_ctl.rc_reorder_ts = cts;
7282 				if (rsm->r_flags & BBR_MARKED_LOST) {
7283 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7284 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7285 						/* LT sampling also needs adjustment */
7286 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7287 				}
7288 			}
7289 			rsm->r_flags |= BBR_ACKED;
7290 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7291 			if (rsm->r_in_tmap) {
7292 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7293 				rsm->r_in_tmap = 0;
7294 			}
7295 		}
7296 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7297 		if (end == rsm->r_end) {
7298 			/* This block only - done */
7299 			goto out;
7300 		}
7301 		/* There is more not coverend by this rsm move on */
7302 		start = rsm->r_end;
7303 		nrsm = TAILQ_NEXT(rsm, r_next);
7304 		rsm = nrsm;
7305 		times = 0;
7306 		goto do_rest_ofb;
7307 	}
7308 	if (rsm->r_flags & BBR_ACKED) {
7309 		/* Been here done that */
7310 		goto out;
7311 	}
7312 	/* Ok we need to split off this one at the tail */
7313 	if (bbr_sack_mergable(rsm, start, end))
7314 		nrsm = bbr_alloc_full_limit(bbr);
7315 	else
7316 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7317 	if (nrsm == NULL) {
7318 		/* failed XXXrrs what can we do but loose the sack info? */
7319 		struct sackblk blk;
7320 
7321 		blk.start = start;
7322 		blk.end = end;
7323 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7324 		goto out;
7325 	}
7326 	/* Clone it */
7327 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7328 	/* The sack block does not cover this guy fully */
7329 	rsm->r_flags &= (~BBR_HAS_FIN);
7330 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7331 	if (rsm->r_in_tmap) {
7332 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7333 		nrsm->r_in_tmap = 1;
7334 	}
7335 	nrsm->r_dupack = 0;
7336 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7337 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7338 	changed += (rsm->r_end - rsm->r_start);
7339 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7340 	bbr_log_sack_passed(tp, bbr, rsm);
7341 	/* Is Reordering occuring? */
7342 	if (rsm->r_flags & BBR_MARKED_LOST) {
7343 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7344 	}
7345 	if (rsm->r_flags & BBR_SACK_PASSED) {
7346 		BBR_STAT_INC(bbr_reorder_seen);
7347 		bbr->r_ctl.rc_reorder_ts = cts;
7348 		if (rsm->r_flags & BBR_MARKED_LOST) {
7349 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7350 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7351 				/* LT sampling also needs adjustment */
7352 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7353 		}
7354 	}
7355 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7356 	rsm->r_flags |= BBR_ACKED;
7357 	if (rsm->r_in_tmap) {
7358 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7359 		rsm->r_in_tmap = 0;
7360 	}
7361 out:
7362 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7363 		/*
7364 		 * Now can we merge this newly acked
7365 		 * block with either the previous or
7366 		 * next block?
7367 		 */
7368 		nrsm = TAILQ_NEXT(rsm, r_next);
7369 		if (nrsm &&
7370 		    (nrsm->r_flags & BBR_ACKED)) {
7371 			/* yep this and next can be merged */
7372 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7373 		}
7374 		/* Now what about the previous? */
7375 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7376 		if (nrsm &&
7377 		    (nrsm->r_flags & BBR_ACKED)) {
7378 			/* yep the previous and this can be merged */
7379 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7380 		}
7381 	}
7382 	if (used_ref == 0) {
7383 		BBR_STAT_INC(bbr_sack_proc_all);
7384 	} else {
7385 		BBR_STAT_INC(bbr_sack_proc_short);
7386 	}
7387 	if (went_fwd && went_back) {
7388 		BBR_STAT_INC(bbr_sack_search_both);
7389 	} else if (went_fwd) {
7390 		BBR_STAT_INC(bbr_sack_search_fwd);
7391 	} else if (went_back) {
7392 		BBR_STAT_INC(bbr_sack_search_back);
7393 	}
7394 	/* Save off where the next seq is */
7395 	if (rsm)
7396 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7397 	else
7398 		bbr->r_ctl.rc_sacklast = NULL;
7399 	*prsm = rsm;
7400 	return (changed);
7401 }
7402 
7403 
7404 static void inline
7405 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7406 {
7407 	struct bbr_sendmap *tmap;
7408 
7409 	BBR_STAT_INC(bbr_reneges_seen);
7410 	tmap = NULL;
7411 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7412 		/* Its no longer sacked, mark it so */
7413 		uint32_t oflags;
7414 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7415 #ifdef BBR_INVARIANTS
7416 		if (rsm->r_in_tmap) {
7417 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7418 			    bbr, rsm, rsm->r_flags);
7419 		}
7420 #endif
7421 		oflags = rsm->r_flags;
7422 		if (rsm->r_flags & BBR_MARKED_LOST) {
7423 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7424 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7425 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7426 				/* LT sampling also needs adjustment */
7427 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7428 		}
7429 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7430 		rsm->r_flags |= BBR_WAS_RENEGED;
7431 		rsm->r_flags |= BBR_RXT_CLEARED;
7432 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7433 		/* Rebuild it into our tmap */
7434 		if (tmap == NULL) {
7435 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7436 			tmap = rsm;
7437 		} else {
7438 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7439 			tmap = rsm;
7440 		}
7441 		tmap->r_in_tmap = 1;
7442 		/*
7443 		 * XXXrrs Delivered? Should we do anything here?
7444 		 *
7445 		 * Of course we don't on a rxt timeout so maybe its ok that
7446 		 * we don't?
7447 		 *
7448 		 * For now lets not.
7449 		 */
7450 		rsm = TAILQ_NEXT(rsm, r_next);
7451 	}
7452 	/*
7453 	 * Now lets possibly clear the sack filter so we start recognizing
7454 	 * sacks that cover this area.
7455 	 */
7456 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7457 }
7458 
7459 static void
7460 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7461 {
7462 	struct tcp_bbr *bbr;
7463 	struct bbr_sendmap *rsm;
7464 	uint32_t cts;
7465 
7466 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7467 	cts = bbr->r_ctl.rc_rcvtime;
7468 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7469 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7470 		if ((rsm->r_end - rsm->r_start) <= 1) {
7471 			/* Log out the SYN completely */
7472 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7473 			rsm->r_rtr_bytes = 0;
7474 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7475 			if (rsm->r_in_tmap) {
7476 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7477 				rsm->r_in_tmap = 0;
7478 			}
7479 			if (bbr->r_ctl.rc_next == rsm) {
7480 				/* scoot along the marker */
7481 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7482 			}
7483 			if (to != NULL)
7484 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7485 			bbr_free(bbr, rsm);
7486 		} else {
7487 			/* There is more (Fast open)? strip out SYN. */
7488 			rsm->r_flags &= ~BBR_HAS_SYN;
7489 			rsm->r_start++;
7490 		}
7491 	}
7492 }
7493 
7494 /*
7495  * Returns the number of bytes that were
7496  * acknowledged by SACK blocks.
7497  */
7498 
7499 static uint32_t
7500 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7501     uint32_t *prev_acked)
7502 {
7503 	uint32_t changed, last_seq, entered_recovery = 0;
7504 	struct tcp_bbr *bbr;
7505 	struct bbr_sendmap *rsm;
7506 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7507 	register uint32_t th_ack;
7508 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7509 	uint32_t cts, acked, ack_point, sack_changed = 0;
7510 	uint32_t p_maxseg, maxseg, p_acked = 0;
7511 
7512 	INP_WLOCK_ASSERT(tp->t_inpcb);
7513 	if (th->th_flags & TH_RST) {
7514 		/* We don't log resets */
7515 		return (0);
7516 	}
7517 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7518 	cts = bbr->r_ctl.rc_rcvtime;
7519 
7520 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7521 	changed = 0;
7522 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7523 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7524 	th_ack = th->th_ack;
7525 	if (SEQ_GT(th_ack, tp->snd_una)) {
7526 		acked = th_ack - tp->snd_una;
7527 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7528 		bbr->rc_tp->t_acktime = ticks;
7529 	} else
7530 		acked = 0;
7531 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7532 		/* Only sent here for sack processing */
7533 		goto proc_sack;
7534 	}
7535 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7536 		changed = th_ack - rsm->r_start;
7537 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7538 		/*
7539 		 * For the SYN incoming case we will not have called
7540 		 * tcp_output for the sending of the SYN, so there will be
7541 		 * no map. All other cases should probably be a panic.
7542 		 */
7543 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7544 			/*
7545 			 * We have a timestamp that can be used to generate
7546 			 * an initial RTT.
7547 			 */
7548 			uint32_t ts, now, rtt;
7549 
7550 			ts = bbr_ts_convert(to->to_tsecr);
7551 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7552 			rtt = now - ts;
7553 			if (rtt < 1)
7554 				rtt = 1;
7555 			bbr_log_type_bbrrttprop(bbr, rtt,
7556 						tp->iss, 0, cts,
7557 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7558 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7559 			changed = 1;
7560 			bbr->r_wanted_output = 1;
7561 			goto out;
7562 		}
7563 		goto proc_sack;
7564 	} else if (rsm == NULL) {
7565 		goto out;
7566 	}
7567 	if (changed) {
7568 		/*
7569 		 * The ACK point is advancing to th_ack, we must drop off
7570 		 * the packets in the rack log and calculate any eligble
7571 		 * RTT's.
7572 		 */
7573 		bbr->r_wanted_output = 1;
7574 more:
7575 		if (rsm == NULL) {
7576 
7577 			if (tp->t_flags & TF_SENTFIN) {
7578 				/* if we send a FIN we will not hav a map */
7579 				goto proc_sack;
7580 			}
7581 #ifdef BBR_INVARIANTS
7582 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7583 			    tp,
7584 			    th, tp->t_state, bbr,
7585 			    tp->snd_una, tp->snd_max, changed);
7586 #endif
7587 			goto proc_sack;
7588 		}
7589 	}
7590 	if (SEQ_LT(th_ack, rsm->r_start)) {
7591 		/* Huh map is missing this */
7592 #ifdef BBR_INVARIANTS
7593 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7594 		    rsm->r_start,
7595 		    th_ack, tp->t_state,
7596 		    bbr->r_state, bbr);
7597 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7598 #endif
7599 		goto proc_sack;
7600 	} else if (th_ack == rsm->r_start) {
7601 		/* None here to ack */
7602 		goto proc_sack;
7603 	}
7604 	/*
7605 	 * Clear the dup ack counter, it will
7606 	 * either be freed or if there is some
7607 	 * remaining we need to start it at zero.
7608 	 */
7609 	rsm->r_dupack = 0;
7610 	/* Now do we consume the whole thing? */
7611 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7612 		/* Its all consumed. */
7613 		uint32_t left;
7614 
7615 		if (rsm->r_flags & BBR_ACKED) {
7616 			/*
7617 			 * It was acked on the scoreboard -- remove it from
7618 			 * total
7619 			 */
7620 			p_acked += (rsm->r_end - rsm->r_start);
7621 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7622 			if (bbr->r_ctl.rc_sacked == 0)
7623 				bbr->r_ctl.rc_sacklast = NULL;
7624 		} else {
7625 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7626 			if (rsm->r_flags & BBR_MARKED_LOST) {
7627 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7628 			}
7629 			if (rsm->r_flags & BBR_SACK_PASSED) {
7630 				/*
7631 				 * There are acked segments ACKED on the
7632 				 * scoreboard further up. We are seeing
7633 				 * reordering.
7634 				 */
7635 				BBR_STAT_INC(bbr_reorder_seen);
7636 				bbr->r_ctl.rc_reorder_ts = cts;
7637 				if (rsm->r_flags & BBR_MARKED_LOST) {
7638 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7639 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7640 						/* LT sampling also needs adjustment */
7641 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7642 				}
7643 			}
7644 			rsm->r_flags &= ~BBR_MARKED_LOST;
7645 		}
7646 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7647 		rsm->r_rtr_bytes = 0;
7648 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7649 		if (rsm->r_in_tmap) {
7650 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7651 			rsm->r_in_tmap = 0;
7652 		}
7653 		if (bbr->r_ctl.rc_next == rsm) {
7654 			/* scoot along the marker */
7655 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7656 		}
7657 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7658 		/* Adjust the packet counts */
7659 		left = th_ack - rsm->r_end;
7660 		/* Free back to zone */
7661 		bbr_free(bbr, rsm);
7662 		if (left) {
7663 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7664 			goto more;
7665 		}
7666 		goto proc_sack;
7667 	}
7668 	if (rsm->r_flags & BBR_ACKED) {
7669 		/*
7670 		 * It was acked on the scoreboard -- remove it from total
7671 		 * for the part being cum-acked.
7672 		 */
7673 		p_acked += (rsm->r_end - rsm->r_start);
7674 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7675 		if (bbr->r_ctl.rc_sacked == 0)
7676 			bbr->r_ctl.rc_sacklast = NULL;
7677 	} else {
7678 		/*
7679 		 * It was acked up to th_ack point for the first time
7680 		 */
7681 		struct bbr_sendmap lrsm;
7682 
7683 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7684 		lrsm.r_end = th_ack;
7685 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7686 	}
7687 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7688 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7689 		/*
7690 		 * It was marked lost and partly ack'd now
7691 		 * for the first time. We lower the rc_lost_bytes
7692 		 * and still leave it MARKED.
7693 		 */
7694 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7695 	}
7696 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7697 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7698 	rsm->r_rtr_bytes = 0;
7699 	/* adjust packet count */
7700 	rsm->r_start = th_ack;
7701 proc_sack:
7702 	/* Check for reneging */
7703 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7704 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7705 		/*
7706 		 * The peer has moved snd_una up to the edge of this send,
7707 		 * i.e. one that it had previously acked. The only way that
7708 		 * can be true if the peer threw away data (space issues)
7709 		 * that it had previously sacked (else it would have given
7710 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7711 		 * markings here.
7712 		 *
7713 		 * Note we have to look to make sure th_ack is our
7714 		 * rsm->r_start in case we get an old ack where th_ack is
7715 		 * behind snd_una.
7716 		 */
7717 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7718 	}
7719 	if ((to->to_flags & TOF_SACK) == 0) {
7720 		/* We are done nothing left to log */
7721 		goto out;
7722 	}
7723 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7724 	if (rsm) {
7725 		last_seq = rsm->r_end;
7726 	} else {
7727 		last_seq = tp->snd_max;
7728 	}
7729 	/* Sack block processing */
7730 	if (SEQ_GT(th_ack, tp->snd_una))
7731 		ack_point = th_ack;
7732 	else
7733 		ack_point = tp->snd_una;
7734 	for (i = 0; i < to->to_nsacks; i++) {
7735 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7736 		    &sack, sizeof(sack));
7737 		sack.start = ntohl(sack.start);
7738 		sack.end = ntohl(sack.end);
7739 		if (SEQ_GT(sack.end, sack.start) &&
7740 		    SEQ_GT(sack.start, ack_point) &&
7741 		    SEQ_LT(sack.start, tp->snd_max) &&
7742 		    SEQ_GT(sack.end, ack_point) &&
7743 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7744 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7745 			    (SEQ_LT(sack.end, last_seq)) &&
7746 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7747 				/*
7748 				 * Not the last piece and its smaller than
7749 				 * 1/8th of a p_maxseg. We ignore this.
7750 				 */
7751 				BBR_STAT_INC(bbr_runt_sacks);
7752 				continue;
7753 			}
7754 			sack_blocks[num_sack_blks] = sack;
7755 			num_sack_blks++;
7756 #ifdef NETFLIX_STATS
7757 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7758 		    SEQ_LEQ(sack.end, th_ack)) {
7759 			/*
7760 			 * Its a D-SACK block.
7761 			 */
7762 			tcp_record_dsack(sack.start, sack.end);
7763 #endif
7764 		}
7765 	}
7766 	if (num_sack_blks == 0)
7767 		goto out;
7768 	/*
7769 	 * Sort the SACK blocks so we can update the rack scoreboard with
7770 	 * just one pass.
7771 	 */
7772 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7773 				  num_sack_blks, th->th_ack);
7774 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7775 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7776 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7777 	num_sack_blks = new_sb;
7778 	if (num_sack_blks < 2) {
7779 		goto do_sack_work;
7780 	}
7781 	/* Sort the sacks */
7782 	for (i = 0; i < num_sack_blks; i++) {
7783 		for (j = i + 1; j < num_sack_blks; j++) {
7784 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7785 				sack = sack_blocks[i];
7786 				sack_blocks[i] = sack_blocks[j];
7787 				sack_blocks[j] = sack;
7788 			}
7789 		}
7790 	}
7791 	/*
7792 	 * Now are any of the sack block ends the same (yes some
7793 	 * implememtations send these)?
7794 	 */
7795 again:
7796 	if (num_sack_blks > 1) {
7797 		for (i = 0; i < num_sack_blks; i++) {
7798 			for (j = i + 1; j < num_sack_blks; j++) {
7799 				if (sack_blocks[i].end == sack_blocks[j].end) {
7800 					/*
7801 					 * Ok these two have the same end we
7802 					 * want the smallest end and then
7803 					 * throw away the larger and start
7804 					 * again.
7805 					 */
7806 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7807 						/*
7808 						 * The second block covers
7809 						 * more area use that
7810 						 */
7811 						sack_blocks[i].start = sack_blocks[j].start;
7812 					}
7813 					/*
7814 					 * Now collapse out the dup-sack and
7815 					 * lower the count
7816 					 */
7817 					for (k = (j + 1); k < num_sack_blks; k++) {
7818 						sack_blocks[j].start = sack_blocks[k].start;
7819 						sack_blocks[j].end = sack_blocks[k].end;
7820 						j++;
7821 					}
7822 					num_sack_blks--;
7823 					goto again;
7824 				}
7825 			}
7826 		}
7827 	}
7828 do_sack_work:
7829 	rsm = bbr->r_ctl.rc_sacklast;
7830 	for (i = 0; i < num_sack_blks; i++) {
7831 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7832 		if (acked) {
7833 			bbr->r_wanted_output = 1;
7834 			changed += acked;
7835 			sack_changed += acked;
7836 		}
7837 	}
7838 out:
7839 	*prev_acked = p_acked;
7840 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7841 		/*
7842 		 * Ok we have a high probability that we need to go in to
7843 		 * recovery since we have data sack'd
7844 		 */
7845 		struct bbr_sendmap *rsm;
7846 
7847 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7848 		if (rsm) {
7849 			/* Enter recovery */
7850 			entered_recovery = 1;
7851 			bbr->r_wanted_output = 1;
7852 			/*
7853 			 * When we enter recovery we need to assure we send
7854 			 * one packet.
7855 			 */
7856 			if (bbr->r_ctl.rc_resend == NULL) {
7857 				bbr->r_ctl.rc_resend = rsm;
7858 			}
7859 		}
7860 	}
7861 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7862 		/*
7863 		 * See if we need to rack-retransmit anything if so set it
7864 		 * up as the thing to resend assuming something else is not
7865 		 * already in that position.
7866 		 */
7867 		if (bbr->r_ctl.rc_resend == NULL) {
7868 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7869 		}
7870 	}
7871 	/*
7872 	 * We return the amount that changed via sack, this is used by the
7873 	 * ack-received code to augment what was changed between th_ack <->
7874 	 * snd_una.
7875 	 */
7876 	return (sack_changed);
7877 }
7878 
7879 static void
7880 bbr_strike_dupack(struct tcp_bbr *bbr)
7881 {
7882 	struct bbr_sendmap *rsm;
7883 
7884 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7885 	if (rsm && (rsm->r_dupack < 0xff)) {
7886 		rsm->r_dupack++;
7887 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7888 			bbr->r_wanted_output = 1;
7889 	}
7890 }
7891 
7892 /*
7893  * Return value of 1, we do not need to call bbr_process_data().
7894  * return value of 0, bbr_process_data can be called.
7895  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7896  * its unlocked and probably unsafe to touch the TCB.
7897  */
7898 static int
7899 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7900     struct tcpcb *tp, struct tcpopt *to,
7901     uint32_t tiwin, int32_t tlen,
7902     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7903 {
7904 	int32_t ourfinisacked = 0;
7905 	int32_t acked_amount;
7906 	uint16_t nsegs;
7907 	int32_t acked;
7908 	uint32_t lost, sack_changed = 0;
7909 	struct mbuf *mfree;
7910 	struct tcp_bbr *bbr;
7911 	uint32_t prev_acked = 0;
7912 
7913 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7914 	lost = bbr->r_ctl.rc_lost;
7915 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7916 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7917 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7918 		bbr->r_wanted_output = 1;
7919 		return (1);
7920 	}
7921 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7922 		/* Process the ack */
7923 		if (bbr->rc_in_persist)
7924 			tp->t_rxtshift = 0;
7925 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7926 		        bbr_strike_dupack(bbr);
7927 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7928 	}
7929 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7930 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7931 		/*
7932 		 * Old ack, behind the last one rcv'd or a duplicate ack
7933 		 * with SACK info.
7934 		 */
7935 		if (th->th_ack == tp->snd_una) {
7936 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7937 			if (bbr->r_state == TCPS_SYN_SENT) {
7938 				/*
7939 				 * Special case on where we sent SYN. When
7940 				 * the SYN-ACK is processed in syn_sent
7941 				 * state it bumps the snd_una. This causes
7942 				 * us to hit here even though we did ack 1
7943 				 * byte.
7944 				 *
7945 				 * Go through the nothing left case so we
7946 				 * send data.
7947 				 */
7948 				goto nothing_left;
7949 			}
7950 		}
7951 		return (0);
7952 	}
7953 	/*
7954 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7955 	 * something we sent.
7956 	 */
7957 	if (tp->t_flags & TF_NEEDSYN) {
7958 		/*
7959 		 * T/TCP: Connection was half-synchronized, and our SYN has
7960 		 * been ACK'd (so connection is now fully synchronized).  Go
7961 		 * to non-starred state, increment snd_una for ACK of SYN,
7962 		 * and check if we can do window scaling.
7963 		 */
7964 		tp->t_flags &= ~TF_NEEDSYN;
7965 		tp->snd_una++;
7966 		/* Do window scaling? */
7967 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7968 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7969 			tp->rcv_scale = tp->request_r_scale;
7970 			/* Send window already scaled. */
7971 		}
7972 	}
7973 	INP_WLOCK_ASSERT(tp->t_inpcb);
7974 
7975 	acked = BYTES_THIS_ACK(tp, th);
7976 	TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7977 	TCPSTAT_ADD(tcps_rcvackbyte, acked);
7978 
7979 	/*
7980 	 * If we just performed our first retransmit, and the ACK arrives
7981 	 * within our recovery window, then it was a mistake to do the
7982 	 * retransmit in the first place.  Recover our original cwnd and
7983 	 * ssthresh, and proceed to transmit where we left off.
7984 	 */
7985 	if (tp->t_flags & TF_PREVVALID) {
7986 		tp->t_flags &= ~TF_PREVVALID;
7987 		if (tp->t_rxtshift == 1 &&
7988 		    (int)(ticks - tp->t_badrxtwin) < 0)
7989 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7990 	}
7991 	SOCKBUF_LOCK(&so->so_snd);
7992 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7993 	tp->snd_wnd -= acked_amount;
7994 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7995 	/* NB: sowwakeup_locked() does an implicit unlock. */
7996 	sowwakeup_locked(so);
7997 	m_freem(mfree);
7998 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7999 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8000 	}
8001 	tp->snd_una = th->th_ack;
8002 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
8003 	if (IN_RECOVERY(tp->t_flags)) {
8004 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
8005 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
8006 			tcp_bbr_partialack(tp);
8007 		} else {
8008 			bbr_post_recovery(tp);
8009 		}
8010 	}
8011 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8012 		tp->snd_recover = tp->snd_una;
8013 	}
8014 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
8015 		tp->snd_nxt = tp->snd_max;
8016 	}
8017 	if (tp->snd_una == tp->snd_max) {
8018 		/* Nothing left outstanding */
8019 nothing_left:
8020 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8021 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8022 			bbr->rc_tp->t_acktime = 0;
8023 		if ((sbused(&so->so_snd) == 0) &&
8024 		    (tp->t_flags & TF_SENTFIN)) {
8025 			ourfinisacked = 1;
8026 		}
8027 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8028 		if (bbr->rc_in_persist == 0) {
8029 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8030 		}
8031 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8032 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8033 		/*
8034 		 * We invalidate the last ack here since we
8035 		 * don't want to transfer forward the time
8036 		 * for our sum's calculations.
8037 		 */
8038 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
8039 		    (sbavail(&so->so_snd) == 0) &&
8040 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
8041 			/*
8042 			 * The socket was gone and the peer sent data, time
8043 			 * to reset him.
8044 			 */
8045 			*ret_val = 1;
8046 			tp = tcp_close(tp);
8047 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
8048 			BBR_STAT_INC(bbr_dropped_af_data);
8049 			return (1);
8050 		}
8051 		/* Set need output so persist might get set */
8052 		bbr->r_wanted_output = 1;
8053 	}
8054 	if (ofia)
8055 		*ofia = ourfinisacked;
8056 	return (0);
8057 }
8058 
8059 static void
8060 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
8061 {
8062 	if (bbr->rc_in_persist == 0) {
8063 		bbr_timer_cancel(bbr, __LINE__, cts);
8064 		bbr->r_ctl.rc_last_delay_val = 0;
8065 		tp->t_rxtshift = 0;
8066 		bbr->rc_in_persist = 1;
8067 		bbr->r_ctl.rc_went_idle_time = cts;
8068 		/* We should be capped when rw went to 0 but just in case */
8069 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
8070 		/* Time freezes for the state, so do the accounting now */
8071 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
8072 			uint32_t time_in;
8073 
8074 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
8075 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
8076 				int32_t idx;
8077 
8078 				idx = bbr_state_val(bbr);
8079 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
8080 			} else {
8081 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
8082 			}
8083 		}
8084 		bbr->r_ctl.rc_bbr_state_time = cts;
8085 	}
8086 }
8087 
8088 static void
8089 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
8090 {
8091 	/*
8092 	 * Note that if idle time does not exceed our
8093 	 * threshold, we do nothing continuing the state
8094 	 * transitions we were last walking through.
8095 	 */
8096 	if (idle_time >= bbr_idle_restart_threshold) {
8097 		if (bbr->rc_use_idle_restart) {
8098 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
8099 			/*
8100 			 * Set our target using BBR_UNIT, so
8101 			 * we increase at a dramatic rate but
8102 			 * we stop when we get the pipe
8103 			 * full again for our current b/w estimate.
8104 			 */
8105 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
8106 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
8107 			bbr_set_state_target(bbr, __LINE__);
8108 			/* Now setup our gains to ramp up */
8109 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
8110 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
8111 			bbr_log_type_statechange(bbr, cts, __LINE__);
8112 		} else {
8113 			bbr_substate_change(bbr, cts, __LINE__, 1);
8114 		}
8115 	}
8116 }
8117 
8118 static void
8119 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
8120 {
8121 	uint32_t idle_time;
8122 
8123 	if (bbr->rc_in_persist == 0)
8124 		return;
8125 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
8126 	bbr->rc_in_persist = 0;
8127 	bbr->rc_hit_state_1 = 0;
8128 	tp->t_flags &= ~TF_FORCEDATA;
8129 	bbr->r_ctl.rc_del_time = cts;
8130 	/*
8131 	 * We invalidate the last ack here since we
8132 	 * don't want to transfer forward the time
8133 	 * for our sum's calculations.
8134 	 */
8135 	if (bbr->rc_inp->inp_in_hpts) {
8136 		tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
8137 		bbr->rc_timer_first = 0;
8138 		bbr->r_ctl.rc_hpts_flags = 0;
8139 		bbr->r_ctl.rc_last_delay_val = 0;
8140 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
8141 		bbr->r_agg_early_set = 0;
8142 		bbr->r_ctl.rc_agg_early = 0;
8143 	}
8144 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
8145 	if (idle_time >= bbr_rtt_probe_time) {
8146 		/*
8147 		 * This qualifies as a RTT_PROBE session since we drop the
8148 		 * data outstanding to nothing and waited more than
8149 		 * bbr_rtt_probe_time.
8150 		 */
8151 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
8152 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
8153 	}
8154 	tp->t_rxtshift = 0;
8155 	/*
8156 	 * If in probeBW and we have persisted more than an RTT lets do
8157 	 * special handling.
8158 	 */
8159 	/* Force a time based epoch */
8160 	bbr_set_epoch(bbr, cts, __LINE__);
8161 	/*
8162 	 * Setup the lost so we don't count anything against the guy
8163 	 * we have been stuck with during persists.
8164 	 */
8165 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
8166 	/* Time un-freezes for the state */
8167 	bbr->r_ctl.rc_bbr_state_time = cts;
8168 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8169 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8170 		/*
8171 		 * If we are going back to probe-bw
8172 		 * or probe_rtt, we may need to possibly
8173 		 * do a fast restart.
8174 		 */
8175 		bbr_restart_after_idle(bbr, cts, idle_time);
8176 	}
8177 }
8178 
8179 static void
8180 bbr_collapsed_window(struct tcp_bbr *bbr)
8181 {
8182 	/*
8183 	 * Now we must walk the
8184 	 * send map and divide the
8185 	 * ones left stranded. These
8186 	 * guys can't cause us to abort
8187 	 * the connection and are really
8188 	 * "unsent". However if a buggy
8189 	 * client actually did keep some
8190 	 * of the data i.e. collapsed the win
8191 	 * and refused to ack and then opened
8192 	 * the win and acked that data. We would
8193 	 * get into an ack war, the simplier
8194 	 * method then of just pretending we
8195 	 * did not send those segments something
8196 	 * won't work.
8197 	 */
8198 	struct bbr_sendmap *rsm, *nrsm;
8199 	tcp_seq max_seq;
8200 	uint32_t maxseg;
8201 	int can_split = 0;
8202 	int fnd = 0;
8203 
8204 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8205 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8206 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8207 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8208 		/* Find the first seq past or at maxseq */
8209 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8210 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8211 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8212 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8213 			fnd = 1;
8214 			break;
8215 		}
8216 	}
8217 	bbr->rc_has_collapsed = 0;
8218 	if (!fnd) {
8219 		/* Nothing to do strange */
8220 		return;
8221 	}
8222 	/*
8223 	 * Now can we split?
8224 	 *
8225 	 * We don't want to split if splitting
8226 	 * would generate too many small segments
8227 	 * less we let an attacker fragment our
8228 	 * send_map and leave us out of memory.
8229 	 */
8230 	if ((max_seq != rsm->r_start) &&
8231 	    (max_seq != rsm->r_end)){
8232 		/* can we split? */
8233 		int res1, res2;
8234 
8235 		res1 = max_seq - rsm->r_start;
8236 		res2 = rsm->r_end - max_seq;
8237 		if ((res1 >= (maxseg/8)) &&
8238 		    (res2 >= (maxseg/8))) {
8239 			/* No small pieces here */
8240 			can_split = 1;
8241 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8242 			/* We are under the limit */
8243 			can_split = 1;
8244 		}
8245 	}
8246 	/* Ok do we need to split this rsm? */
8247 	if (max_seq == rsm->r_start) {
8248 		/* It's this guy no split required */
8249 		nrsm = rsm;
8250 	} else if (max_seq == rsm->r_end) {
8251 		/* It's the next one no split required. */
8252 		nrsm = TAILQ_NEXT(rsm, r_next);
8253 		if (nrsm == NULL) {
8254 			/* Huh? */
8255 			return;
8256 		}
8257 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8258 		/* yep we need to split it */
8259 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8260 		if (nrsm == NULL) {
8261 			/* failed XXXrrs what can we do mark the whole? */
8262 			nrsm = rsm;
8263 			goto no_split;
8264 		}
8265 		/* Clone it */
8266 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8267 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8268 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8269 		if (rsm->r_in_tmap) {
8270 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8271 			nrsm->r_in_tmap = 1;
8272 		}
8273 	} else {
8274 		/*
8275 		 * Split not allowed just start here just
8276 		 * use this guy.
8277 		 */
8278 		nrsm = rsm;
8279 	}
8280 no_split:
8281 	BBR_STAT_INC(bbr_collapsed_win);
8282 	/* reuse fnd as a count */
8283 	fnd = 0;
8284 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8285 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8286 		fnd++;
8287 		bbr->rc_has_collapsed = 1;
8288 	}
8289 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8290 }
8291 
8292 static void
8293 bbr_un_collapse_window(struct tcp_bbr *bbr)
8294 {
8295 	struct bbr_sendmap *rsm;
8296 	int cleared = 0;
8297 
8298 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8299 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8300 			/* Clear the flag */
8301 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8302 			cleared++;
8303 		} else
8304 			break;
8305 	}
8306 	bbr_log_type_rwnd_collapse(bbr,
8307 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8308 	bbr->rc_has_collapsed = 0;
8309 }
8310 
8311 /*
8312  * Return value of 1, the TCB is unlocked and most
8313  * likely gone, return value of 0, the TCB is still
8314  * locked.
8315  */
8316 static int
8317 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8318     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8319     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8320 {
8321 	/*
8322 	 * Update window information. Don't look at window if no ACK: TAC's
8323 	 * send garbage on first SYN.
8324 	 */
8325 	uint16_t nsegs;
8326 	int32_t tfo_syn;
8327 	struct tcp_bbr *bbr;
8328 
8329 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8330 	INP_WLOCK_ASSERT(tp->t_inpcb);
8331 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8332 	if ((thflags & TH_ACK) &&
8333 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8334 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8335 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8336 		/* keep track of pure window updates */
8337 		if (tlen == 0 &&
8338 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8339 			TCPSTAT_INC(tcps_rcvwinupd);
8340 		tp->snd_wnd = tiwin;
8341 		tp->snd_wl1 = th->th_seq;
8342 		tp->snd_wl2 = th->th_ack;
8343 		if (tp->snd_wnd > tp->max_sndwnd)
8344 			tp->max_sndwnd = tp->snd_wnd;
8345 		bbr->r_wanted_output = 1;
8346 	} else if (thflags & TH_ACK) {
8347 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8348 			tp->snd_wnd = tiwin;
8349 			tp->snd_wl1 = th->th_seq;
8350 			tp->snd_wl2 = th->th_ack;
8351 		}
8352 	}
8353 	if (tp->snd_wnd < ctf_outstanding(tp))
8354 		/* The peer collapsed its window on us */
8355 		bbr_collapsed_window(bbr);
8356  	else if (bbr->rc_has_collapsed)
8357 		bbr_un_collapse_window(bbr);
8358 	/* Was persist timer active and now we have window space? */
8359 	if ((bbr->rc_in_persist != 0) &&
8360 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8361 				bbr_minseg(bbr)))) {
8362 		/*
8363 		 * Make the rate persist at end of persist mode if idle long
8364 		 * enough
8365 		 */
8366 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8367 
8368 		/* Make sure we output to start the timer */
8369 		bbr->r_wanted_output = 1;
8370 	}
8371 	/* Do we need to enter persist? */
8372 	if ((bbr->rc_in_persist == 0) &&
8373 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8374 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8375 	    (tp->snd_max == tp->snd_una) &&
8376 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8377 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8378 		/* No send window.. we must enter persist */
8379 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8380 	}
8381 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8382 		m_freem(m);
8383 		return (0);
8384 	}
8385 	/*
8386 	 * Process segments with URG.
8387 	 */
8388 	if ((thflags & TH_URG) && th->th_urp &&
8389 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8390 		/*
8391 		 * This is a kludge, but if we receive and accept random
8392 		 * urgent pointers, we'll crash in soreceive.  It's hard to
8393 		 * imagine someone actually wanting to send this much urgent
8394 		 * data.
8395 		 */
8396 		SOCKBUF_LOCK(&so->so_rcv);
8397 		if (th->th_urp + sbavail(&so->so_rcv) > sb_max) {
8398 			th->th_urp = 0;	/* XXX */
8399 			thflags &= ~TH_URG;	/* XXX */
8400 			SOCKBUF_UNLOCK(&so->so_rcv);	/* XXX */
8401 			goto dodata;	/* XXX */
8402 		}
8403 		/*
8404 		 * If this segment advances the known urgent pointer, then
8405 		 * mark the data stream.  This should not happen in
8406 		 * CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since a
8407 		 * FIN has been received from the remote side. In these
8408 		 * states we ignore the URG.
8409 		 *
8410 		 * According to RFC961 (Assigned Protocols), the urgent
8411 		 * pointer points to the last octet of urgent data.  We
8412 		 * continue, however, to consider it to indicate the first
8413 		 * octet of data past the urgent section as the original
8414 		 * spec states (in one of two places).
8415 		 */
8416 		if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
8417 			tp->rcv_up = th->th_seq + th->th_urp;
8418 			so->so_oobmark = sbavail(&so->so_rcv) +
8419 			    (tp->rcv_up - tp->rcv_nxt) - 1;
8420 			if (so->so_oobmark == 0)
8421 				so->so_rcv.sb_state |= SBS_RCVATMARK;
8422 			sohasoutofband(so);
8423 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
8424 		}
8425 		SOCKBUF_UNLOCK(&so->so_rcv);
8426 		/*
8427 		 * Remove out of band data so doesn't get presented to user.
8428 		 * This can happen independent of advancing the URG pointer,
8429 		 * but if two URG's are pending at once, some out-of-band
8430 		 * data may creep in... ick.
8431 		 */
8432 		if (th->th_urp <= (uint32_t)tlen &&
8433 		    !(so->so_options & SO_OOBINLINE)) {
8434 			/* hdr drop is delayed */
8435 			tcp_pulloutofband(so, th, m, drop_hdrlen);
8436 		}
8437 	} else {
8438 		/*
8439 		 * If no out of band data is expected, pull receive urgent
8440 		 * pointer along with the receive window.
8441 		 */
8442 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
8443 			tp->rcv_up = tp->rcv_nxt;
8444 	}
8445 dodata:				/* XXX */
8446 	INP_WLOCK_ASSERT(tp->t_inpcb);
8447 
8448 	/*
8449 	 * Process the segment text, merging it into the TCP sequencing
8450 	 * queue, and arranging for acknowledgment of receipt if necessary.
8451 	 * This process logically involves adjusting tp->rcv_wnd as data is
8452 	 * presented to the user (this happens in tcp_usrreq.c, case
8453 	 * PRU_RCVD).  If a FIN has already been received on this connection
8454 	 * then we just ignore the text.
8455 	 */
8456 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8457 		   IS_FASTOPEN(tp->t_flags));
8458 	if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
8459 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8460 		tcp_seq save_start = th->th_seq;
8461 		tcp_seq save_rnxt  = tp->rcv_nxt;
8462 		int     save_tlen  = tlen;
8463 
8464 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8465 		/*
8466 		 * Insert segment which includes th into TCP reassembly
8467 		 * queue with control block tp.  Set thflags to whether
8468 		 * reassembly now includes a segment with FIN.  This handles
8469 		 * the common case inline (segment is the next to be
8470 		 * received on an established connection, and the queue is
8471 		 * empty), avoiding linkage into and removal from the queue
8472 		 * and repetition of various conversions. Set DELACK for
8473 		 * segments received in order, but ack immediately when
8474 		 * segments are out of order (so fast retransmit can work).
8475 		 */
8476 		if (th->th_seq == tp->rcv_nxt &&
8477 		    SEGQ_EMPTY(tp) &&
8478 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8479 		    tfo_syn)) {
8480 #ifdef NETFLIX_SB_LIMITS
8481 			u_int mcnt, appended;
8482 
8483 			if (so->so_rcv.sb_shlim) {
8484 				mcnt = m_memcnt(m);
8485 				appended = 0;
8486 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8487 				    CFO_NOSLEEP, NULL) == false) {
8488 					counter_u64_add(tcp_sb_shlim_fails, 1);
8489 					m_freem(m);
8490 					return (0);
8491 				}
8492 			}
8493 #endif
8494 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8495 				bbr->bbr_segs_rcvd += max(1, nsegs);
8496 				tp->t_flags |= TF_DELACK;
8497 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8498 			} else {
8499 				bbr->r_wanted_output = 1;
8500 				tp->t_flags |= TF_ACKNOW;
8501 			}
8502 			tp->rcv_nxt += tlen;
8503 			thflags = th->th_flags & TH_FIN;
8504 			TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8505 			TCPSTAT_ADD(tcps_rcvbyte, tlen);
8506 			SOCKBUF_LOCK(&so->so_rcv);
8507 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8508 				m_freem(m);
8509 			else
8510 #ifdef NETFLIX_SB_LIMITS
8511 				appended =
8512 #endif
8513 					sbappendstream_locked(&so->so_rcv, m, 0);
8514 			/* NB: sorwakeup_locked() does an implicit unlock. */
8515 			sorwakeup_locked(so);
8516 #ifdef NETFLIX_SB_LIMITS
8517 			if (so->so_rcv.sb_shlim && appended != mcnt)
8518 				counter_fo_release(so->so_rcv.sb_shlim,
8519 				    mcnt - appended);
8520 #endif
8521 		} else {
8522 			/*
8523 			 * XXX: Due to the header drop above "th" is
8524 			 * theoretically invalid by now.  Fortunately
8525 			 * m_adj() doesn't actually frees any mbufs when
8526 			 * trimming from the head.
8527 			 */
8528 			tcp_seq temp = save_start;
8529 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8530 			tp->t_flags |= TF_ACKNOW;
8531 		}
8532 		if ((tp->t_flags & TF_SACK_PERMIT) && (save_tlen > 0)) {
8533 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8534 				/*
8535 				 * DSACK actually handled in the fastpath
8536 				 * above.
8537 				 */
8538 				tcp_update_sack_list(tp, save_start,
8539 				    save_start + save_tlen);
8540 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8541 				if ((tp->rcv_numsacks >= 1) &&
8542 				    (tp->sackblks[0].end == save_start)) {
8543 					/*
8544 					 * Partial overlap, recorded at todrop
8545 					 * above.
8546 					 */
8547 					tcp_update_sack_list(tp,
8548 					    tp->sackblks[0].start,
8549 					    tp->sackblks[0].end);
8550 				} else {
8551 					tcp_update_dsack_list(tp, save_start,
8552 					    save_start + save_tlen);
8553 				}
8554 			} else if (tlen >= save_tlen) {
8555 				/* Update of sackblks. */
8556 				tcp_update_dsack_list(tp, save_start,
8557 				    save_start + save_tlen);
8558 			} else if (tlen > 0) {
8559 				tcp_update_dsack_list(tp, save_start,
8560 				    save_start + tlen);
8561 			}
8562 		}
8563 	} else {
8564 		m_freem(m);
8565 		thflags &= ~TH_FIN;
8566 	}
8567 
8568 	/*
8569 	 * If FIN is received ACK the FIN and let the user know that the
8570 	 * connection is closing.
8571 	 */
8572 	if (thflags & TH_FIN) {
8573 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8574 			socantrcvmore(so);
8575 			/*
8576 			 * If connection is half-synchronized (ie NEEDSYN
8577 			 * flag on) then delay ACK, so it may be piggybacked
8578 			 * when SYN is sent. Otherwise, since we received a
8579 			 * FIN then no more input can be expected, send ACK
8580 			 * now.
8581 			 */
8582 			if (tp->t_flags & TF_NEEDSYN) {
8583 				tp->t_flags |= TF_DELACK;
8584 				bbr_timer_cancel(bbr,
8585 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8586 			} else {
8587 				tp->t_flags |= TF_ACKNOW;
8588 			}
8589 			tp->rcv_nxt++;
8590 		}
8591 		switch (tp->t_state) {
8592 
8593 			/*
8594 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8595 			 * CLOSE_WAIT state.
8596 			 */
8597 		case TCPS_SYN_RECEIVED:
8598 			tp->t_starttime = ticks;
8599 			/* FALLTHROUGH */
8600 		case TCPS_ESTABLISHED:
8601 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8602 			break;
8603 
8604 			/*
8605 			 * If still in FIN_WAIT_1 STATE FIN has not been
8606 			 * acked so enter the CLOSING state.
8607 			 */
8608 		case TCPS_FIN_WAIT_1:
8609 			tcp_state_change(tp, TCPS_CLOSING);
8610 			break;
8611 
8612 			/*
8613 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8614 			 * starting the time-wait timer, turning off the
8615 			 * other standard timers.
8616 			 */
8617 		case TCPS_FIN_WAIT_2:
8618 			bbr->rc_timer_first = 1;
8619 			bbr_timer_cancel(bbr,
8620 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8621 			INP_WLOCK_ASSERT(tp->t_inpcb);
8622 			tcp_twstart(tp);
8623 			return (1);
8624 		}
8625 	}
8626 	/*
8627 	 * Return any desired output.
8628 	 */
8629 	if ((tp->t_flags & TF_ACKNOW) ||
8630 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8631 		bbr->r_wanted_output = 1;
8632 	}
8633 	INP_WLOCK_ASSERT(tp->t_inpcb);
8634 	return (0);
8635 }
8636 
8637 /*
8638  * Here nothing is really faster, its just that we
8639  * have broken out the fast-data path also just like
8640  * the fast-ack. Return 1 if we processed the packet
8641  * return 0 if you need to take the "slow-path".
8642  */
8643 static int
8644 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8645     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8646     uint32_t tiwin, int32_t nxt_pkt)
8647 {
8648 	uint16_t nsegs;
8649 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8650 	struct tcp_bbr *bbr;
8651 #ifdef NETFLIX_SB_LIMITS
8652 	u_int mcnt, appended;
8653 #endif
8654 #ifdef TCPDEBUG
8655 	/*
8656 	 * The size of tcp_saveipgen must be the size of the max ip header,
8657 	 * now IPv6.
8658 	 */
8659 	u_char tcp_saveipgen[IP6_HDR_LEN];
8660 	struct tcphdr tcp_savetcp;
8661 	short ostate = 0;
8662 
8663 #endif
8664 	/* On the hpts and we would have called output */
8665 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8666 
8667 	/*
8668 	 * If last ACK falls within this segment's sequence numbers, record
8669 	 * the timestamp. NOTE that the test is modified according to the
8670 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8671 	 */
8672 	if (bbr->r_ctl.rc_resend != NULL) {
8673 		return (0);
8674 	}
8675 	if (tiwin && tiwin != tp->snd_wnd) {
8676 		return (0);
8677 	}
8678 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8679 		return (0);
8680 	}
8681 	if (__predict_false((to->to_flags & TOF_TS) &&
8682 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8683 		return (0);
8684 	}
8685 	if (__predict_false((th->th_ack != tp->snd_una))) {
8686 		return (0);
8687 	}
8688 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8689 		return (0);
8690 	}
8691 	if ((to->to_flags & TOF_TS) != 0 &&
8692 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8693 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8694 		tp->ts_recent = to->to_tsval;
8695 	}
8696 	/*
8697 	 * This is a pure, in-sequence data packet with nothing on the
8698 	 * reassembly queue and we have enough buffer space to take it.
8699 	 */
8700 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8701 #ifdef NETFLIX_SB_LIMITS
8702 	if (so->so_rcv.sb_shlim) {
8703 		mcnt = m_memcnt(m);
8704 		appended = 0;
8705 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8706 		    CFO_NOSLEEP, NULL) == false) {
8707 			counter_u64_add(tcp_sb_shlim_fails, 1);
8708 			m_freem(m);
8709 			return (1);
8710 		}
8711 	}
8712 #endif
8713 	/* Clean receiver SACK report if present */
8714 	if (tp->rcv_numsacks)
8715 		tcp_clean_sackreport(tp);
8716 	TCPSTAT_INC(tcps_preddat);
8717 	tp->rcv_nxt += tlen;
8718 	/*
8719 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8720 	 */
8721 	tp->snd_wl1 = th->th_seq;
8722 	/*
8723 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8724 	 */
8725 	tp->rcv_up = tp->rcv_nxt;
8726 	TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8727 	TCPSTAT_ADD(tcps_rcvbyte, tlen);
8728 #ifdef TCPDEBUG
8729 	if (so->so_options & SO_DEBUG)
8730 		tcp_trace(TA_INPUT, ostate, tp,
8731 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8732 #endif
8733 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8734 
8735 	/* Add data to socket buffer. */
8736 	SOCKBUF_LOCK(&so->so_rcv);
8737 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8738 		m_freem(m);
8739 	} else {
8740 		/*
8741 		 * Set new socket buffer size. Give up when limit is
8742 		 * reached.
8743 		 */
8744 		if (newsize)
8745 			if (!sbreserve_locked(&so->so_rcv,
8746 			    newsize, so, NULL))
8747 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8748 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8749 #ifdef NETFLIX_SB_LIMITS
8750 		appended =
8751 #endif
8752 			sbappendstream_locked(&so->so_rcv, m, 0);
8753 		ctf_calc_rwin(so, tp);
8754 	}
8755 	/* NB: sorwakeup_locked() does an implicit unlock. */
8756 	sorwakeup_locked(so);
8757 #ifdef NETFLIX_SB_LIMITS
8758 	if (so->so_rcv.sb_shlim && mcnt != appended)
8759 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8760 #endif
8761 	if (DELAY_ACK(tp, bbr, nsegs)) {
8762 		bbr->bbr_segs_rcvd += max(1, nsegs);
8763 		tp->t_flags |= TF_DELACK;
8764 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8765 	} else {
8766 		bbr->r_wanted_output = 1;
8767 		tp->t_flags |= TF_ACKNOW;
8768 	}
8769 	return (1);
8770 }
8771 
8772 /*
8773  * This subfunction is used to try to highly optimize the
8774  * fast path. We again allow window updates that are
8775  * in sequence to remain in the fast-path. We also add
8776  * in the __predict's to attempt to help the compiler.
8777  * Note that if we return a 0, then we can *not* process
8778  * it and the caller should push the packet into the
8779  * slow-path. If we return 1, then all is well and
8780  * the packet is fully processed.
8781  */
8782 static int
8783 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8784     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8785     uint32_t tiwin, int32_t nxt_pkt)
8786 {
8787 	int32_t acked;
8788 	uint16_t nsegs;
8789 	uint32_t sack_changed;
8790 #ifdef TCPDEBUG
8791 	/*
8792 	 * The size of tcp_saveipgen must be the size of the max ip header,
8793 	 * now IPv6.
8794 	 */
8795 	u_char tcp_saveipgen[IP6_HDR_LEN];
8796 	struct tcphdr tcp_savetcp;
8797 	short ostate = 0;
8798 
8799 #endif
8800 	uint32_t prev_acked = 0;
8801 	struct tcp_bbr *bbr;
8802 
8803 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8804 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8805 		return (0);
8806 	}
8807 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8808 		/* Above what we have sent? */
8809 		return (0);
8810 	}
8811 	if (__predict_false(tiwin == 0)) {
8812 		/* zero window */
8813 		return (0);
8814 	}
8815 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8816 		/* We need a SYN or a FIN, unlikely.. */
8817 		return (0);
8818 	}
8819 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8820 		/* Timestamp is behind .. old ack with seq wrap? */
8821 		return (0);
8822 	}
8823 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8824 		/* Still recovering */
8825 		return (0);
8826 	}
8827 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8828 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8829 		/* We are retransmitting */
8830 		return (0);
8831 	}
8832 	if (__predict_false(bbr->rc_in_persist != 0)) {
8833 		/* In persist mode */
8834 		return (0);
8835 	}
8836 	if (bbr->r_ctl.rc_sacked) {
8837 		/* We have sack holes on our scoreboard */
8838 		return (0);
8839 	}
8840 	/* Ok if we reach here, we can process a fast-ack */
8841 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8842 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8843 	/*
8844 	 * We never detect loss in fast ack [we can't
8845 	 * have a sack and can't be in recovery so
8846 	 * we always pass 0 (nothing detected)].
8847 	 */
8848 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8849 	/* Did the window get updated? */
8850 	if (tiwin != tp->snd_wnd) {
8851 		tp->snd_wnd = tiwin;
8852 		tp->snd_wl1 = th->th_seq;
8853 		if (tp->snd_wnd > tp->max_sndwnd)
8854 			tp->max_sndwnd = tp->snd_wnd;
8855 	}
8856 	/* Do we need to exit persists? */
8857 	if ((bbr->rc_in_persist != 0) &&
8858 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8859 			       bbr_minseg(bbr)))) {
8860 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8861 		bbr->r_wanted_output = 1;
8862 	}
8863 	/* Do we need to enter persists? */
8864 	if ((bbr->rc_in_persist == 0) &&
8865 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8866 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8867 	    (tp->snd_max == tp->snd_una) &&
8868 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8869 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8870 		/* No send window.. we must enter persist */
8871 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8872 	}
8873 	/*
8874 	 * If last ACK falls within this segment's sequence numbers, record
8875 	 * the timestamp. NOTE that the test is modified according to the
8876 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8877 	 */
8878 	if ((to->to_flags & TOF_TS) != 0 &&
8879 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8880 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8881 		tp->ts_recent = to->to_tsval;
8882 	}
8883 	/*
8884 	 * This is a pure ack for outstanding data.
8885 	 */
8886 	TCPSTAT_INC(tcps_predack);
8887 
8888 	/*
8889 	 * "bad retransmit" recovery.
8890 	 */
8891 	if (tp->t_flags & TF_PREVVALID) {
8892 		tp->t_flags &= ~TF_PREVVALID;
8893 		if (tp->t_rxtshift == 1 &&
8894 		    (int)(ticks - tp->t_badrxtwin) < 0)
8895 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8896 	}
8897 	/*
8898 	 * Recalculate the transmit timer / rtt.
8899 	 *
8900 	 * Some boxes send broken timestamp replies during the SYN+ACK
8901 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8902 	 * and blow up the retransmit timer.
8903 	 */
8904 	acked = BYTES_THIS_ACK(tp, th);
8905 
8906 #ifdef TCP_HHOOK
8907 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8908 	hhook_run_tcp_est_in(tp, th, to);
8909 #endif
8910 
8911 	TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8912 	TCPSTAT_ADD(tcps_rcvackbyte, acked);
8913 	sbdrop(&so->so_snd, acked);
8914 
8915 	if (SEQ_GT(th->th_ack, tp->snd_una))
8916 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8917 	tp->snd_una = th->th_ack;
8918 	if (tp->snd_wnd < ctf_outstanding(tp))
8919 		/* The peer collapsed its window on us */
8920 		bbr_collapsed_window(bbr);
8921 	else if (bbr->rc_has_collapsed)
8922 		bbr_un_collapse_window(bbr);
8923 
8924 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8925 		tp->snd_recover = tp->snd_una;
8926 	}
8927 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8928 	/*
8929 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8930 	 */
8931 	tp->snd_wl2 = th->th_ack;
8932 	m_freem(m);
8933 	/*
8934 	 * If all outstanding data are acked, stop retransmit timer,
8935 	 * otherwise restart timer using current (possibly backed-off)
8936 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8937 	 * If data are ready to send, let tcp_output decide between more
8938 	 * output or persist.
8939 	 */
8940 #ifdef TCPDEBUG
8941 	if (so->so_options & SO_DEBUG)
8942 		tcp_trace(TA_INPUT, ostate, tp,
8943 		    (void *)tcp_saveipgen,
8944 		    &tcp_savetcp, 0);
8945 #endif
8946 	/* Wake up the socket if we have room to write more */
8947 	sowwakeup(so);
8948 	if (tp->snd_una == tp->snd_max) {
8949 		/* Nothing left outstanding */
8950 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8951 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8952 			bbr->rc_tp->t_acktime = 0;
8953 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8954 		if (bbr->rc_in_persist == 0) {
8955 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8956 		}
8957 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8958 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8959 		/*
8960 		 * We invalidate the last ack here since we
8961 		 * don't want to transfer forward the time
8962 		 * for our sum's calculations.
8963 		 */
8964 		bbr->r_wanted_output = 1;
8965 	}
8966 	if (sbavail(&so->so_snd)) {
8967 		bbr->r_wanted_output = 1;
8968 	}
8969 	return (1);
8970 }
8971 
8972 /*
8973  * Return value of 1, the TCB is unlocked and most
8974  * likely gone, return value of 0, the TCB is still
8975  * locked.
8976  */
8977 static int
8978 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8979     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8980     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8981 {
8982 	int32_t todrop;
8983 	int32_t ourfinisacked = 0;
8984 	struct tcp_bbr *bbr;
8985 	int32_t ret_val = 0;
8986 
8987 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8988 	ctf_calc_rwin(so, tp);
8989 	/*
8990 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8991 	 * SYN, drop the input. if seg contains a RST, then drop the
8992 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8993 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8994 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8995 	 * not support ECN so we will not say we are capable. if SYN has
8996 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8997 	 * segment to be acked (eventually) continue processing rest of
8998 	 * data/controls, beginning with URG
8999 	 */
9000 	if ((thflags & TH_ACK) &&
9001 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
9002 	    SEQ_GT(th->th_ack, tp->snd_max))) {
9003 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9004 		return (1);
9005 	}
9006 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
9007 		TCP_PROBE5(connect__refused, NULL, tp,
9008 		    mtod(m, const char *), tp, th);
9009 		tp = tcp_drop(tp, ECONNREFUSED);
9010 		ctf_do_drop(m, tp);
9011 		return (1);
9012 	}
9013 	if (thflags & TH_RST) {
9014 		ctf_do_drop(m, tp);
9015 		return (1);
9016 	}
9017 	if (!(thflags & TH_SYN)) {
9018 		ctf_do_drop(m, tp);
9019 		return (1);
9020 	}
9021 	tp->irs = th->th_seq;
9022 	tcp_rcvseqinit(tp);
9023 	if (thflags & TH_ACK) {
9024 		int tfo_partial = 0;
9025 
9026 		TCPSTAT_INC(tcps_connects);
9027 		soisconnected(so);
9028 #ifdef MAC
9029 		mac_socketpeer_set_from_mbuf(m, so);
9030 #endif
9031 		/* Do window scaling on this connection? */
9032 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9033 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9034 			tp->rcv_scale = tp->request_r_scale;
9035 		}
9036 		tp->rcv_adv += min(tp->rcv_wnd,
9037 		    TCP_MAXWIN << tp->rcv_scale);
9038 		/*
9039 		 * If not all the data that was sent in the TFO SYN
9040 		 * has been acked, resend the remainder right away.
9041 		 */
9042 		if (IS_FASTOPEN(tp->t_flags) &&
9043 		    (tp->snd_una != tp->snd_max)) {
9044 			tp->snd_nxt = th->th_ack;
9045 			tfo_partial = 1;
9046 		}
9047 		/*
9048 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
9049 		 * will be turned on later.
9050 		 */
9051 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && (tfo_partial == 0)) {
9052 			bbr->bbr_segs_rcvd += 1;
9053 			tp->t_flags |= TF_DELACK;
9054 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
9055 		} else {
9056 			bbr->r_wanted_output = 1;
9057 			tp->t_flags |= TF_ACKNOW;
9058 		}
9059 		if (SEQ_GT(th->th_ack, tp->iss)) {
9060 			/*
9061 			 * The SYN is acked
9062 			 * handle it specially.
9063 			 */
9064 			bbr_log_syn(tp, to);
9065 		}
9066 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
9067 			/*
9068 			 * We advance snd_una for the
9069 			 * fast open case. If th_ack is
9070 			 * acknowledging data beyond
9071 			 * snd_una we can't just call
9072 			 * ack-processing since the
9073 			 * data stream in our send-map
9074 			 * will start at snd_una + 1 (one
9075 			 * beyond the SYN). If its just
9076 			 * equal we don't need to do that
9077 			 * and there is no send_map.
9078 			 */
9079 			tp->snd_una++;
9080 		}
9081 		/*
9082 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
9083 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
9084 		 */
9085 		tp->t_starttime = ticks;
9086 		if (tp->t_flags & TF_NEEDFIN) {
9087 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
9088 			tp->t_flags &= ~TF_NEEDFIN;
9089 			thflags &= ~TH_SYN;
9090 		} else {
9091 			tcp_state_change(tp, TCPS_ESTABLISHED);
9092 			TCP_PROBE5(connect__established, NULL, tp,
9093 			    mtod(m, const char *), tp, th);
9094 			cc_conn_init(tp);
9095 		}
9096 	} else {
9097 		/*
9098 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
9099 		 * open.  If segment contains CC option and there is a
9100 		 * cached CC, apply TAO test. If it succeeds, connection is *
9101 		 * half-synchronized. Otherwise, do 3-way handshake:
9102 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
9103 		 * there was no CC option, clear cached CC value.
9104 		 */
9105 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
9106 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
9107 	}
9108 	INP_WLOCK_ASSERT(tp->t_inpcb);
9109 	/*
9110 	 * Advance th->th_seq to correspond to first data byte. If data,
9111 	 * trim to stay within window, dropping FIN if necessary.
9112 	 */
9113 	th->th_seq++;
9114 	if (tlen > tp->rcv_wnd) {
9115 		todrop = tlen - tp->rcv_wnd;
9116 		m_adj(m, -todrop);
9117 		tlen = tp->rcv_wnd;
9118 		thflags &= ~TH_FIN;
9119 		TCPSTAT_INC(tcps_rcvpackafterwin);
9120 		TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
9121 	}
9122 	tp->snd_wl1 = th->th_seq - 1;
9123 	tp->rcv_up = th->th_seq;
9124 	/*
9125 	 * Client side of transaction: already sent SYN and data. If the
9126 	 * remote host used T/TCP to validate the SYN, our data will be
9127 	 * ACK'd; if so, enter normal data segment processing in the middle
9128 	 * of step 5, ack processing. Otherwise, goto step 6.
9129 	 */
9130 	if (thflags & TH_ACK) {
9131 		if ((to->to_flags & TOF_TS) != 0) {
9132 			uint32_t t, rtt;
9133 
9134 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
9135 			if (TSTMP_GEQ(t, to->to_tsecr)) {
9136 				rtt = t - to->to_tsecr;
9137 				if (rtt == 0) {
9138 					rtt = 1;
9139 				}
9140 				rtt *= MS_IN_USEC;
9141 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9142 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
9143 						       rtt, bbr->r_ctl.rc_rcvtime);
9144 			}
9145 		}
9146 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
9147 			return (ret_val);
9148 		/* We may have changed to FIN_WAIT_1 above */
9149 		if (tp->t_state == TCPS_FIN_WAIT_1) {
9150 			/*
9151 			 * In FIN_WAIT_1 STATE in addition to the processing
9152 			 * for the ESTABLISHED state if our FIN is now
9153 			 * acknowledged then enter FIN_WAIT_2.
9154 			 */
9155 			if (ourfinisacked) {
9156 				/*
9157 				 * If we can't receive any more data, then
9158 				 * closing user can proceed. Starting the
9159 				 * timer is contrary to the specification,
9160 				 * but if we don't get a FIN we'll hang
9161 				 * forever.
9162 				 *
9163 				 * XXXjl: we should release the tp also, and
9164 				 * use a compressed state.
9165 				 */
9166 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9167 					soisdisconnected(so);
9168 					tcp_timer_activate(tp, TT_2MSL,
9169 					    (tcp_fast_finwait2_recycle ?
9170 					    tcp_finwait2_timeout :
9171 					    TP_MAXIDLE(tp)));
9172 				}
9173 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
9174 			}
9175 		}
9176 	}
9177 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9178 	    tiwin, thflags, nxt_pkt));
9179 }
9180 
9181 /*
9182  * Return value of 1, the TCB is unlocked and most
9183  * likely gone, return value of 0, the TCB is still
9184  * locked.
9185  */
9186 static int
9187 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
9188 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9189 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9190 {
9191 	int32_t ourfinisacked = 0;
9192 	int32_t ret_val;
9193 	struct tcp_bbr *bbr;
9194 
9195 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9196 	ctf_calc_rwin(so, tp);
9197 	if ((thflags & TH_ACK) &&
9198 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9199 	     SEQ_GT(th->th_ack, tp->snd_max))) {
9200 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9201 		return (1);
9202 	}
9203 	if (IS_FASTOPEN(tp->t_flags)) {
9204 		/*
9205 		 * When a TFO connection is in SYN_RECEIVED, the only valid
9206 		 * packets are the initial SYN, a retransmit/copy of the
9207 		 * initial SYN (possibly with a subset of the original
9208 		 * data), a valid ACK, a FIN, or a RST.
9209 		 */
9210 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9211 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9212 			return (1);
9213 		} else if (thflags & TH_SYN) {
9214 			/* non-initial SYN is ignored */
9215 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9216 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9217 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9218 				ctf_do_drop(m, NULL);
9219 				return (0);
9220 			}
9221 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9222 			ctf_do_drop(m, NULL);
9223 			return (0);
9224 		}
9225 	}
9226 	if ((thflags & TH_RST) ||
9227 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9228 		return (ctf_process_rst(m, th, so, tp));
9229 	/*
9230 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9231 	 * it's less than ts_recent, drop it.
9232 	 */
9233 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9234 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9235 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9236 			return (ret_val);
9237 	}
9238 	/*
9239 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9240 	 * this connection before trimming the data to fit the receive
9241 	 * window.  Check the sequence number versus IRS since we know the
9242 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9243 	 * "LAND" DoS attack.
9244 	 */
9245 	if (SEQ_LT(th->th_seq, tp->irs)) {
9246 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9247 		return (1);
9248 	}
9249 	INP_WLOCK_ASSERT(tp->t_inpcb);
9250 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9251 		return (ret_val);
9252 	}
9253 	/*
9254 	 * If last ACK falls within this segment's sequence numbers, record
9255 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9256 	 * from the latest proposal of the tcplw@cray.com list (Braden
9257 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9258 	 * with our earlier PAWS tests, so this check should be solely
9259 	 * predicated on the sequence space of this segment. 3) That we
9260 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9261 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9262 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9263 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9264 	 * p.869. In such cases, we can still calculate the RTT correctly
9265 	 * when RCV.NXT == Last.ACK.Sent.
9266 	 */
9267 	if ((to->to_flags & TOF_TS) != 0 &&
9268 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9269 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9270 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9271 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9272 		tp->ts_recent = to->to_tsval;
9273 	}
9274 	tp->snd_wnd = tiwin;
9275 	/*
9276 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9277 	 * is on (half-synchronized state), then queue data for later
9278 	 * processing; else drop segment and return.
9279 	 */
9280 	if ((thflags & TH_ACK) == 0) {
9281 		if (IS_FASTOPEN(tp->t_flags)) {
9282 			cc_conn_init(tp);
9283 		}
9284 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9285 					 tiwin, thflags, nxt_pkt));
9286 	}
9287 	TCPSTAT_INC(tcps_connects);
9288 	soisconnected(so);
9289 	/* Do window scaling? */
9290 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9291 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9292 		tp->rcv_scale = tp->request_r_scale;
9293 	}
9294 	/*
9295 	 * ok for the first time in lets see if we can use the ts to figure
9296 	 * out what the initial RTT was.
9297 	 */
9298 	if ((to->to_flags & TOF_TS) != 0) {
9299 		uint32_t t, rtt;
9300 
9301 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9302 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9303 			rtt = t - to->to_tsecr;
9304 			if (rtt == 0) {
9305 				rtt = 1;
9306 			}
9307 			rtt *= MS_IN_USEC;
9308 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9309 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9310 		}
9311 	}
9312 	/* Drop off any SYN in the send map (probably not there)  */
9313 	if (thflags & TH_ACK)
9314 		bbr_log_syn(tp, to);
9315 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9316 
9317 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9318 		tp->t_tfo_pending = NULL;
9319 		/*
9320 		 * Account for the ACK of our SYN prior to regular
9321 		 * ACK processing below.
9322 		 */
9323 		tp->snd_una++;
9324 	}
9325 	/*
9326 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9327 	 * FIN-WAIT-1
9328 	 */
9329 	tp->t_starttime = ticks;
9330 	if (tp->t_flags & TF_NEEDFIN) {
9331 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9332 		tp->t_flags &= ~TF_NEEDFIN;
9333 	} else {
9334 		tcp_state_change(tp, TCPS_ESTABLISHED);
9335 		TCP_PROBE5(accept__established, NULL, tp,
9336 			   mtod(m, const char *), tp, th);
9337 		/*
9338 		 * TFO connections call cc_conn_init() during SYN
9339 		 * processing.  Calling it again here for such connections
9340 		 * is not harmless as it would undo the snd_cwnd reduction
9341 		 * that occurs when a TFO SYN|ACK is retransmitted.
9342 		 */
9343 		if (!IS_FASTOPEN(tp->t_flags))
9344 			cc_conn_init(tp);
9345 	}
9346 	/*
9347 	 * If segment contains data or ACK, will call tcp_reass() later; if
9348 	 * not, do so now to pass queued data to user.
9349 	 */
9350 	if (tlen == 0 && (thflags & TH_FIN) == 0)
9351 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9352 			(struct mbuf *)0);
9353 	tp->snd_wl1 = th->th_seq - 1;
9354 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9355 		return (ret_val);
9356 	}
9357 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9358 		/* We could have went to FIN_WAIT_1 (or EST) above */
9359 		/*
9360 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9361 		 * ESTABLISHED state if our FIN is now acknowledged then
9362 		 * enter FIN_WAIT_2.
9363 		 */
9364 		if (ourfinisacked) {
9365 			/*
9366 			 * If we can't receive any more data, then closing
9367 			 * user can proceed. Starting the timer is contrary
9368 			 * to the specification, but if we don't get a FIN
9369 			 * we'll hang forever.
9370 			 *
9371 			 * XXXjl: we should release the tp also, and use a
9372 			 * compressed state.
9373 			 */
9374 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9375 				soisdisconnected(so);
9376 				tcp_timer_activate(tp, TT_2MSL,
9377 						   (tcp_fast_finwait2_recycle ?
9378 						    tcp_finwait2_timeout :
9379 						    TP_MAXIDLE(tp)));
9380 			}
9381 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9382 		}
9383 	}
9384 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9385 				 tiwin, thflags, nxt_pkt));
9386 }
9387 
9388 /*
9389  * Return value of 1, the TCB is unlocked and most
9390  * likely gone, return value of 0, the TCB is still
9391  * locked.
9392  */
9393 static int
9394 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9395     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9396     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9397 {
9398 	struct tcp_bbr *bbr;
9399 	int32_t ret_val;
9400 
9401 	/*
9402 	 * Header prediction: check for the two common cases of a
9403 	 * uni-directional data xfer.  If the packet has no control flags,
9404 	 * is in-sequence, the window didn't change and we're not
9405 	 * retransmitting, it's a candidate.  If the length is zero and the
9406 	 * ack moved forward, we're the sender side of the xfer.  Just free
9407 	 * the data acked & wake any higher level process that was blocked
9408 	 * waiting for space.  If the length is non-zero and the ack didn't
9409 	 * move, we're the receiver side.  If we're getting packets in-order
9410 	 * (the reassembly queue is empty), add the data toc The socket
9411 	 * buffer and note that we need a delayed ack. Make sure that the
9412 	 * hidden state-flags are also off. Since we check for
9413 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9414 	 */
9415 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9416 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9417 		/*
9418 		 * If we have delived under 4 segments increase the initial
9419 		 * window if raised by the peer. We use this to determine
9420 		 * dynamic and static rwnd's at the end of a connection.
9421 		 */
9422 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9423 	}
9424 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9425 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9426 	    __predict_true(SEGQ_EMPTY(tp)) &&
9427 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9428 		if (tlen == 0) {
9429 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9430 			    tiwin, nxt_pkt)) {
9431 				return (0);
9432 			}
9433 		} else {
9434 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9435 			    tiwin, nxt_pkt)) {
9436 				return (0);
9437 			}
9438 		}
9439 	}
9440 	ctf_calc_rwin(so, tp);
9441 
9442 	if ((thflags & TH_RST) ||
9443 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9444 		return (ctf_process_rst(m, th, so, tp));
9445 	/*
9446 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9447 	 * synchronized state.
9448 	 */
9449 	if (thflags & TH_SYN) {
9450 		ctf_challenge_ack(m, th, tp, &ret_val);
9451 		return (ret_val);
9452 	}
9453 	/*
9454 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9455 	 * it's less than ts_recent, drop it.
9456 	 */
9457 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9458 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9459 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9460 			return (ret_val);
9461 	}
9462 	INP_WLOCK_ASSERT(tp->t_inpcb);
9463 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9464 		return (ret_val);
9465 	}
9466 	/*
9467 	 * If last ACK falls within this segment's sequence numbers, record
9468 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9469 	 * from the latest proposal of the tcplw@cray.com list (Braden
9470 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9471 	 * with our earlier PAWS tests, so this check should be solely
9472 	 * predicated on the sequence space of this segment. 3) That we
9473 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9474 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9475 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9476 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9477 	 * p.869. In such cases, we can still calculate the RTT correctly
9478 	 * when RCV.NXT == Last.ACK.Sent.
9479 	 */
9480 	if ((to->to_flags & TOF_TS) != 0 &&
9481 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9482 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9483 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9484 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9485 		tp->ts_recent = to->to_tsval;
9486 	}
9487 	/*
9488 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9489 	 * is on (half-synchronized state), then queue data for later
9490 	 * processing; else drop segment and return.
9491 	 */
9492 	if ((thflags & TH_ACK) == 0) {
9493 		if (tp->t_flags & TF_NEEDSYN) {
9494 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9495 			    tiwin, thflags, nxt_pkt));
9496 		} else if (tp->t_flags & TF_ACKNOW) {
9497 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9498 			bbr->r_wanted_output = 1;
9499 			return (ret_val);
9500 		} else {
9501 			ctf_do_drop(m, NULL);
9502 			return (0);
9503 		}
9504 	}
9505 	/*
9506 	 * Ack processing.
9507 	 */
9508 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9509 		return (ret_val);
9510 	}
9511 	if (sbavail(&so->so_snd)) {
9512 		if (bbr_progress_timeout_check(bbr)) {
9513 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9514 			return (1);
9515 		}
9516 	}
9517 	/* State changes only happen in bbr_process_data() */
9518 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9519 	    tiwin, thflags, nxt_pkt));
9520 }
9521 
9522 /*
9523  * Return value of 1, the TCB is unlocked and most
9524  * likely gone, return value of 0, the TCB is still
9525  * locked.
9526  */
9527 static int
9528 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9529     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9530     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9531 {
9532 	struct tcp_bbr *bbr;
9533 	int32_t ret_val;
9534 
9535 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9536 	ctf_calc_rwin(so, tp);
9537 	if ((thflags & TH_RST) ||
9538 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9539 		return (ctf_process_rst(m, th, so, tp));
9540 	/*
9541 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9542 	 * synchronized state.
9543 	 */
9544 	if (thflags & TH_SYN) {
9545 		ctf_challenge_ack(m, th, tp, &ret_val);
9546 		return (ret_val);
9547 	}
9548 	/*
9549 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9550 	 * it's less than ts_recent, drop it.
9551 	 */
9552 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9553 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9554 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9555 			return (ret_val);
9556 	}
9557 	INP_WLOCK_ASSERT(tp->t_inpcb);
9558 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9559 		return (ret_val);
9560 	}
9561 	/*
9562 	 * If last ACK falls within this segment's sequence numbers, record
9563 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9564 	 * from the latest proposal of the tcplw@cray.com list (Braden
9565 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9566 	 * with our earlier PAWS tests, so this check should be solely
9567 	 * predicated on the sequence space of this segment. 3) That we
9568 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9569 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9570 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9571 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9572 	 * p.869. In such cases, we can still calculate the RTT correctly
9573 	 * when RCV.NXT == Last.ACK.Sent.
9574 	 */
9575 	if ((to->to_flags & TOF_TS) != 0 &&
9576 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9577 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9578 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9579 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9580 		tp->ts_recent = to->to_tsval;
9581 	}
9582 	/*
9583 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9584 	 * is on (half-synchronized state), then queue data for later
9585 	 * processing; else drop segment and return.
9586 	 */
9587 	if ((thflags & TH_ACK) == 0) {
9588 		if (tp->t_flags & TF_NEEDSYN) {
9589 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9590 			    tiwin, thflags, nxt_pkt));
9591 		} else if (tp->t_flags & TF_ACKNOW) {
9592 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9593 			bbr->r_wanted_output = 1;
9594 			return (ret_val);
9595 		} else {
9596 			ctf_do_drop(m, NULL);
9597 			return (0);
9598 		}
9599 	}
9600 	/*
9601 	 * Ack processing.
9602 	 */
9603 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9604 		return (ret_val);
9605 	}
9606 	if (sbavail(&so->so_snd)) {
9607 		if (bbr_progress_timeout_check(bbr)) {
9608 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9609 			return (1);
9610 		}
9611 	}
9612 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9613 	    tiwin, thflags, nxt_pkt));
9614 }
9615 
9616 static int
9617 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9618     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9619 {
9620 
9621 	if (bbr->rc_allow_data_af_clo == 0) {
9622 close_now:
9623 		tp = tcp_close(tp);
9624 		TCPSTAT_INC(tcps_rcvafterclose);
9625 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9626 		return (1);
9627 	}
9628 	if (sbavail(&so->so_snd) == 0)
9629 		goto close_now;
9630 	/* Ok we allow data that is ignored and a followup reset */
9631 	tp->rcv_nxt = th->th_seq + *tlen;
9632 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9633 	bbr->r_wanted_output = 1;
9634 	*tlen = 0;
9635 	return (0);
9636 }
9637 
9638 /*
9639  * Return value of 1, the TCB is unlocked and most
9640  * likely gone, return value of 0, the TCB is still
9641  * locked.
9642  */
9643 static int
9644 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9645     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9646     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9647 {
9648 	int32_t ourfinisacked = 0;
9649 	int32_t ret_val;
9650 	struct tcp_bbr *bbr;
9651 
9652 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9653 	ctf_calc_rwin(so, tp);
9654 	if ((thflags & TH_RST) ||
9655 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9656 		return (ctf_process_rst(m, th, so, tp));
9657 	/*
9658 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9659 	 * synchronized state.
9660 	 */
9661 	if (thflags & TH_SYN) {
9662 		ctf_challenge_ack(m, th, tp, &ret_val);
9663 		return (ret_val);
9664 	}
9665 	/*
9666 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9667 	 * it's less than ts_recent, drop it.
9668 	 */
9669 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9670 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9671 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9672 			return (ret_val);
9673 	}
9674 	INP_WLOCK_ASSERT(tp->t_inpcb);
9675 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9676 		return (ret_val);
9677 	}
9678 	/*
9679 	 * If new data are received on a connection after the user processes
9680 	 * are gone, then RST the other end.
9681 	 */
9682 	if ((so->so_state & SS_NOFDREF) && tlen) {
9683 		/*
9684 		 * We call a new function now so we might continue and setup
9685 		 * to reset at all data being ack'd.
9686 		 */
9687 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9688 			return (1);
9689 	}
9690 	/*
9691 	 * If last ACK falls within this segment's sequence numbers, record
9692 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9693 	 * from the latest proposal of the tcplw@cray.com list (Braden
9694 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9695 	 * with our earlier PAWS tests, so this check should be solely
9696 	 * predicated on the sequence space of this segment. 3) That we
9697 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9698 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9699 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9700 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9701 	 * p.869. In such cases, we can still calculate the RTT correctly
9702 	 * when RCV.NXT == Last.ACK.Sent.
9703 	 */
9704 	if ((to->to_flags & TOF_TS) != 0 &&
9705 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9706 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9707 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9708 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9709 		tp->ts_recent = to->to_tsval;
9710 	}
9711 	/*
9712 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9713 	 * is on (half-synchronized state), then queue data for later
9714 	 * processing; else drop segment and return.
9715 	 */
9716 	if ((thflags & TH_ACK) == 0) {
9717 		if (tp->t_flags & TF_NEEDSYN) {
9718 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9719 			    tiwin, thflags, nxt_pkt));
9720 		} else if (tp->t_flags & TF_ACKNOW) {
9721 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9722 			bbr->r_wanted_output = 1;
9723 			return (ret_val);
9724 		} else {
9725 			ctf_do_drop(m, NULL);
9726 			return (0);
9727 		}
9728 	}
9729 	/*
9730 	 * Ack processing.
9731 	 */
9732 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9733 		return (ret_val);
9734 	}
9735 	if (ourfinisacked) {
9736 		/*
9737 		 * If we can't receive any more data, then closing user can
9738 		 * proceed. Starting the timer is contrary to the
9739 		 * specification, but if we don't get a FIN we'll hang
9740 		 * forever.
9741 		 *
9742 		 * XXXjl: we should release the tp also, and use a
9743 		 * compressed state.
9744 		 */
9745 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9746 			soisdisconnected(so);
9747 			tcp_timer_activate(tp, TT_2MSL,
9748 			    (tcp_fast_finwait2_recycle ?
9749 			    tcp_finwait2_timeout :
9750 			    TP_MAXIDLE(tp)));
9751 		}
9752 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9753 	}
9754 	if (sbavail(&so->so_snd)) {
9755 		if (bbr_progress_timeout_check(bbr)) {
9756 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9757 			return (1);
9758 		}
9759 	}
9760 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9761 	    tiwin, thflags, nxt_pkt));
9762 }
9763 
9764 /*
9765  * Return value of 1, the TCB is unlocked and most
9766  * likely gone, return value of 0, the TCB is still
9767  * locked.
9768  */
9769 static int
9770 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9771     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9772     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9773 {
9774 	int32_t ourfinisacked = 0;
9775 	int32_t ret_val;
9776 	struct tcp_bbr *bbr;
9777 
9778 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9779 	ctf_calc_rwin(so, tp);
9780 	if ((thflags & TH_RST) ||
9781 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9782 		return (ctf_process_rst(m, th, so, tp));
9783 	/*
9784 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9785 	 * synchronized state.
9786 	 */
9787 	if (thflags & TH_SYN) {
9788 		ctf_challenge_ack(m, th, tp, &ret_val);
9789 		return (ret_val);
9790 	}
9791 	/*
9792 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9793 	 * it's less than ts_recent, drop it.
9794 	 */
9795 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9796 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9797 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9798 			return (ret_val);
9799 	}
9800 	INP_WLOCK_ASSERT(tp->t_inpcb);
9801 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9802 		return (ret_val);
9803 	}
9804 	/*
9805 	 * If new data are received on a connection after the user processes
9806 	 * are gone, then RST the other end.
9807 	 */
9808 	if ((so->so_state & SS_NOFDREF) && tlen) {
9809 		/*
9810 		 * We call a new function now so we might continue and setup
9811 		 * to reset at all data being ack'd.
9812 		 */
9813 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9814 			return (1);
9815 	}
9816 	/*
9817 	 * If last ACK falls within this segment's sequence numbers, record
9818 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9819 	 * from the latest proposal of the tcplw@cray.com list (Braden
9820 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9821 	 * with our earlier PAWS tests, so this check should be solely
9822 	 * predicated on the sequence space of this segment. 3) That we
9823 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9824 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9825 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9826 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9827 	 * p.869. In such cases, we can still calculate the RTT correctly
9828 	 * when RCV.NXT == Last.ACK.Sent.
9829 	 */
9830 	if ((to->to_flags & TOF_TS) != 0 &&
9831 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9832 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9833 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9834 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9835 		tp->ts_recent = to->to_tsval;
9836 	}
9837 	/*
9838 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9839 	 * is on (half-synchronized state), then queue data for later
9840 	 * processing; else drop segment and return.
9841 	 */
9842 	if ((thflags & TH_ACK) == 0) {
9843 		if (tp->t_flags & TF_NEEDSYN) {
9844 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9845 			    tiwin, thflags, nxt_pkt));
9846 		} else if (tp->t_flags & TF_ACKNOW) {
9847 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9848 			bbr->r_wanted_output = 1;
9849 			return (ret_val);
9850 		} else {
9851 			ctf_do_drop(m, NULL);
9852 			return (0);
9853 		}
9854 	}
9855 	/*
9856 	 * Ack processing.
9857 	 */
9858 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9859 		return (ret_val);
9860 	}
9861 	if (ourfinisacked) {
9862 		tcp_twstart(tp);
9863 		m_freem(m);
9864 		return (1);
9865 	}
9866 	if (sbavail(&so->so_snd)) {
9867 		if (bbr_progress_timeout_check(bbr)) {
9868 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9869 			return (1);
9870 		}
9871 	}
9872 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9873 	    tiwin, thflags, nxt_pkt));
9874 }
9875 
9876 /*
9877  * Return value of 1, the TCB is unlocked and most
9878  * likely gone, return value of 0, the TCB is still
9879  * locked.
9880  */
9881 static int
9882 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9883     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9884     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9885 {
9886 	int32_t ourfinisacked = 0;
9887 	int32_t ret_val;
9888 	struct tcp_bbr *bbr;
9889 
9890 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9891 	ctf_calc_rwin(so, tp);
9892 	if ((thflags & TH_RST) ||
9893 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9894 		return (ctf_process_rst(m, th, so, tp));
9895 	/*
9896 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9897 	 * synchronized state.
9898 	 */
9899 	if (thflags & TH_SYN) {
9900 		ctf_challenge_ack(m, th, tp, &ret_val);
9901 		return (ret_val);
9902 	}
9903 	/*
9904 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9905 	 * it's less than ts_recent, drop it.
9906 	 */
9907 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9908 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9909 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9910 			return (ret_val);
9911 	}
9912 	INP_WLOCK_ASSERT(tp->t_inpcb);
9913 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9914 		return (ret_val);
9915 	}
9916 	/*
9917 	 * If new data are received on a connection after the user processes
9918 	 * are gone, then RST the other end.
9919 	 */
9920 	if ((so->so_state & SS_NOFDREF) && tlen) {
9921 		/*
9922 		 * We call a new function now so we might continue and setup
9923 		 * to reset at all data being ack'd.
9924 		 */
9925 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9926 			return (1);
9927 	}
9928 	/*
9929 	 * If last ACK falls within this segment's sequence numbers, record
9930 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9931 	 * from the latest proposal of the tcplw@cray.com list (Braden
9932 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9933 	 * with our earlier PAWS tests, so this check should be solely
9934 	 * predicated on the sequence space of this segment. 3) That we
9935 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9936 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9937 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9938 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9939 	 * p.869. In such cases, we can still calculate the RTT correctly
9940 	 * when RCV.NXT == Last.ACK.Sent.
9941 	 */
9942 	if ((to->to_flags & TOF_TS) != 0 &&
9943 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9944 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9945 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9946 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9947 		tp->ts_recent = to->to_tsval;
9948 	}
9949 	/*
9950 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9951 	 * is on (half-synchronized state), then queue data for later
9952 	 * processing; else drop segment and return.
9953 	 */
9954 	if ((thflags & TH_ACK) == 0) {
9955 		if (tp->t_flags & TF_NEEDSYN) {
9956 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9957 			    tiwin, thflags, nxt_pkt));
9958 		} else if (tp->t_flags & TF_ACKNOW) {
9959 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9960 			bbr->r_wanted_output = 1;
9961 			return (ret_val);
9962 		} else {
9963 			ctf_do_drop(m, NULL);
9964 			return (0);
9965 		}
9966 	}
9967 	/*
9968 	 * case TCPS_LAST_ACK: Ack processing.
9969 	 */
9970 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9971 		return (ret_val);
9972 	}
9973 	if (ourfinisacked) {
9974 		tp = tcp_close(tp);
9975 		ctf_do_drop(m, tp);
9976 		return (1);
9977 	}
9978 	if (sbavail(&so->so_snd)) {
9979 		if (bbr_progress_timeout_check(bbr)) {
9980 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9981 			return (1);
9982 		}
9983 	}
9984 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9985 	    tiwin, thflags, nxt_pkt));
9986 }
9987 
9988 
9989 /*
9990  * Return value of 1, the TCB is unlocked and most
9991  * likely gone, return value of 0, the TCB is still
9992  * locked.
9993  */
9994 static int
9995 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9996     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9997     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
9998 {
9999 	int32_t ourfinisacked = 0;
10000 	int32_t ret_val;
10001 	struct tcp_bbr *bbr;
10002 
10003 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10004 	ctf_calc_rwin(so, tp);
10005 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
10006 	if ((thflags & TH_RST) ||
10007 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
10008 		return (ctf_process_rst(m, th, so, tp));
10009 
10010 	/*
10011 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
10012 	 * synchronized state.
10013 	 */
10014 	if (thflags & TH_SYN) {
10015 		ctf_challenge_ack(m, th, tp, &ret_val);
10016 		return (ret_val);
10017 	}
10018 	INP_WLOCK_ASSERT(tp->t_inpcb);
10019 	/*
10020 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
10021 	 * it's less than ts_recent, drop it.
10022 	 */
10023 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
10024 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
10025 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
10026 			return (ret_val);
10027 	}
10028 	INP_WLOCK_ASSERT(tp->t_inpcb);
10029 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
10030 		return (ret_val);
10031 	}
10032 	/*
10033 	 * If new data are received on a connection after the user processes
10034 	 * are gone, then we may RST the other end depending on the outcome
10035 	 * of bbr_check_data_after_close.
10036 	 */
10037 	if ((so->so_state & SS_NOFDREF) &&
10038 	    tlen) {
10039 		/*
10040 		 * We call a new function now so we might continue and setup
10041 		 * to reset at all data being ack'd.
10042 		 */
10043 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
10044 			return (1);
10045 	}
10046 	INP_WLOCK_ASSERT(tp->t_inpcb);
10047 	/*
10048 	 * If last ACK falls within this segment's sequence numbers, record
10049 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
10050 	 * from the latest proposal of the tcplw@cray.com list (Braden
10051 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
10052 	 * with our earlier PAWS tests, so this check should be solely
10053 	 * predicated on the sequence space of this segment. 3) That we
10054 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
10055 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
10056 	 * SEG.Len, This modified check allows us to overcome RFC1323's
10057 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
10058 	 * p.869. In such cases, we can still calculate the RTT correctly
10059 	 * when RCV.NXT == Last.ACK.Sent.
10060 	 */
10061 	INP_WLOCK_ASSERT(tp->t_inpcb);
10062 	if ((to->to_flags & TOF_TS) != 0 &&
10063 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
10064 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
10065 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
10066 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
10067 		tp->ts_recent = to->to_tsval;
10068 	}
10069 	/*
10070 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
10071 	 * is on (half-synchronized state), then queue data for later
10072 	 * processing; else drop segment and return.
10073 	 */
10074 	if ((thflags & TH_ACK) == 0) {
10075 		if (tp->t_flags & TF_NEEDSYN) {
10076 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
10077 			    tiwin, thflags, nxt_pkt));
10078 		} else if (tp->t_flags & TF_ACKNOW) {
10079 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
10080 			bbr->r_wanted_output = 1;
10081 			return (ret_val);
10082 		} else {
10083 			ctf_do_drop(m, NULL);
10084 			return (0);
10085 		}
10086 	}
10087 	/*
10088 	 * Ack processing.
10089 	 */
10090 	INP_WLOCK_ASSERT(tp->t_inpcb);
10091 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
10092 		return (ret_val);
10093 	}
10094 	if (sbavail(&so->so_snd)) {
10095 		if (bbr_progress_timeout_check(bbr)) {
10096 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
10097 			return (1);
10098 		}
10099 	}
10100 	INP_WLOCK_ASSERT(tp->t_inpcb);
10101 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
10102 	    tiwin, thflags, nxt_pkt));
10103 }
10104 
10105 static void
10106 bbr_stop_all_timers(struct tcpcb *tp)
10107 {
10108 	struct tcp_bbr *bbr;
10109 
10110 	/*
10111 	 * Assure no timers are running.
10112 	 */
10113 	if (tcp_timer_active(tp, TT_PERSIST)) {
10114 		/* We enter in persists, set the flag appropriately */
10115 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10116 		bbr->rc_in_persist = 1;
10117 	}
10118 	tcp_timer_suspend(tp, TT_PERSIST);
10119 	tcp_timer_suspend(tp, TT_REXMT);
10120 	tcp_timer_suspend(tp, TT_KEEP);
10121 	tcp_timer_suspend(tp, TT_DELACK);
10122 }
10123 
10124 static void
10125 bbr_google_mode_on(struct tcp_bbr *bbr)
10126 {
10127 	bbr->rc_use_google = 1;
10128 	bbr->rc_no_pacing = 0;
10129 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10130 	bbr->r_use_policer = bbr_policer_detection_enabled;
10131 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10132 	bbr->bbr_use_rack_cheat = 0;
10133 	bbr->r_ctl.rc_incr_tmrs = 0;
10134 	bbr->r_ctl.rc_inc_tcp_oh = 0;
10135 	bbr->r_ctl.rc_inc_ip_oh = 0;
10136 	bbr->r_ctl.rc_inc_enet_oh = 0;
10137 	reset_time(&bbr->r_ctl.rc_delrate,
10138 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10139 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10140 			 (11 * USECS_IN_SECOND));
10141 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10142 }
10143 
10144 static void
10145 bbr_google_mode_off(struct tcp_bbr *bbr)
10146 {
10147 	bbr->rc_use_google = 0;
10148 	bbr->r_ctl.bbr_google_discount = 0;
10149 	bbr->no_pacing_until = bbr_no_pacing_until;
10150 	bbr->r_use_policer = 0;
10151 	if (bbr->no_pacing_until)
10152 		bbr->rc_no_pacing = 1;
10153 	else
10154 		bbr->rc_no_pacing = 0;
10155 	if (bbr_use_rack_resend_cheat)
10156 		bbr->bbr_use_rack_cheat = 1;
10157 	else
10158 		bbr->bbr_use_rack_cheat = 0;
10159 	if (bbr_incr_timers)
10160 		bbr->r_ctl.rc_incr_tmrs = 1;
10161 	else
10162 		bbr->r_ctl.rc_incr_tmrs = 0;
10163 	if (bbr_include_tcp_oh)
10164 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10165 	else
10166 		bbr->r_ctl.rc_inc_tcp_oh = 0;
10167 	if (bbr_include_ip_oh)
10168 		bbr->r_ctl.rc_inc_ip_oh = 1;
10169 	else
10170 		bbr->r_ctl.rc_inc_ip_oh = 0;
10171 	if (bbr_include_enet_oh)
10172 		bbr->r_ctl.rc_inc_enet_oh = 1;
10173 	else
10174 		bbr->r_ctl.rc_inc_enet_oh = 0;
10175 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10176 	reset_time(&bbr->r_ctl.rc_delrate,
10177 		   bbr_num_pktepo_for_del_limit);
10178 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10179 			 (bbr_filter_len_sec * USECS_IN_SECOND));
10180 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10181 }
10182 /*
10183  * Return 0 on success, non-zero on failure
10184  * which indicates the error (usually no memory).
10185  */
10186 static int
10187 bbr_init(struct tcpcb *tp)
10188 {
10189 	struct tcp_bbr *bbr = NULL;
10190 	struct inpcb *inp;
10191 	uint32_t cts;
10192 
10193 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10194 	if (tp->t_fb_ptr == NULL) {
10195 		/*
10196 		 * We need to allocate memory but cant. The INP and INP_INFO
10197 		 * locks and they are recusive (happens during setup. So a
10198 		 * scheme to drop the locks fails :(
10199 		 *
10200 		 */
10201 		return (ENOMEM);
10202 	}
10203 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10204 	bbr->rtt_valid = 0;
10205 	inp = tp->t_inpcb;
10206 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10207 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10208 	TAILQ_INIT(&bbr->r_ctl.rc_map);
10209 	TAILQ_INIT(&bbr->r_ctl.rc_free);
10210 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10211 	bbr->rc_tp = tp;
10212 	if (tp->t_inpcb) {
10213 		bbr->rc_inp = tp->t_inpcb;
10214 	}
10215 	cts = tcp_get_usecs(&bbr->rc_tv);
10216 	tp->t_acktime = 0;
10217 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10218 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10219 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
10220 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10221 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10222 	bbr->r_ctl.rc_min_to = bbr_min_to;
10223 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
10224 	bbr->r_ctl.bbr_lost_at_state = 0;
10225 	bbr->r_ctl.rc_lost_at_startup = 0;
10226 	bbr->rc_all_timers_stopped = 0;
10227 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10228 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10229 	bbr->r_ctl.rc_pkt_epoch = 0;
10230 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10231 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10232 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10233 	bbr->r_ctl.rc_went_idle_time = cts;
10234 	bbr->rc_pacer_started = cts;
10235 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10236 	bbr->r_ctl.rc_rcvtime = cts;
10237 	bbr->r_ctl.rc_bbr_state_time = cts;
10238 	bbr->r_ctl.rc_del_time = cts;
10239 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10240 	bbr->r_ctl.last_in_probertt = cts;
10241 	bbr->skip_gain = 0;
10242 	bbr->gain_is_limited = 0;
10243 	bbr->no_pacing_until = bbr_no_pacing_until;
10244 	if (bbr->no_pacing_until)
10245 		bbr->rc_no_pacing = 1;
10246 	if (bbr_use_google_algo) {
10247 		bbr->rc_no_pacing = 0;
10248 		bbr->rc_use_google = 1;
10249 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10250 		bbr->r_use_policer = bbr_policer_detection_enabled;
10251 	} else {
10252 		bbr->rc_use_google = 0;
10253 		bbr->r_ctl.bbr_google_discount = 0;
10254 		bbr->r_use_policer = 0;
10255 	}
10256 	if (bbr_ts_limiting)
10257 		bbr->rc_use_ts_limit = 1;
10258 	else
10259 		bbr->rc_use_ts_limit = 0;
10260 	if (bbr_ts_can_raise)
10261 		bbr->ts_can_raise = 1;
10262 	else
10263 		bbr->ts_can_raise = 0;
10264 	if (V_tcp_delack_enabled == 1)
10265 		tp->t_delayed_ack = 2;
10266 	else if (V_tcp_delack_enabled == 0)
10267 		tp->t_delayed_ack = 0;
10268 	else if (V_tcp_delack_enabled < 100)
10269 		tp->t_delayed_ack = V_tcp_delack_enabled;
10270 	else
10271 		tp->t_delayed_ack = 2;
10272 	if (bbr->rc_use_google == 0)
10273 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10274 	else
10275 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10276 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10277 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10278 	bbr->rc_init_win = bbr_def_init_win;
10279 	if (tp->t_flags & TF_REQ_TSTMP)
10280 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10281 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10282 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10283 	bbr->r_init_rtt = 1;
10284 
10285 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10286 	if (bbr_allow_hdwr_pacing)
10287 		bbr->bbr_hdw_pace_ena = 1;
10288 	else
10289 		bbr->bbr_hdw_pace_ena = 0;
10290 	if (bbr_sends_full_iwnd)
10291 		bbr->bbr_init_win_cheat = 1;
10292 	else
10293 		bbr->bbr_init_win_cheat = 0;
10294 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10295 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10296 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10297 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10298 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10299 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10300 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10301 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10302 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10303 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10304 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10305 	bbr->r_ctl.rc_rtt_shrinks = cts;
10306 	if (bbr->rc_use_google) {
10307 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10308 				  FILTER_TYPE_MAX,
10309 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10310 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10311 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10312 	} else {
10313 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10314 				  FILTER_TYPE_MAX,
10315 				  bbr_num_pktepo_for_del_limit);
10316 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10317 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10318 	}
10319 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10320 	if (bbr_uses_idle_restart)
10321 		bbr->rc_use_idle_restart = 1;
10322 	else
10323 		bbr->rc_use_idle_restart = 0;
10324 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10325 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10326 	if (bbr_resends_use_tso)
10327 		bbr->rc_resends_use_tso = 1;
10328 #ifdef NETFLIX_PEAKRATE
10329 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10330 #endif
10331 	if (tp->snd_una != tp->snd_max) {
10332 		/* Create a send map for the current outstanding data */
10333 		struct bbr_sendmap *rsm;
10334 
10335 		rsm = bbr_alloc(bbr);
10336 		if (rsm == NULL) {
10337 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10338 			tp->t_fb_ptr = NULL;
10339 			return (ENOMEM);
10340 		}
10341 		rsm->r_flags = BBR_OVERMAX;
10342 		rsm->r_tim_lastsent[0] = cts;
10343 		rsm->r_rtr_cnt = 1;
10344 		rsm->r_rtr_bytes = 0;
10345 		rsm->r_start = tp->snd_una;
10346 		rsm->r_end = tp->snd_max;
10347 		rsm->r_dupack = 0;
10348 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10349 		rsm->r_ts_valid = 0;
10350 		rsm->r_del_ack_ts = tp->ts_recent;
10351 		rsm->r_del_time = cts;
10352 		if (bbr->r_ctl.r_app_limited_until)
10353 			rsm->r_app_limited = 1;
10354 		else
10355 			rsm->r_app_limited = 0;
10356 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10357 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10358 		rsm->r_in_tmap = 1;
10359 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10360 			rsm->r_bbr_state = bbr_state_val(bbr);
10361 		else
10362 			rsm->r_bbr_state = 8;
10363 	}
10364 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10365 		bbr->bbr_use_rack_cheat = 1;
10366 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10367 		bbr->r_ctl.rc_incr_tmrs = 1;
10368 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10369 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10370 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10371 		bbr->r_ctl.rc_inc_ip_oh = 1;
10372 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10373 		bbr->r_ctl.rc_inc_enet_oh = 1;
10374 
10375 	bbr_log_type_statechange(bbr, cts, __LINE__);
10376 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10377 	    (tp->t_srtt)) {
10378 		uint32_t rtt;
10379 
10380 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10381 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10382 	}
10383 	/* announce the settings and state */
10384 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10385 	tcp_bbr_tso_size_check(bbr, cts);
10386 	/*
10387 	 * Now call the generic function to start a timer. This will place
10388 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10389 	 * flags.
10390 	 */
10391 	bbr_stop_all_timers(tp);
10392 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10393 	return (0);
10394 }
10395 
10396 /*
10397  * Return 0 if we can accept the connection. Return
10398  * non-zero if we can't handle the connection. A EAGAIN
10399  * means you need to wait until the connection is up.
10400  * a EADDRNOTAVAIL means we can never handle the connection
10401  * (no SACK).
10402  */
10403 static int
10404 bbr_handoff_ok(struct tcpcb *tp)
10405 {
10406 	if ((tp->t_state == TCPS_CLOSED) ||
10407 	    (tp->t_state == TCPS_LISTEN)) {
10408 		/* Sure no problem though it may not stick */
10409 		return (0);
10410 	}
10411 	if ((tp->t_state == TCPS_SYN_SENT) ||
10412 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10413 		/*
10414 		 * We really don't know you have to get to ESTAB or beyond
10415 		 * to tell.
10416 		 */
10417 		return (EAGAIN);
10418 	}
10419 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10420 		return (0);
10421 	}
10422 	/*
10423 	 * If we reach here we don't do SACK on this connection so we can
10424 	 * never do rack.
10425 	 */
10426 	return (EINVAL);
10427 }
10428 
10429 static void
10430 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10431 {
10432 	if (tp->t_fb_ptr) {
10433 		uint32_t calc;
10434 		struct tcp_bbr *bbr;
10435 		struct bbr_sendmap *rsm;
10436 
10437 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10438 		if (bbr->r_ctl.crte)
10439 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10440 		bbr_log_flowend(bbr);
10441 		bbr->rc_tp = NULL;
10442 		if (tp->t_inpcb) {
10443 			/* Backout any flags2 we applied */
10444 			tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10445 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10446 			tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10447 		}
10448 		if (bbr->bbr_hdrw_pacing)
10449 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10450 		else
10451 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10452 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10453 		while (rsm) {
10454 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10455 			uma_zfree(bbr_zone, rsm);
10456 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10457 		}
10458 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10459 		while (rsm) {
10460 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10461 			uma_zfree(bbr_zone, rsm);
10462 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10463 		}
10464 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10465 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10466 			BBR_STAT_INC(bbr_dynamic_rwnd);
10467 		else
10468 			BBR_STAT_INC(bbr_static_rwnd);
10469 		bbr->r_ctl.rc_free_cnt = 0;
10470 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10471 		tp->t_fb_ptr = NULL;
10472 	}
10473 	/* Make sure snd_nxt is correctly set */
10474 	tp->snd_nxt = tp->snd_max;
10475 }
10476 
10477 static void
10478 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10479 {
10480 	switch (tp->t_state) {
10481 	case TCPS_SYN_SENT:
10482 		bbr->r_state = TCPS_SYN_SENT;
10483 		bbr->r_substate = bbr_do_syn_sent;
10484 		break;
10485 	case TCPS_SYN_RECEIVED:
10486 		bbr->r_state = TCPS_SYN_RECEIVED;
10487 		bbr->r_substate = bbr_do_syn_recv;
10488 		break;
10489 	case TCPS_ESTABLISHED:
10490 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10491 		bbr->r_state = TCPS_ESTABLISHED;
10492 		bbr->r_substate = bbr_do_established;
10493 		break;
10494 	case TCPS_CLOSE_WAIT:
10495 		bbr->r_state = TCPS_CLOSE_WAIT;
10496 		bbr->r_substate = bbr_do_close_wait;
10497 		break;
10498 	case TCPS_FIN_WAIT_1:
10499 		bbr->r_state = TCPS_FIN_WAIT_1;
10500 		bbr->r_substate = bbr_do_fin_wait_1;
10501 		break;
10502 	case TCPS_CLOSING:
10503 		bbr->r_state = TCPS_CLOSING;
10504 		bbr->r_substate = bbr_do_closing;
10505 		break;
10506 	case TCPS_LAST_ACK:
10507 		bbr->r_state = TCPS_LAST_ACK;
10508 		bbr->r_substate = bbr_do_lastack;
10509 		break;
10510 	case TCPS_FIN_WAIT_2:
10511 		bbr->r_state = TCPS_FIN_WAIT_2;
10512 		bbr->r_substate = bbr_do_fin_wait_2;
10513 		break;
10514 	case TCPS_LISTEN:
10515 	case TCPS_CLOSED:
10516 	case TCPS_TIME_WAIT:
10517 	default:
10518 		break;
10519 	};
10520 }
10521 
10522 static void
10523 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10524 {
10525 	/*
10526 	 * Now what state are we going into now? Is there adjustments
10527 	 * needed?
10528 	 */
10529 	int32_t old_state, old_gain;
10530 
10531 
10532 	old_state = bbr_state_val(bbr);
10533 	old_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
10534 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10535 		/* Save the lowest srtt we saw in our end of the sub-state */
10536 		bbr->rc_hit_state_1 = 0;
10537 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10538 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10539 	}
10540 	bbr->rc_bbr_substate++;
10541 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10542 		/* Cycle back to first state-> gain */
10543 		bbr->rc_bbr_substate = 0;
10544 	}
10545 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10546 		/*
10547 		 * We enter the gain(5/4) cycle (possibly less if
10548 		 * shallow buffer detection is enabled)
10549 		 */
10550 		if (bbr->skip_gain) {
10551 			/*
10552 			 * Hardware pacing has set our rate to
10553 			 * the max and limited our b/w just
10554 			 * do level i.e. no gain.
10555 			 */
10556 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10557 		} else if (bbr->gain_is_limited &&
10558 			   bbr->bbr_hdrw_pacing &&
10559 			   bbr->r_ctl.crte) {
10560 			/*
10561 			 * We can't gain above the hardware pacing
10562 			 * rate which is less than our rate + the gain
10563 			 * calculate the gain needed to reach the hardware
10564 			 * pacing rate..
10565 			 */
10566 			uint64_t bw, rate, gain_calc;
10567 
10568 			bw = bbr_get_bw(bbr);
10569 			rate = bbr->r_ctl.crte->rate;
10570 			if ((rate > bw) &&
10571 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10572 				gain_calc = (rate * BBR_UNIT) / bw;
10573 				if (gain_calc < BBR_UNIT)
10574 					gain_calc = BBR_UNIT;
10575 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10576 			} else {
10577 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10578 			}
10579 		} else
10580 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10581 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10582 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10583 		} else
10584 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10585 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10586 		bbr->rc_hit_state_1 = 1;
10587 		bbr->r_ctl.rc_exta_time_gd = 0;
10588 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10589 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10590 		if (bbr_state_drain_2_tar) {
10591 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10592 		} else
10593 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10594 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10595 	} else {
10596 		/* All other cycles hit here 2-7 */
10597 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10598 			if (bbr_sub_drain_slam_cwnd &&
10599 			    (bbr->rc_use_google == 0) &&
10600 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10601 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10602 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10603 			}
10604 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10605 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10606 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10607 			else
10608 				bbr->r_ctl.rc_exta_time_gd = 0;
10609 			if (bbr->r_ctl.rc_exta_time_gd) {
10610 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10611 				/* Now chop up the time for each state (div by 7) */
10612 				bbr->r_ctl.rc_level_state_extra /= 7;
10613 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10614 					/* Add a randomization */
10615 					bbr_randomize_extra_state_time(bbr);
10616 				}
10617 			}
10618 		}
10619 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10620 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10621 	}
10622 	if (bbr->rc_use_google) {
10623 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10624 	}
10625 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10626 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10627 	if (dolog)
10628 		bbr_log_type_statechange(bbr, cts, line);
10629 
10630 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10631 		uint32_t time_in;
10632 
10633 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10634 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10635 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10636 		} else {
10637 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10638 		}
10639 	}
10640 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10641 	bbr_set_state_target(bbr, __LINE__);
10642 	if (bbr_sub_drain_slam_cwnd &&
10643 	    (bbr->rc_use_google == 0) &&
10644 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10645 		/* Slam down the cwnd */
10646 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10647 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10648 		if (bbr_sub_drain_app_limit) {
10649 			/* Go app limited if we are on a long drain */
10650 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10651 							  ctf_flight_size(bbr->rc_tp,
10652 							      (bbr->r_ctl.rc_sacked +
10653 							       bbr->r_ctl.rc_lost_bytes)));
10654 		}
10655 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10656 	}
10657 	if (bbr->rc_lt_use_bw) {
10658 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10659 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10660 	}
10661 	/* Google changes TSO size every cycle */
10662 	if (bbr->rc_use_google)
10663 		tcp_bbr_tso_size_check(bbr, cts);
10664 	bbr->r_ctl.gain_epoch = cts;
10665 	bbr->r_ctl.rc_bbr_state_time = cts;
10666 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10667 }
10668 
10669 static void
10670 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10671 {
10672 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10673 	    (google_allow_early_out == 1) &&
10674 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10675 		/* We have reached out target flight size possibly early */
10676 		goto change_state;
10677 	}
10678 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10679 		return;
10680 	}
10681 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10682 		/*
10683 		 * Must be a rttProp movement forward before
10684 		 * we can change states.
10685 		 */
10686 		return;
10687 	}
10688 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10689 		/*
10690 		 * The needed time has passed but for
10691 		 * the gain cycle extra rules apply:
10692 		 * 1) If we have seen loss, we exit
10693 		 * 2) If we have not reached the target
10694 		 *    we stay in GAIN (gain-to-target).
10695 		 */
10696 		if (google_consider_lost && losses)
10697 			goto change_state;
10698 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10699 			return;
10700 		}
10701 	}
10702 change_state:
10703 	/* For gain we must reach our target, all others last 1 rttProp */
10704 	bbr_substate_change(bbr, cts, __LINE__, 1);
10705 }
10706 
10707 static void
10708 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10709 {
10710 	uint32_t flight, bbr_cur_cycle_time;
10711 
10712 	if (bbr->rc_use_google) {
10713 		bbr_set_probebw_google_gains(bbr, cts, losses);
10714 		return;
10715 	}
10716 	if (cts == 0) {
10717 		/*
10718 		 * Never alow cts to be 0 we
10719 		 * do this so we can judge if
10720 		 * we have set a timestamp.
10721 		 */
10722 		cts = 1;
10723 	}
10724 	if (bbr_state_is_pkt_epoch)
10725 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10726 	else
10727 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10728 
10729 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10730 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10731 			flight = ctf_flight_size(bbr->rc_tp,
10732 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10733 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10734 				/* Keep it slam down */
10735 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10736 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10737 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10738 				}
10739 				if (bbr_sub_drain_app_limit) {
10740 					/* Go app limited if we are on a long drain */
10741 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10742 				}
10743 			}
10744 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10745 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10746 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10747 				/*
10748 				 * Still here after the same time as
10749 				 * the gain. We need to drain harder
10750 				 * for the next srtt. Reduce by a set amount
10751 				 * the gain drop is capped at DRAIN states
10752 				 * value (88).
10753 				 */
10754 				bbr->r_ctl.flightsize_at_drain = flight;
10755 				if (bbr_drain_drop_mul &&
10756 				    bbr_drain_drop_div &&
10757 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10758 					/* Use your specific drop value (def 4/5 = 20%) */
10759 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10760 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10761 				} else {
10762 					/* You get drop of 20% */
10763 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10764 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10765 				}
10766 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10767 					/* Reduce our gain again to the bottom  */
10768 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10769 				}
10770 				bbr_log_exit_gain(bbr, cts, 4);
10771 				/*
10772 				 * Extend out so we wait another
10773 				 * epoch before dropping again.
10774 				 */
10775 				bbr->r_ctl.gain_epoch = cts;
10776 			}
10777 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10778 				if (bbr_sub_drain_slam_cwnd &&
10779 				    (bbr->rc_use_google == 0) &&
10780 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10781 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10782 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10783 				}
10784 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10785 				bbr_log_exit_gain(bbr, cts, 3);
10786 			}
10787 		} else {
10788 			/* Its a gain  */
10789 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10790 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10791 				goto change_state;
10792 			}
10793 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10794 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10795 			     bbr->rc_tp->snd_wnd)) {
10796 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10797 				bbr_log_exit_gain(bbr, cts, 2);
10798 			}
10799 		}
10800 		/**
10801 		 * We fall through and return always one of two things has
10802 		 * occured.
10803 		 * 1) We are still not at target
10804 		 *    <or>
10805 		 * 2) We reached the target and set rc_bbr_state_atflight
10806 		 *    which means we no longer hit this block
10807 		 *    next time we are called.
10808 		 */
10809 		return;
10810 	}
10811 change_state:
10812 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10813 		return;
10814 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10815 		/* Less than a full time-period has passed */
10816 		return;
10817 	}
10818 	if (bbr->r_ctl.rc_level_state_extra &&
10819 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10820 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10821 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10822 		/* Less than a full time-period + extra has passed */
10823 		return;
10824 	}
10825 	if (bbr_gain_gets_extra_too &&
10826 	    bbr->r_ctl.rc_level_state_extra &&
10827 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10828 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10829 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10830 		/* Less than a full time-period + extra has passed */
10831 		return;
10832 	}
10833 	bbr_substate_change(bbr, cts, __LINE__, 1);
10834 }
10835 
10836 static uint32_t
10837 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10838 {
10839 	uint32_t mss, tar;
10840 
10841 	if (bbr->rc_use_google) {
10842 		/* Google just uses the cwnd target */
10843 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10844 	} else {
10845 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10846 			  bbr->r_ctl.rc_pace_max_segs);
10847 		/* Get the base cwnd with gain rounded to a mss */
10848 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10849 						      gain), mss);
10850 		/* Make sure it is within our min */
10851 		if (tar < get_min_cwnd(bbr))
10852 			return (get_min_cwnd(bbr));
10853 	}
10854 	return (tar);
10855 }
10856 
10857 static void
10858 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10859 {
10860 	uint32_t tar, meth;
10861 
10862 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10863 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10864 		/* Special case using old probe-rtt method */
10865 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10866 		meth = 1;
10867 	} else {
10868 		/* Non-probe-rtt case and reduced probe-rtt  */
10869 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10870 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10871 			/* For gain cycle we use the hptsi gain */
10872 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10873 			meth = 2;
10874 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10875 			/*
10876 			 * If configured, or for google all other states
10877 			 * get BBR_UNIT.
10878 			 */
10879 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10880 			meth = 3;
10881 		} else {
10882 			/*
10883 			 * Or we set a target based on the pacing gain
10884 			 * for non-google mode and default (non-configured).
10885 			 * Note we don't set a target goal below drain (192).
10886 			 */
10887 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10888 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10889 				meth = 4;
10890 			} else {
10891 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10892 				meth = 5;
10893 			}
10894 		}
10895 	}
10896 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10897 	bbr->r_ctl.rc_target_at_state = tar;
10898 }
10899 
10900 static void
10901 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10902 {
10903 	/* Change to probe_rtt */
10904 	uint32_t time_in;
10905 
10906 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10907 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10908 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10909 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10910 					  + bbr->r_ctl.rc_delivered);
10911 	/* Setup so we force feed the filter */
10912 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10913 		bbr->rc_prtt_set_ts = 1;
10914 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10915 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10916 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10917 	}
10918 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10919 	bbr->r_ctl.rc_rtt_shrinks = cts;
10920 	bbr->r_ctl.last_in_probertt = cts;
10921 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10922 	bbr->r_ctl.rc_bbr_state_time = cts;
10923 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10924 	/* We need to force the filter to update */
10925 
10926 	if ((bbr_sub_drain_slam_cwnd) &&
10927 	    bbr->rc_hit_state_1 &&
10928 	    (bbr->rc_use_google == 0) &&
10929 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10930 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10931 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10932 	} else
10933 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10934 	/* Update the lost */
10935 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10936 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10937 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10938 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10939 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10940 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10941 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10942 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10943 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10944 	} else {
10945 		/*
10946 		 * We bring it down slowly by using a hptsi gain that is
10947 		 * probably 75%. This will slowly float down our outstanding
10948 		 * without tampering with the cwnd.
10949 		 */
10950 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10951 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10952 		bbr_set_state_target(bbr, __LINE__);
10953 		if (bbr_prtt_slam_cwnd &&
10954 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10955 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10956 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10957 		}
10958 	}
10959 	if (ctf_flight_size(bbr->rc_tp,
10960 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10961 	    bbr->r_ctl.rc_target_at_state) {
10962 		/* We are at target */
10963 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10964 	} else {
10965 		/* We need to come down to reach target before our time begins */
10966 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10967 	}
10968 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10969 	BBR_STAT_INC(bbr_enter_probertt);
10970 	bbr_log_exit_gain(bbr, cts, 0);
10971 	bbr_log_type_statechange(bbr, cts, line);
10972 }
10973 
10974 static void
10975 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10976 {
10977 	/*
10978 	 * Sanity check on probe-rtt intervals.
10979 	 * In crazy situations where we are competing
10980 	 * against new-reno flows with huge buffers
10981 	 * our rtt-prop interval could come to dominate
10982 	 * things if we can't get through a full set
10983 	 * of cycles, we need to adjust it.
10984 	 */
10985 	if (bbr_can_adjust_probertt &&
10986 	    (bbr->rc_use_google == 0)) {
10987 		uint16_t val = 0;
10988 		uint32_t cur_rttp, fval, newval, baseval;
10989 
10990 		/* Are we to small and go into probe-rtt to often? */
10991 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10992 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10993 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10994 		if (bbr_is_ratio == 0) {
10995 			if (fval > bbr_rtt_probe_limit)
10996 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10997 			else
10998 				newval = cur_rttp;
10999 		} else {
11000 			int mul;
11001 
11002 			mul = fval / bbr_rtt_probe_limit;
11003 			newval = cur_rttp * mul;
11004 		}
11005 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
11006 			bbr->r_ctl.rc_probertt_int = cur_rttp;
11007 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
11008 			val = 1;
11009 		} else {
11010 			/*
11011 			 * No adjustments were made
11012 			 * do we need to shrink it?
11013 			 */
11014 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
11015 				if (cur_rttp <= bbr_rtt_probe_limit) {
11016 					/*
11017 					 * Things have calmed down lets
11018 					 * shrink all the way to default
11019 					 */
11020 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
11021 					reset_time_small(&bbr->r_ctl.rc_rttprop,
11022 							 (bbr_filter_len_sec * USECS_IN_SECOND));
11023 					cur_rttp = bbr_rtt_probe_limit;
11024 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
11025 					val = 2;
11026 				} else {
11027 					/*
11028 					 * Well does some adjustment make sense?
11029 					 */
11030 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
11031 						/* We can reduce interval time some */
11032 						bbr->r_ctl.rc_probertt_int = cur_rttp;
11033 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
11034 						val = 3;
11035 					}
11036 				}
11037 			}
11038 		}
11039 		if (val)
11040 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
11041 	}
11042 }
11043 
11044 static void
11045 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
11046 {
11047 	/* Exit probe-rtt */
11048 
11049 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
11050 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11051 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11052 	}
11053 	bbr_log_exit_gain(bbr, cts, 1);
11054 	bbr->rc_hit_state_1 = 0;
11055 	bbr->r_ctl.rc_rtt_shrinks = cts;
11056 	bbr->r_ctl.last_in_probertt = cts;
11057 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
11058 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11059 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
11060 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11061 					  bbr->r_ctl.rc_delivered);
11062 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11063 		uint32_t time_in;
11064 
11065 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11066 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11067 	}
11068 	if (bbr->rc_filled_pipe) {
11069 		/* Switch to probe_bw */
11070 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11071 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11072 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
11073 		bbr_substate_change(bbr, cts, __LINE__, 0);
11074 		bbr_log_type_statechange(bbr, cts, __LINE__);
11075 	} else {
11076 		/* Back to startup */
11077 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
11078 		bbr->r_ctl.rc_bbr_state_time = cts;
11079 		/*
11080 		 * We don't want to give a complete free 3
11081 		 * measurements until we exit, so we use
11082 		 * the number of pe's we were in probe-rtt
11083 		 * to add to the startup_epoch. That way
11084 		 * we will still retain the old state.
11085 		 */
11086 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
11087 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11088 		/* Make sure to use the lower pg when shifting back in */
11089 		if (bbr->r_ctl.rc_lost &&
11090 		    bbr_use_lower_gain_in_startup &&
11091 		    (bbr->rc_use_google == 0))
11092 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11093 		else
11094 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
11095 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
11096 		/* Probably not needed but set it anyway */
11097 		bbr_set_state_target(bbr, __LINE__);
11098 		bbr_log_type_statechange(bbr, cts, __LINE__);
11099 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11100 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
11101 	}
11102 	bbr_check_probe_rtt_limits(bbr, cts);
11103 }
11104 
11105 static int32_t inline
11106 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
11107 {
11108 	if ((bbr->rc_past_init_win == 1) &&
11109 	    (bbr->rc_in_persist == 0) &&
11110 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
11111 		return (1);
11112 	}
11113 	if (bbr_can_force_probertt &&
11114 	    (bbr->rc_in_persist == 0) &&
11115 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
11116 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
11117 		return (1);
11118 	}
11119 	return (0);
11120 }
11121 
11122 
11123 static int32_t
11124 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
11125 {
11126 	uint64_t btlbw, gain;
11127 	if (pkt_epoch == 0) {
11128 		/*
11129 		 * Need to be on a pkt-epoch to continue.
11130 		 */
11131 		return (0);
11132 	}
11133 	btlbw = bbr_get_full_bw(bbr);
11134 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11135 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11136 	if (btlbw >= gain) {
11137 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11138 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11139 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11140 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11141 	}
11142 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
11143 		return (1);
11144 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11145 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11146 	return(0);
11147 }
11148 
11149 static int32_t inline
11150 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
11151 {
11152 	/* Have we gained 25% in the last 3 packet based epoch's? */
11153 	uint64_t btlbw, gain;
11154 	int do_exit;
11155 	int delta, rtt_gain;
11156 
11157 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11158 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11159 		/*
11160 		 * This qualifies as a RTT_PROBE session since we drop the
11161 		 * data outstanding to nothing and waited more than
11162 		 * bbr_rtt_probe_time.
11163 		 */
11164 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11165 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
11166 	}
11167 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
11168 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
11169 		return (0);
11170 	}
11171 	if (bbr->rc_use_google)
11172 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
11173 
11174 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11175 	    (bbr_use_lower_gain_in_startup)) {
11176 		/* Drop to a lower gain 1.5 x since we saw loss */
11177 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11178 	}
11179 	if (pkt_epoch == 0) {
11180 		/*
11181 		 * Need to be on a pkt-epoch to continue.
11182 		 */
11183 		return (0);
11184 	}
11185 	if (bbr_rtt_gain_thresh) {
11186 		/*
11187 		 * Do we allow a flow to stay
11188 		 * in startup with no loss and no
11189 		 * gain in rtt over a set threshold?
11190 		 */
11191 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11192 		    bbr->r_ctl.startup_last_srtt &&
11193 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11194 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11195 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11196 		} else
11197 			rtt_gain = 0;
11198 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11199 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11200 			/* First time or new lower value */
11201 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11202 
11203 		if ((bbr->r_ctl.rc_lost == 0) &&
11204 		    (rtt_gain < bbr_rtt_gain_thresh)) {
11205 			/*
11206 			 * No loss, and we are under
11207 			 * our gain threhold for
11208 			 * increasing RTT.
11209 			 */
11210 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11211 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
11212 			bbr_log_startup_event(bbr, cts, rtt_gain,
11213 					      delta, bbr->r_ctl.startup_last_srtt, 10);
11214 			return (0);
11215 		}
11216 	}
11217 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11218 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11219 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11220 		/*
11221 		 * We only assess if we have a new measurment when
11222 		 * we have no loss and are not in recovery.
11223 		 * Drag up by one our last_startup epoch so we will hold
11224 		 * the number of non-gain we have already accumulated.
11225 		 */
11226 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11227 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11228 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11229 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11230 		return (0);
11231 	}
11232 	/* Case where we reduced the lost (bad retransmit) */
11233 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11234 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11235 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11236 	btlbw = bbr_get_full_bw(bbr);
11237 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11238 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11239 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11240 	else
11241 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11242 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11243 	do_exit = 0;
11244 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11245 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11246 	if (btlbw >= gain) {
11247 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11248 		/* Update the lost so we won't exit in next set of tests */
11249 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11250 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11251 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11252 	}
11253 	if ((bbr->rc_loss_exit &&
11254 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11255 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11256 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11257 		/*
11258 		 * If we had no gain,  we had loss and that loss was above
11259 		 * our threshould, the rwnd is not constrained, and we have
11260 		 * had at least 3 packet epochs exit. Note that this is
11261 		 * switched off by sysctl. Google does not do this by the
11262 		 * way.
11263 		 */
11264 		if ((ctf_flight_size(bbr->rc_tp,
11265 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11266 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11267 			do_exit = 1;
11268 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11269 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11270 		} else {
11271 			/* Just record an updated loss value */
11272 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11273 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11274 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11275 		}
11276 	} else
11277 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11278 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11279 	    do_exit) {
11280 		/* Return 1 to exit the startup state. */
11281 		return (1);
11282 	}
11283 	/* Stay in startup */
11284 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11285 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11286 	return (0);
11287 }
11288 
11289 static void
11290 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11291 {
11292 	/*
11293 	 * A tick occured in the rtt epoch do we need to do anything?
11294 	 */
11295 #ifdef BBR_INVARIANTS
11296 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11297 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11298 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11299 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11300 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11301 		/* Debug code? */
11302 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11303 	}
11304 #endif
11305 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11306 		/* Do we exit the startup state? */
11307 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11308 			uint32_t time_in;
11309 
11310 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11311 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11312 			bbr->rc_filled_pipe = 1;
11313 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11314 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11315 
11316 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11317 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11318 			} else
11319 				time_in = 0;
11320 			if (bbr->rc_no_pacing)
11321 				bbr->rc_no_pacing = 0;
11322 			bbr->r_ctl.rc_bbr_state_time = cts;
11323 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11324 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11325 			bbr_set_state_target(bbr, __LINE__);
11326 			if ((bbr->rc_use_google == 0) &&
11327 			    bbr_slam_cwnd_in_main_drain) {
11328 				/* Here we don't have to worry about probe-rtt */
11329 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11330 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11331 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11332 			}
11333 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11334 			bbr_log_type_statechange(bbr, cts, __LINE__);
11335 			if (ctf_flight_size(bbr->rc_tp,
11336 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11337 			    bbr->r_ctl.rc_target_at_state) {
11338 				/*
11339 				 * Switch to probe_bw if we are already
11340 				 * there
11341 				 */
11342 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11343 				bbr_substate_change(bbr, cts, __LINE__, 0);
11344 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11345 				bbr_log_type_statechange(bbr, cts, __LINE__);
11346 			}
11347 		}
11348 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11349 		uint32_t inflight;
11350 		struct tcpcb *tp;
11351 
11352 		tp = bbr->rc_tp;
11353 		inflight = ctf_flight_size(tp,
11354 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11355 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11356 			/* We have reached a flight of the cwnd target */
11357 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11358 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11359 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11360 			bbr_set_state_target(bbr, __LINE__);
11361 			/*
11362 			 * Rig it so we don't do anything crazy and
11363 			 * start fresh with a new randomization.
11364 			 */
11365 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11366 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11367 			bbr_substate_change(bbr, cts, __LINE__, 1);
11368 		}
11369 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11370 		/* Has in-flight reached the bdp (or less)? */
11371 		uint32_t inflight;
11372 		struct tcpcb *tp;
11373 
11374 		tp = bbr->rc_tp;
11375 		inflight = ctf_flight_size(tp,
11376 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11377 		if ((bbr->rc_use_google == 0) &&
11378 		    bbr_slam_cwnd_in_main_drain &&
11379 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11380 			/*
11381 			 * Here we don't have to worry about probe-rtt
11382 			 * re-slam it, but keep it slammed down.
11383 			 */
11384 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11385 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11386 		}
11387 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11388 			/* We have drained */
11389 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11390 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11391 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11392 				uint32_t time_in;
11393 
11394 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11395 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11396 			}
11397 			if ((bbr->rc_use_google == 0) &&
11398 			    bbr_slam_cwnd_in_main_drain &&
11399 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11400 				/* Restore the cwnd */
11401 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11402 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11403 			}
11404 			/* Setup probe-rtt has being done now RRS-HERE */
11405 			bbr->r_ctl.rc_rtt_shrinks = cts;
11406 			bbr->r_ctl.last_in_probertt = cts;
11407 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11408 			/* Randomly pick a sub-state */
11409 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11410 			bbr_substate_change(bbr, cts, __LINE__, 0);
11411 			bbr_log_type_statechange(bbr, cts, __LINE__);
11412 		}
11413 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11414 		uint32_t flight;
11415 
11416 		flight = ctf_flight_size(bbr->rc_tp,
11417 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11418 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11419 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11420 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11421 			/*
11422 			 * We must keep cwnd at the desired MSS.
11423 			 */
11424 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11425 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11426 		} else if ((bbr_prtt_slam_cwnd) &&
11427 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11428 			/* Re-slam it */
11429 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11430 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11431 		}
11432 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11433 			/* Has outstanding reached our target? */
11434 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11435 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11436 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11437 				/* If time is exactly 0, be 1usec off */
11438 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11439 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11440 				if (bbr->rc_use_google == 0) {
11441 					/*
11442 					 * Restore any lowering that as occured to
11443 					 * reach here
11444 					 */
11445 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11446 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11447 					else
11448 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11449 				}
11450 			}
11451 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11452 			    (bbr->rc_use_google == 0) &&
11453 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11454 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11455 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11456 				/*
11457 				 * We have doddled with our current hptsi
11458 				 * gain an srtt and have still not made it
11459 				 * to target, or we have increased our flight.
11460 				 * Lets reduce the gain by xx%
11461 				 * flooring the reduce at DRAIN (based on
11462 				 * mul/div)
11463 				 */
11464 				int red;
11465 
11466 				bbr->r_ctl.flightsize_at_drain = flight;
11467 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11468 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11469 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11470 					/* Reduce our gain again */
11471 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11472 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11473 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11474 					/* one more chance before we give up */
11475 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11476 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11477 				} else {
11478 					/* At the very bottom */
11479 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11480 				}
11481 			}
11482 		}
11483 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11484 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11485 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11486 			/* Time to exit probe RTT normally */
11487 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11488 		}
11489 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11490 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11491 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11492 			/*
11493 			 * This qualifies as a RTT_PROBE session since we
11494 			 * drop the data outstanding to nothing and waited
11495 			 * more than bbr_rtt_probe_time.
11496 			 */
11497 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11498 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11499 		}
11500 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11501 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11502 		} else {
11503 			bbr_set_probebw_gains(bbr, cts, losses);
11504 		}
11505 	}
11506 }
11507 
11508 static void
11509 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11510 {
11511 	int32_t epoch = 0;
11512 
11513 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11514 		bbr_set_epoch(bbr, cts, line);
11515 		/* At each epoch doe lt bw sampling */
11516 		epoch = 1;
11517 	}
11518 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11519 }
11520 
11521 static int
11522 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11523     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11524     int32_t nxt_pkt, struct timeval *tv)
11525 {
11526 	int32_t thflags, retval;
11527 	uint32_t cts, lcts;
11528 	uint32_t tiwin;
11529 	struct tcpopt to;
11530 	struct tcp_bbr *bbr;
11531 	struct bbr_sendmap *rsm;
11532 	struct timeval ltv;
11533 	int32_t did_out = 0;
11534 	int32_t in_recovery;
11535 	uint16_t nsegs;
11536 	int32_t prev_state;
11537 	uint32_t lost;
11538 
11539 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11540 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11541 	/* add in our stats */
11542 	kern_prefetch(bbr, &prev_state);
11543 	prev_state = 0;
11544 	thflags = th->th_flags;
11545 	/*
11546 	 * If this is either a state-changing packet or current state isn't
11547 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11548 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11549 	 * caller may have unnecessarily acquired a write lock due to a
11550 	 * race.
11551 	 */
11552 	INP_WLOCK_ASSERT(tp->t_inpcb);
11553 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11554 	    __func__));
11555 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11556 	    __func__));
11557 
11558 	tp->t_rcvtime = ticks;
11559 	/*
11560 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11561 	 * the scale is zero.
11562 	 */
11563 	tiwin = th->th_win << tp->snd_scale;
11564 #ifdef NETFLIX_STATS
11565 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11566 #endif
11567 	/*
11568 	 * Parse options on any incoming segment.
11569 	 */
11570 	tcp_dooptions(&to, (u_char *)(th + 1),
11571 	    (th->th_off << 2) - sizeof(struct tcphdr),
11572 	    (thflags & TH_SYN) ? TO_SYN : 0);
11573 
11574 	if (m->m_flags & M_TSTMP) {
11575 		/* Prefer the hardware timestamp if present */
11576 		struct timespec ts;
11577 
11578 		mbuf_tstmp2timespec(m, &ts);
11579 		bbr->rc_tv.tv_sec = ts.tv_sec;
11580 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11581 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11582 	} else if (m->m_flags & M_TSTMP_LRO) {
11583 		/* Next the arrival timestamp */
11584 		struct timespec ts;
11585 
11586 		mbuf_tstmp2timespec(m, &ts);
11587 		bbr->rc_tv.tv_sec = ts.tv_sec;
11588 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11589 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11590 	} else {
11591 		/*
11592 		 * Ok just get the current time.
11593 		 */
11594 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11595 	}
11596 	/*
11597 	 * If echoed timestamp is later than the current time, fall back to
11598 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11599 	 * were used when this connection was established.
11600 	 */
11601 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11602 		to.to_tsecr -= tp->ts_offset;
11603 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11604 			to.to_tsecr = 0;
11605 	}
11606 	/*
11607 	 * If its the first time in we need to take care of options and
11608 	 * verify we can do SACK for rack!
11609 	 */
11610 	if (bbr->r_state == 0) {
11611 		/*
11612 		 * Process options only when we get SYN/ACK back. The SYN
11613 		 * case for incoming connections is handled in tcp_syncache.
11614 		 * According to RFC1323 the window field in a SYN (i.e., a
11615 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11616 		 * this is traditional behavior, may need to be cleaned up.
11617 		 */
11618 		if (bbr->rc_inp == NULL) {
11619 			bbr->rc_inp = tp->t_inpcb;
11620 		}
11621 		/*
11622 		 * We need to init rc_inp here since its not init'd when
11623 		 * bbr_init is called
11624 		 */
11625 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11626 			if ((to.to_flags & TOF_SCALE) &&
11627 			    (tp->t_flags & TF_REQ_SCALE)) {
11628 				tp->t_flags |= TF_RCVD_SCALE;
11629 				tp->snd_scale = to.to_wscale;
11630 			}
11631 			/*
11632 			 * Initial send window.  It will be updated with the
11633 			 * next incoming segment to the scaled value.
11634 			 */
11635 			tp->snd_wnd = th->th_win;
11636 			if (to.to_flags & TOF_TS) {
11637 				tp->t_flags |= TF_RCVD_TSTMP;
11638 				tp->ts_recent = to.to_tsval;
11639 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11640 			}
11641 			if (to.to_flags & TOF_MSS)
11642 				tcp_mss(tp, to.to_mss);
11643 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11644 			    (to.to_flags & TOF_SACKPERM) == 0)
11645 				tp->t_flags &= ~TF_SACK_PERMIT;
11646 			if (IS_FASTOPEN(tp->t_flags)) {
11647 				if (to.to_flags & TOF_FASTOPEN) {
11648 					uint16_t mss;
11649 
11650 					if (to.to_flags & TOF_MSS)
11651 						mss = to.to_mss;
11652 					else
11653 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11654 							mss = TCP6_MSS;
11655 						else
11656 							mss = TCP_MSS;
11657 					tcp_fastopen_update_cache(tp, mss,
11658 					    to.to_tfo_len, to.to_tfo_cookie);
11659 				} else
11660 					tcp_fastopen_disable_path(tp);
11661 			}
11662 		}
11663 		/*
11664 		 * At this point we are at the initial call. Here we decide
11665 		 * if we are doing RACK or not. We do this by seeing if
11666 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11667 		 * we switch to the default code.
11668 		 */
11669 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11670 			/* Bail */
11671 			tcp_switch_back_to_default(tp);
11672 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11673 			    tlen, iptos);
11674 			return (1);
11675 		}
11676 		/* Set the flag */
11677 		bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11678 		tcp_set_hpts(tp->t_inpcb);
11679 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11680 	}
11681 	if (thflags & TH_ACK) {
11682 		/* Track ack types */
11683 		if (to.to_flags & TOF_SACK)
11684 			BBR_STAT_INC(bbr_acks_with_sacks);
11685 		else
11686 			BBR_STAT_INC(bbr_plain_acks);
11687 	}
11688 	/*
11689 	 * This is the one exception case where we set the rack state
11690 	 * always. All other times (timers etc) we must have a rack-state
11691 	 * set (so we assure we have done the checks above for SACK).
11692 	 */
11693 	if (bbr->r_state != tp->t_state)
11694 		bbr_set_state(tp, bbr, tiwin);
11695 
11696 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11697 		kern_prefetch(rsm, &prev_state);
11698 	prev_state = bbr->r_state;
11699 	bbr->rc_ack_was_delayed = 0;
11700 	lost = bbr->r_ctl.rc_lost;
11701 	bbr->rc_is_pkt_epoch_now = 0;
11702 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11703 		/* Get the real time into lcts and figure the real delay */
11704 		lcts = tcp_get_usecs(&ltv);
11705 		if (TSTMP_GT(lcts, cts)) {
11706 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11707 			bbr->rc_ack_was_delayed = 1;
11708 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11709 				     bbr->r_ctl.highest_hdwr_delay))
11710 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11711 		} else {
11712 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11713 			bbr->rc_ack_was_delayed = 0;
11714 		}
11715 	} else {
11716 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11717 		bbr->rc_ack_was_delayed = 0;
11718 	}
11719 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11720 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11721 		retval = 0;
11722 		m_freem(m);
11723                 goto done_with_input;
11724         }
11725         /*
11726          * If a segment with the ACK-bit set arrives in the SYN-SENT state
11727          * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11728          */
11729         if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11730             (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11731 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11732                 return (1);
11733         }
11734 	in_recovery = IN_RECOVERY(tp->t_flags);
11735 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11736 		bbr->r_ctl.rc_high_rwnd = tiwin;
11737 #ifdef BBR_INVARIANTS
11738 	if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11739 	    (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11740 		panic("tp:%p bbr:%p given a dropped inp:%p",
11741 		    tp, bbr, tp->t_inpcb);
11742 	}
11743 #endif
11744 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11745 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11746 	bbr->rtt_valid = 0;
11747 	if (to.to_flags & TOF_TS) {
11748 		bbr->rc_ts_valid = 1;
11749 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11750 	} else {
11751 		bbr->rc_ts_valid = 0;
11752 		bbr->r_ctl.last_inbound_ts = 0;
11753 	}
11754 	retval = (*bbr->r_substate) (m, th, so,
11755 	    tp, &to, drop_hdrlen,
11756 	    tlen, tiwin, thflags, nxt_pkt);
11757 #ifdef BBR_INVARIANTS
11758 	if ((retval == 0) &&
11759 	    (tp->t_inpcb == NULL)) {
11760 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11761 		    retval, tp, prev_state);
11762 	}
11763 #endif
11764 	if (nxt_pkt == 0)
11765 		BBR_STAT_INC(bbr_rlock_left_ret0);
11766 	else
11767 		BBR_STAT_INC(bbr_rlock_left_ret1);
11768 	if (retval == 0) {
11769 		/*
11770 		 * If retval is 1 the tcb is unlocked and most likely the tp
11771 		 * is gone.
11772 		 */
11773 		INP_WLOCK_ASSERT(tp->t_inpcb);
11774 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11775 		if (bbr->rc_is_pkt_epoch_now)
11776 			bbr_set_pktepoch(bbr, cts, __LINE__);
11777 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11778 		if (nxt_pkt == 0) {
11779 			if (bbr->r_wanted_output != 0) {
11780 				bbr->rc_output_starts_timer = 0;
11781 				did_out = 1;
11782 				(void)tp->t_fb->tfb_tcp_output(tp);
11783 			} else
11784 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11785 		}
11786 		if ((nxt_pkt == 0) &&
11787 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11788 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11789 		     (tp->t_flags & TF_DELACK) ||
11790 		     ((tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11791 		      (tp->t_state <= TCPS_CLOSING)))) {
11792 			/*
11793 			 * We could not send (probably in the hpts but
11794 			 * stopped the timer)?
11795 			 */
11796 			if ((tp->snd_max == tp->snd_una) &&
11797 			    ((tp->t_flags & TF_DELACK) == 0) &&
11798 			    (bbr->rc_inp->inp_in_hpts) &&
11799 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11800 				/*
11801 				 * keep alive not needed if we are hptsi
11802 				 * output yet
11803 				 */
11804 				;
11805 			} else {
11806 				if (bbr->rc_inp->inp_in_hpts) {
11807 					tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
11808 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11809 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11810 						uint32_t del;
11811 
11812 						del = lcts - bbr->rc_pacer_started;
11813 						if (bbr->r_ctl.rc_last_delay_val > del) {
11814 							BBR_STAT_INC(bbr_force_timer_start);
11815 							bbr->r_ctl.rc_last_delay_val -= del;
11816 							bbr->rc_pacer_started = lcts;
11817 						} else {
11818 							/* We are late */
11819 							bbr->r_ctl.rc_last_delay_val = 0;
11820 							BBR_STAT_INC(bbr_force_output);
11821 							(void)tp->t_fb->tfb_tcp_output(tp);
11822 						}
11823 					}
11824 				}
11825 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11826 				    0);
11827 			}
11828 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11829 			/* Do we have the correct timer running? */
11830 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11831 		}
11832 		/* Do we have a new state */
11833 		if (bbr->r_state != tp->t_state)
11834 			bbr_set_state(tp, bbr, tiwin);
11835 done_with_input:
11836 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11837 		if (did_out)
11838 			bbr->r_wanted_output = 0;
11839 #ifdef BBR_INVARIANTS
11840 		if (tp->t_inpcb == NULL) {
11841 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11842 			    did_out,
11843 			    retval, tp, prev_state);
11844 		}
11845 #endif
11846 	}
11847 	return (retval);
11848 }
11849 
11850 static void
11851 bbr_log_type_hrdwtso(struct tcpcb *tp, struct tcp_bbr *bbr, int len, int mod, int what_we_can_send)
11852 {
11853 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
11854 		union tcp_log_stackspecific log;
11855 		struct timeval tv;
11856 		uint32_t cts;
11857 
11858 		cts = tcp_get_usecs(&tv);
11859 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
11860 		log.u_bbr.flex1 = bbr->r_ctl.rc_pace_min_segs;
11861 		log.u_bbr.flex2 = what_we_can_send;
11862 		log.u_bbr.flex3 = bbr->r_ctl.rc_pace_max_segs;
11863 		log.u_bbr.flex4 = len;
11864 		log.u_bbr.flex5 = 0;
11865 		log.u_bbr.flex7 = mod;
11866 		log.u_bbr.flex8 = 1;
11867 		TCP_LOG_EVENTP(tp, NULL,
11868 		    &tp->t_inpcb->inp_socket->so_rcv,
11869 		    &tp->t_inpcb->inp_socket->so_snd,
11870 		    TCP_HDWR_TLS, 0,
11871 		    0, &log, false, &tv);
11872 	}
11873 }
11874 
11875 static void
11876 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11877     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11878 {
11879 	struct timeval tv;
11880 	int retval;
11881 
11882 	/* First lets see if we have old packets */
11883 	if (tp->t_in_pkt) {
11884 		if (ctf_do_queued_segments(so, tp, 1)) {
11885 			m_freem(m);
11886 			return;
11887 		}
11888 	}
11889 	if (m->m_flags & M_TSTMP_LRO) {
11890 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11891 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11892 	} else {
11893 		/* Should not be should we kassert instead? */
11894 		tcp_get_usecs(&tv);
11895 	}
11896 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11897 					 drop_hdrlen, tlen, iptos, 0, &tv);
11898 	if (retval == 0)
11899 		INP_WUNLOCK(tp->t_inpcb);
11900 }
11901 
11902 /*
11903  * Return how much data can be sent without violating the
11904  * cwnd or rwnd.
11905  */
11906 
11907 static inline uint32_t
11908 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11909     uint32_t avail, int32_t sb_offset, uint32_t cts)
11910 {
11911 	uint32_t len;
11912 
11913 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11914 		/* We never want to go over our peers rcv-window */
11915 		len = 0;
11916 	} else {
11917 		uint32_t flight;
11918 
11919 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11920 		if (flight >= sendwin) {
11921 			/*
11922 			 * We have in flight what we are allowed by cwnd (if
11923 			 * it was rwnd blocking it would have hit above out
11924 			 * >= tp->snd_wnd).
11925 			 */
11926 			return (0);
11927 		}
11928 		len = sendwin - flight;
11929 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11930 			/* We would send too much (beyond the rwnd) */
11931 			len = tp->snd_wnd - ctf_outstanding(tp);
11932 		}
11933 		if ((len + sb_offset) > avail) {
11934 			/*
11935 			 * We don't have that much in the SB, how much is
11936 			 * there?
11937 			 */
11938 			len = avail - sb_offset;
11939 		}
11940 	}
11941 	return (len);
11942 }
11943 
11944 static inline void
11945 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11946 {
11947 #ifdef NETFLIX_STATS
11948 	TCPSTAT_INC(tcps_sndpack_error);
11949 	TCPSTAT_ADD(tcps_sndbyte_error, len);
11950 #endif
11951 }
11952 
11953 static inline void
11954 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11955 {
11956 	if (error) {
11957 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11958 		return;
11959 	}
11960 	if ((tp->t_flags & TF_FORCEDATA) && len == 1) {
11961 		/* Window probe */
11962 		TCPSTAT_INC(tcps_sndprobe);
11963 #ifdef NETFLIX_STATS
11964 		stats_voi_update_abs_u32(tp->t_stats,
11965 		    VOI_TCP_RETXPB, len);
11966 #endif
11967 	} else if (rsm) {
11968 		if (rsm->r_flags & BBR_TLP) {
11969 			/*
11970 			 * TLP should not count in retran count, but in its
11971 			 * own bin
11972 			 */
11973 #ifdef NETFLIX_STATS
11974 			tp->t_sndtlppack++;
11975 			tp->t_sndtlpbyte += len;
11976 			TCPSTAT_INC(tcps_tlpresends);
11977 			TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11978 #endif
11979 		} else {
11980 			/* Retransmit */
11981 			tp->t_sndrexmitpack++;
11982 			TCPSTAT_INC(tcps_sndrexmitpack);
11983 			TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11984 #ifdef NETFLIX_STATS
11985 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11986 			    len);
11987 #endif
11988 		}
11989 		/*
11990 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11991 		 * sub-state
11992 		 */
11993 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11994 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11995 			/* Non probe_bw log in 1, 2, or 4. */
11996 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11997 		} else {
11998 			/*
11999 			 * Log our probe state 3, and log also 5-13 to show
12000 			 * us the recovery sub-state for the send. This
12001 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
12002 			 */
12003 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
12004 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
12005 		}
12006 		/* Place in both 16's the totals of retransmitted */
12007 		counter_u64_add(bbr_state_lost[16], len);
12008 		counter_u64_add(bbr_state_resend[16], len);
12009 		/* Place in 17's the total sent */
12010 		counter_u64_add(bbr_state_resend[17], len);
12011 		counter_u64_add(bbr_state_lost[17], len);
12012 
12013 	} else {
12014 		/* New sends */
12015 		TCPSTAT_INC(tcps_sndpack);
12016 		TCPSTAT_ADD(tcps_sndbyte, len);
12017 		/* Place in 17's the total sent */
12018 		counter_u64_add(bbr_state_resend[17], len);
12019 		counter_u64_add(bbr_state_lost[17], len);
12020 #ifdef NETFLIX_STATS
12021 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
12022 		    len);
12023 #endif
12024 	}
12025 }
12026 
12027 static void
12028 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
12029 {
12030 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
12031 		/*
12032 		 * Limit the cwnd to not be above N x the target plus whats
12033 		 * is outstanding. The target is based on the current b/w
12034 		 * estimate.
12035 		 */
12036 		uint32_t target;
12037 
12038 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
12039 		target += ctf_outstanding(tp);
12040 		target *= bbr_target_cwnd_mult_limit;
12041 		if (tp->snd_cwnd > target)
12042 			tp->snd_cwnd = target;
12043 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
12044 	}
12045 }
12046 
12047 static int
12048 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
12049 {
12050 	/*
12051 	 * "adv" is the amount we could increase the window, taking into
12052 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
12053 	 */
12054 	uint32_t adv;
12055 	int32_t oldwin;
12056 
12057 	adv = min(recwin, TCP_MAXWIN << tp->rcv_scale);
12058 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
12059 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
12060 		adv -= oldwin;
12061 	} else
12062 		oldwin = 0;
12063 
12064 	/*
12065 	 * If the new window size ends up being the same as the old size
12066 	 * when it is scaled, then don't force a window update.
12067 	 */
12068 	if (oldwin >> tp->rcv_scale == (adv + oldwin) >> tp->rcv_scale)
12069 		return (0);
12070 
12071 	if (adv >= (2 * maxseg) &&
12072 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
12073 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
12074 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
12075 		return (1);
12076 	}
12077 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
12078 		return (1);
12079 	return (0);
12080 }
12081 
12082 /*
12083  * Return 0 on success and a errno on failure to send.
12084  * Note that a 0 return may not mean we sent anything
12085  * if the TCB was on the hpts. A non-zero return
12086  * does indicate the error we got from ip[6]_output.
12087  */
12088 static int
12089 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
12090 {
12091 	struct socket *so;
12092 	int32_t len;
12093 	uint32_t cts;
12094 	uint32_t recwin, sendwin;
12095 	int32_t sb_offset;
12096 	int32_t flags, abandon, error = 0;
12097 	struct tcp_log_buffer *lgb = NULL;
12098 	struct mbuf *m;
12099 	struct mbuf *mb;
12100 	uint32_t if_hw_tsomaxsegcount = 0;
12101 	uint32_t if_hw_tsomaxsegsize = 0;
12102 	uint32_t if_hw_tsomax = 0;
12103 	struct ip *ip = NULL;
12104 #ifdef TCPDEBUG
12105 	struct ipovly *ipov = NULL;
12106 #endif
12107 	struct tcp_bbr *bbr;
12108 	struct tcphdr *th;
12109 #ifdef NETFLIX_TCPOUDP
12110 	struct udphdr *udp = NULL;
12111 #endif
12112 	u_char opt[TCP_MAXOLEN];
12113 	unsigned ipoptlen, optlen, hdrlen;
12114 #ifdef NETFLIX_TCPOUDP
12115 	unsigned ulen;
12116 #endif
12117 	uint32_t bbr_seq;
12118 	uint32_t delay_calc=0;
12119 	uint8_t doing_tlp = 0;
12120 	uint8_t local_options;
12121 #ifdef BBR_INVARIANTS
12122 	uint8_t doing_retran_from = 0;
12123 	uint8_t picked_up_retran = 0;
12124 #endif
12125 	uint8_t wanted_cookie = 0;
12126 	uint8_t more_to_rxt=0;
12127 	int32_t prefetch_so_done = 0;
12128 	int32_t prefetch_rsm = 0;
12129  	uint32_t what_we_can = 0;
12130 	uint32_t tot_len = 0;
12131 	uint32_t rtr_cnt = 0;
12132 	uint32_t maxseg, pace_max_segs, p_maxseg;
12133 	int32_t csum_flags;
12134  	int32_t hw_tls;
12135 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12136 	unsigned ipsec_optlen = 0;
12137 
12138 #endif
12139 	volatile int32_t sack_rxmit;
12140 	struct bbr_sendmap *rsm = NULL;
12141 	int32_t tso, mtu;
12142 	int force_tso = 0;
12143 	struct tcpopt to;
12144 	int32_t slot = 0;
12145 	struct inpcb *inp;
12146 	struct sockbuf *sb;
12147 	uint32_t hpts_calling;
12148 #ifdef INET6
12149 	struct ip6_hdr *ip6 = NULL;
12150 	int32_t isipv6;
12151 #endif
12152 	uint8_t app_limited = BBR_JR_SENT_DATA;
12153 	uint8_t filled_all = 0;
12154 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
12155 	/* We take a cache hit here */
12156 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
12157 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
12158 	inp = bbr->rc_inp;
12159 	so = inp->inp_socket;
12160 	sb = &so->so_snd;
12161 #ifdef KERN_TLS
12162  	if (sb->sb_flags & SB_TLS_IFNET)
12163  		hw_tls = 1;
12164  	else
12165 #endif
12166  		hw_tls = 0;
12167 	kern_prefetch(sb, &maxseg);
12168 	maxseg = tp->t_maxseg - bbr->rc_last_options;
12169 	if (bbr_minseg(bbr) < maxseg) {
12170 		tcp_bbr_tso_size_check(bbr, cts);
12171 	}
12172 	/* Remove any flags that indicate we are pacing on the inp  */
12173 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
12174 	p_maxseg = min(maxseg, pace_max_segs);
12175 	INP_WLOCK_ASSERT(inp);
12176 #ifdef TCP_OFFLOAD
12177 	if (tp->t_flags & TF_TOE)
12178 		return (tcp_offload_output(tp));
12179 #endif
12180 
12181 #ifdef INET6
12182 	if (bbr->r_state) {
12183 		/* Use the cache line loaded if possible */
12184 		isipv6 = bbr->r_is_v6;
12185 	} else {
12186 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
12187 	}
12188 #endif
12189 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
12190 	    inp->inp_in_hpts) {
12191 		/*
12192 		 * We are on the hpts for some timer but not hptsi output.
12193 		 * Possibly remove from the hpts so we can send/recv etc.
12194 		 */
12195 		if ((tp->t_flags & TF_ACKNOW) == 0) {
12196 			/*
12197 			 * No immediate demand right now to send an ack, but
12198 			 * the user may have read, making room for new data
12199 			 * (a window update). If so we may want to cancel
12200 			 * whatever timer is running (KEEP/DEL-ACK?) and
12201 			 * continue to send out a window update. Or we may
12202 			 * have gotten more data into the socket buffer to
12203 			 * send.
12204 			 */
12205 			recwin = min(max(sbspace(&so->so_rcv), 0),
12206 			    TCP_MAXWIN << tp->rcv_scale);
12207 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12208 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12209 			    (tp->snd_max - tp->snd_una))) {
12210 				/*
12211 				 * Nothing new to send and no window update
12212 				 * is needed to send. Lets just return and
12213 				 * let the timer-run off.
12214 				 */
12215 				return (0);
12216 			}
12217 		}
12218 		tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12219 		bbr_timer_cancel(bbr, __LINE__, cts);
12220 	}
12221 	if (bbr->r_ctl.rc_last_delay_val) {
12222 		/* Calculate a rough delay for early escape to sending  */
12223 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12224 			delay_calc = cts - bbr->rc_pacer_started;
12225 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12226 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12227 		else
12228 			delay_calc = 0;
12229 	}
12230 	/* Mark that we have called bbr_output(). */
12231 	if ((bbr->r_timer_override) ||
12232 	    (tp->t_flags & TF_FORCEDATA) ||
12233 	    (tp->t_state < TCPS_ESTABLISHED)) {
12234 		/* Timeouts or early states are exempt */
12235 		if (inp->inp_in_hpts)
12236 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12237 	} else if (inp->inp_in_hpts) {
12238 		if ((bbr->r_ctl.rc_last_delay_val) &&
12239 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12240 		    delay_calc) {
12241 			/*
12242 			 * We were being paced for output and the delay has
12243 			 * already exceeded when we were supposed to be
12244 			 * called, lets go ahead and pull out of the hpts
12245 			 * and call output.
12246 			 */
12247 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12248 			bbr->r_ctl.rc_last_delay_val = 0;
12249 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12250 		} else if (tp->t_state == TCPS_CLOSED) {
12251 			bbr->r_ctl.rc_last_delay_val = 0;
12252 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12253 		} else {
12254 			/*
12255 			 * On the hpts, you shall not pass! even if ACKNOW
12256 			 * is on, we will when the hpts fires, unless of
12257 			 * course we are overdue.
12258 			 */
12259 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12260 			return (0);
12261 		}
12262 	}
12263 	bbr->rc_cwnd_limited = 0;
12264 	if (bbr->r_ctl.rc_last_delay_val) {
12265 		/* recalculate the real delay and deal with over/under  */
12266 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12267 			delay_calc = cts - bbr->rc_pacer_started;
12268 		else
12269 			delay_calc = 0;
12270 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12271 			/* Setup the delay which will be added in */
12272 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12273 		else {
12274 			/*
12275 			 * We are early setup to adjust
12276 			 * our slot time.
12277 			 */
12278 			uint64_t merged_val;
12279 
12280 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12281 			bbr->r_agg_early_set = 1;
12282 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12283 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12284 					/* Nope our previous late cancels out the early */
12285 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12286 					bbr->r_agg_early_set = 0;
12287 					bbr->r_ctl.rc_agg_early = 0;
12288 				} else {
12289 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12290 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12291 				}
12292 			}
12293 			merged_val = bbr->rc_pacer_started;
12294 			merged_val <<= 32;
12295 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12296 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12297 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12298 						 bbr->r_agg_early_set, 3);
12299 			bbr->r_ctl.rc_last_delay_val = 0;
12300 			BBR_STAT_INC(bbr_early);
12301 			delay_calc = 0;
12302 		}
12303 	} else {
12304 		/* We were not delayed due to hptsi */
12305 		if (bbr->r_agg_early_set)
12306 			bbr->r_ctl.rc_agg_early = 0;
12307 		bbr->r_agg_early_set = 0;
12308 		delay_calc = 0;
12309 	}
12310 	if (delay_calc) {
12311 		/*
12312 		 * We had a hptsi delay which means we are falling behind on
12313 		 * sending at the expected rate. Calculate an extra amount
12314 		 * of data we can send, if any, to put us back on track.
12315 		 */
12316 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12317 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12318 		else
12319 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12320 	}
12321 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12322 	if ((tp->snd_una == tp->snd_max) &&
12323 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12324 	    (sbavail(sb))) {
12325 		/*
12326 		 * Ok we have been idle with nothing outstanding
12327 		 * we possibly need to start fresh with either a new
12328 		 * suite of states or a fast-ramp up.
12329 		 */
12330 		bbr_restart_after_idle(bbr,
12331 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12332 	}
12333 	/*
12334 	 * Now was there a hptsi delay where we are behind? We only count
12335 	 * being behind if: a) We are not in recovery. b) There was a delay.
12336 	 * <and> c) We had room to send something.
12337 	 *
12338 	 */
12339 	hpts_calling = inp->inp_hpts_calls;
12340 	inp->inp_hpts_calls = 0;
12341 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12342 		if (bbr_process_timers(tp, bbr, cts, hpts_calling)) {
12343 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12344 			return (0);
12345 		}
12346 	}
12347 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12348 	if (hpts_calling &&
12349 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12350 		bbr->r_ctl.rc_last_delay_val = 0;
12351 	}
12352 	bbr->r_timer_override = 0;
12353 	bbr->r_wanted_output = 0;
12354 	/*
12355 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12356 	 * SYN|ACK and those sent by the retransmit timer.
12357 	 */
12358 	if (IS_FASTOPEN(tp->t_flags) &&
12359 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12360 	     (tp->t_state == TCPS_SYN_SENT)) &&
12361 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* inital SYN or SYN|ACK sent */
12362 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12363 		return (0);
12364 	}
12365 	/*
12366 	 * Before sending anything check for a state update. For hpts
12367 	 * calling without input this is important. If its input calling
12368 	 * then this was already done.
12369 	 */
12370 	if (bbr->rc_use_google == 0)
12371 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12372 again:
12373 	/*
12374 	 * If we've recently taken a timeout, snd_max will be greater than
12375 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12376 	 * for historic reasons the persist timer still uses it. This means
12377 	 * we have to look at it. All retransmissions that are not persits
12378 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12379 	 * end of this routine we pull snd_nxt always up to snd_max.
12380 	 */
12381 	doing_tlp = 0;
12382 #ifdef BBR_INVARIANTS
12383 	doing_retran_from = picked_up_retran = 0;
12384 #endif
12385 	error = 0;
12386 	tso = 0;
12387 	slot = 0;
12388 	mtu = 0;
12389 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12390 	sb_offset = tp->snd_max - tp->snd_una;
12391 	flags = tcp_outflags[tp->t_state];
12392 	sack_rxmit = 0;
12393 	len = 0;
12394 	rsm = NULL;
12395 	if (flags & TH_RST) {
12396 		SOCKBUF_LOCK(sb);
12397 		goto send;
12398 	}
12399 recheck_resend:
12400 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12401 		/* We need to always have one in reserve */
12402 		rsm = bbr_alloc(bbr);
12403 		if (rsm == NULL) {
12404 			error = ENOMEM;
12405 			/* Lie to get on the hpts */
12406 			tot_len = tp->t_maxseg;
12407 			if (hpts_calling)
12408 				/* Retry in a ms */
12409 				slot = 1001;
12410 			goto just_return_nolock;
12411 		}
12412 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12413 		bbr->r_ctl.rc_free_cnt++;
12414 		rsm = NULL;
12415 	}
12416 	/* What do we send, a resend? */
12417 	if (bbr->r_ctl.rc_resend == NULL) {
12418 		/* Check for rack timeout */
12419 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12420 		if (bbr->r_ctl.rc_resend) {
12421 #ifdef BBR_INVARIANTS
12422 			picked_up_retran = 1;
12423 #endif
12424 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12425 		}
12426 	}
12427 	if (bbr->r_ctl.rc_resend) {
12428 		rsm = bbr->r_ctl.rc_resend;
12429 #ifdef BBR_INVARIANTS
12430 		doing_retran_from = 1;
12431 #endif
12432 		/* Remove any TLP flags its a RACK or T-O */
12433 		rsm->r_flags &= ~BBR_TLP;
12434 		bbr->r_ctl.rc_resend = NULL;
12435 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12436 #ifdef BBR_INVARIANTS
12437 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12438 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12439 			goto recheck_resend;
12440 #else
12441 			/* TSNH */
12442 			rsm = NULL;
12443 			goto recheck_resend;
12444 #endif
12445 		}
12446 		rtr_cnt++;
12447 		if (rsm->r_flags & BBR_HAS_SYN) {
12448 			/* Only retransmit a SYN by itself */
12449 			len = 0;
12450 			if ((flags & TH_SYN) == 0) {
12451 				/* Huh something is wrong */
12452 				rsm->r_start++;
12453 				if (rsm->r_start == rsm->r_end) {
12454 					/* Clean it up, somehow we missed the ack? */
12455 					bbr_log_syn(tp, NULL);
12456 				} else {
12457 					/* TFO with data? */
12458 					rsm->r_flags &= ~BBR_HAS_SYN;
12459 					len = rsm->r_end - rsm->r_start;
12460 				}
12461 			} else {
12462 				/* Retransmitting SYN */
12463 				rsm = NULL;
12464 				SOCKBUF_LOCK(sb);
12465 				goto send;
12466 			}
12467 		} else
12468 			len = rsm->r_end - rsm->r_start;
12469 		if ((bbr->rc_resends_use_tso == 0) &&
12470 #ifdef KERN_TLS
12471 		    ((sb->sb_flags & SB_TLS_IFNET) == 0) &&
12472 #endif
12473 		    (len > maxseg)) {
12474 			len = maxseg;
12475 			more_to_rxt = 1;
12476 		}
12477 		sb_offset = rsm->r_start - tp->snd_una;
12478 		if (len > 0) {
12479 			sack_rxmit = 1;
12480 			TCPSTAT_INC(tcps_sack_rexmits);
12481 			TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12482 			    min(len, maxseg));
12483 		} else {
12484 			/* I dont think this can happen */
12485 			rsm = NULL;
12486 			goto recheck_resend;
12487 		}
12488 		BBR_STAT_INC(bbr_resends_set);
12489 	} else if (bbr->r_ctl.rc_tlp_send) {
12490 		/*
12491 		 * Tail loss probe
12492 		 */
12493 		doing_tlp = 1;
12494 		rsm = bbr->r_ctl.rc_tlp_send;
12495 		bbr->r_ctl.rc_tlp_send = NULL;
12496 		sack_rxmit = 1;
12497 		len = rsm->r_end - rsm->r_start;
12498 		rtr_cnt++;
12499 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12500 			len = maxseg;
12501 
12502 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12503 #ifdef BBR_INVARIANTS
12504 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12505 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12506 #else
12507 			/* TSNH */
12508 			rsm = NULL;
12509 			goto recheck_resend;
12510 #endif
12511 		}
12512 		sb_offset = rsm->r_start - tp->snd_una;
12513 		BBR_STAT_INC(bbr_tlp_set);
12514 	}
12515 	/*
12516 	 * Enforce a connection sendmap count limit if set
12517 	 * as long as we are not retransmiting.
12518 	 */
12519 	if ((rsm == NULL) &&
12520 	    (bbr_tcp_map_entries_limit > 0) &&
12521 	    (bbr->r_ctl.rc_num_maps_alloced >= bbr_tcp_map_entries_limit)) {
12522 		BBR_STAT_INC(bbr_alloc_limited);
12523 		if (!bbr->alloc_limit_reported) {
12524 			bbr->alloc_limit_reported = 1;
12525 			BBR_STAT_INC(bbr_alloc_limited_conns);
12526 		}
12527 		goto just_return_nolock;
12528 	}
12529 #ifdef BBR_INVARIANTS
12530 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12531 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12532 		    tp, bbr, rsm, sb_offset, len);
12533 	}
12534 #endif
12535 	/*
12536 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12537 	 * state flags.
12538 	 */
12539 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12540 		flags |= TH_FIN;
12541 	if (tp->t_flags & TF_NEEDSYN)
12542 		flags |= TH_SYN;
12543 
12544 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12545 		/* we are retransmitting the fin */
12546 		len--;
12547 		if (len) {
12548 			/*
12549 			 * When retransmitting data do *not* include the
12550 			 * FIN. This could happen from a TLP probe if we
12551 			 * allowed data with a FIN.
12552 			 */
12553 			flags &= ~TH_FIN;
12554 		}
12555 	} else if (rsm) {
12556 		if (flags & TH_FIN)
12557 			flags &= ~TH_FIN;
12558 	}
12559 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12560 		void *end_rsm;
12561 
12562 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12563 		if (end_rsm)
12564 			kern_prefetch(end_rsm, &prefetch_rsm);
12565 		prefetch_rsm = 1;
12566 	}
12567 	SOCKBUF_LOCK(sb);
12568 	/*
12569 	 * If in persist timeout with window of 0, send 1 byte. Otherwise,
12570 	 * if window is small but nonzero and time TF_SENTFIN expired, we
12571 	 * will send what we can and go to transmit state.
12572 	 */
12573 	if (tp->t_flags & TF_FORCEDATA) {
12574 		if ((sendwin == 0) || (sendwin <= (tp->snd_max - tp->snd_una))) {
12575 			/*
12576 			 * If we still have some data to send, then clear
12577 			 * the FIN bit.  Usually this would happen below
12578 			 * when it realizes that we aren't sending all the
12579 			 * data.  However, if we have exactly 1 byte of
12580 			 * unsent data, then it won't clear the FIN bit
12581 			 * below, and if we are in persist state, we wind up
12582 			 * sending the packet without recording that we sent
12583 			 * the FIN bit.
12584 			 *
12585 			 * We can't just blindly clear the FIN bit, because
12586 			 * if we don't have any more data to send then the
12587 			 * probe will be the FIN itself.
12588 			 */
12589 			if (sb_offset < sbused(sb))
12590 				flags &= ~TH_FIN;
12591 			sendwin = 1;
12592 		} else {
12593 			if ((bbr->rc_in_persist != 0) &&
12594  			    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
12595 					       bbr_minseg(bbr)))) {
12596 				/* Exit persists if there is space */
12597 				bbr_exit_persist(tp, bbr, cts, __LINE__);
12598 			}
12599 			if (rsm == NULL) {
12600 				/*
12601 				 * If we are dropping persist mode then we
12602 				 * need to correct sb_offset if not a
12603 				 * retransmit.
12604 				 */
12605 				sb_offset = tp->snd_max - tp->snd_una;
12606 			}
12607 		}
12608 	}
12609 	/*
12610 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12611 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12612 	 * negative length.  This can also occur when TCP opens up its
12613 	 * congestion window while receiving additional duplicate acks after
12614 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12615 	 * the fast-retransmit.
12616 	 *
12617 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12618 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12619 	 * up 0.
12620 	 *
12621 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12622 	 * in which case len is already set.
12623 	 */
12624 	if (sack_rxmit == 0) {
12625 		uint32_t avail;
12626 
12627 		avail = sbavail(sb);
12628 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12629 			sb_offset = tp->snd_max - tp->snd_una;
12630 		else
12631 			sb_offset = 0;
12632 		if (bbr->rc_tlp_new_data) {
12633 			/* TLP is forcing out new data */
12634 			uint32_t tlplen;
12635 
12636 			doing_tlp = 1;
12637 			tlplen = maxseg;
12638 
12639 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12640 				tlplen = (uint32_t)(avail - sb_offset);
12641 			}
12642 			if (tlplen > tp->snd_wnd) {
12643 				len = tp->snd_wnd;
12644 			} else {
12645 				len = tlplen;
12646 			}
12647 			bbr->rc_tlp_new_data = 0;
12648 		} else {
12649 			what_we_can = len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12650 			if ((len < p_maxseg) &&
12651 			    (bbr->rc_in_persist == 0) &&
12652 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12653 			    ((avail - sb_offset) >= p_maxseg)) {
12654 				/*
12655 				 * We are not completing whats in the socket
12656 				 * buffer (i.e. there is at least a segment
12657 				 * waiting to send) and we have 2 or more
12658 				 * segments outstanding. There is no sense
12659 				 * of sending a little piece. Lets defer and
12660 				 * and wait until we can send a whole
12661 				 * segment.
12662 				 */
12663 				len = 0;
12664 			}
12665 			if ((tp->t_flags & TF_FORCEDATA) && (bbr->rc_in_persist)) {
12666 				/*
12667 				 * We are in persists, figure out if
12668 				 * a retransmit is available (maybe the previous
12669 				 * persists we sent) or if we have to send new
12670 				 * data.
12671 				 */
12672 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12673 				if (rsm) {
12674 					len = rsm->r_end - rsm->r_start;
12675 					if (rsm->r_flags & BBR_HAS_FIN)
12676 						len--;
12677 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12678 						len = maxseg;
12679 					if (len > 1)
12680 						BBR_STAT_INC(bbr_persist_reneg);
12681 					/*
12682 					 * XXXrrs we could force the len to
12683 					 * 1 byte here to cause the chunk to
12684 					 * split apart.. but that would then
12685 					 * mean we always retransmit it as
12686 					 * one byte even after the window
12687 					 * opens.
12688 					 */
12689 					sack_rxmit = 1;
12690 					sb_offset = rsm->r_start - tp->snd_una;
12691 				} else {
12692 					/*
12693 					 * First time through in persists or peer
12694 					 * acked our one byte. Though we do have
12695 					 * to have something in the sb.
12696 					 */
12697 					len = 1;
12698 					sb_offset = 0;
12699 					if (avail == 0)
12700 					    len = 0;
12701 				}
12702 			}
12703 		}
12704 	}
12705 	if (prefetch_so_done == 0) {
12706 		kern_prefetch(so, &prefetch_so_done);
12707 		prefetch_so_done = 1;
12708 	}
12709 	/*
12710 	 * Lop off SYN bit if it has already been sent.  However, if this is
12711 	 * SYN-SENT state and if segment contains data and if we don't know
12712 	 * that foreign host supports TAO, suppress sending segment.
12713 	 */
12714 	if ((flags & TH_SYN) && (rsm == NULL) &&
12715 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12716 		if (tp->t_state != TCPS_SYN_RECEIVED)
12717 			flags &= ~TH_SYN;
12718 		/*
12719 		 * When sending additional segments following a TFO SYN|ACK,
12720 		 * do not include the SYN bit.
12721 		 */
12722 		if (IS_FASTOPEN(tp->t_flags) &&
12723 		    (tp->t_state == TCPS_SYN_RECEIVED))
12724 			flags &= ~TH_SYN;
12725 		sb_offset--, len++;
12726 		if (sbavail(sb) == 0)
12727 			len = 0;
12728 	} else if ((flags & TH_SYN) && rsm) {
12729 		/*
12730 		 * Subtract one from the len for the SYN being
12731 		 * retransmitted.
12732 		 */
12733 		len--;
12734 	}
12735 	/*
12736 	 * Be careful not to send data and/or FIN on SYN segments. This
12737 	 * measure is needed to prevent interoperability problems with not
12738 	 * fully conformant TCP implementations.
12739 	 */
12740 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12741 		len = 0;
12742 		flags &= ~TH_FIN;
12743 	}
12744 	/*
12745 	 * On TFO sockets, ensure no data is sent in the following cases:
12746 	 *
12747 	 *  - When retransmitting SYN|ACK on a passively-created socket
12748 	 *  - When retransmitting SYN on an actively created socket
12749 	 *  - When sending a zero-length cookie (cookie request) on an
12750 	 *    actively created socket
12751 	 *  - When the socket is in the CLOSED state (RST is being sent)
12752 	 */
12753 	if (IS_FASTOPEN(tp->t_flags) &&
12754 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12755 	     ((tp->t_state == TCPS_SYN_SENT) &&
12756 	      (tp->t_tfo_client_cookie_len == 0)) ||
12757 	     (flags & TH_RST))) {
12758 		len = 0;
12759 		sack_rxmit = 0;
12760 		rsm = NULL;
12761 	}
12762 	/* Without fast-open there should never be data sent on a SYN */
12763 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12764 		len = 0;
12765 	if (len <= 0) {
12766 		/*
12767 		 * If FIN has been sent but not acked, but we haven't been
12768 		 * called to retransmit, len will be < 0.  Otherwise, window
12769 		 * shrank after we sent into it.  If window shrank to 0,
12770 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12771 		 * window, and set the persist timer if it isn't already
12772 		 * going.  If the window didn't close completely, just wait
12773 		 * for an ACK.
12774 		 *
12775 		 * We also do a general check here to ensure that we will
12776 		 * set the persist timer when we have data to send, but a
12777 		 * 0-byte window. This makes sure the persist timer is set
12778 		 * even if the packet hits one of the "goto send" lines
12779 		 * below.
12780 		 */
12781 		len = 0;
12782 		if ((tp->snd_wnd == 0) &&
12783 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12784 		    (tp->snd_una == tp->snd_max) &&
12785 		    (sb_offset < (int)sbavail(sb))) {
12786 			/*
12787 			 * Not enough room in the rwnd to send
12788 			 * a paced segment out.
12789 			 */
12790 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12791 		}
12792 	} else if ((rsm == NULL) &&
12793 		   (doing_tlp == 0) &&
12794 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12795 		/*
12796 		 * We are not sending a full segment for
12797 		 * some reason. Should we not send anything (think
12798 		 * sws or persists)?
12799 		 */
12800 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12801 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12802 		    (len < (int)(sbavail(sb) - sb_offset))) {
12803 			/*
12804 			 * Here the rwnd is less than
12805 			 * the pacing size, this is not a retransmit,
12806 			 * we are established and
12807 			 * the send is not the last in the socket buffer
12808 			 * lets not send, and possibly enter persists.
12809 			 */
12810 			len = 0;
12811 			if (tp->snd_max == tp->snd_una)
12812 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12813 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12814 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12815 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12816 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12817 			   (len < bbr_minseg(bbr))) {
12818 			/*
12819 			 * Here we are not retransmitting, and
12820 			 * the cwnd is not so small that we could
12821 			 * not send at least a min size (rxt timer
12822 			 * not having gone off), We have 2 segments or
12823 			 * more already in flight, its not the tail end
12824 			 * of the socket buffer  and the cwnd is blocking
12825 			 * us from sending out minimum pacing segment size.
12826 			 * Lets not send anything.
12827 			 */
12828 			bbr->rc_cwnd_limited = 1;
12829 			len = 0;
12830 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12831 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12832 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12833 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12834 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12835 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12836 			/*
12837 			 * Here we have a send window but we have
12838 			 * filled it up and we can't send another pacing segment.
12839 			 * We also have in flight more than 2 segments
12840 			 * and we are not completing the sb i.e. we allow
12841 			 * the last bytes of the sb to go out even if
12842 			 * its not a full pacing segment.
12843 			 */
12844 			len = 0;
12845 		}
12846 	}
12847 	/* len will be >= 0 after this point. */
12848 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12849 	tcp_sndbuf_autoscale(tp, so, sendwin);
12850 	/*
12851 	 *
12852 	 */
12853 	if (bbr->rc_in_persist &&
12854 	    len &&
12855 	    (rsm == NULL) &&
12856 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12857 		/*
12858 		 * We are in persist, not doing a retransmit and don't have enough space
12859 		 * yet to send a full TSO. So is it at the end of the sb
12860 		 * if so we need to send else nuke to 0 and don't send.
12861 		 */
12862 		int sbleft;
12863 		if (sbavail(sb) > sb_offset)
12864 			sbleft = sbavail(sb) - sb_offset;
12865 		else
12866 			sbleft = 0;
12867 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12868 			/* not at end of sb lets not send */
12869 			len = 0;
12870 		}
12871 	}
12872 	/*
12873 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12874 	 * hardware).
12875 	 *
12876 	 * TSO may only be used if we are in a pure bulk sending state.  The
12877 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12878 	 * options prevent using TSO.  With TSO the TCP header is the same
12879 	 * (except for the sequence number) for all generated packets.  This
12880 	 * makes it impossible to transmit any options which vary per
12881 	 * generated segment or packet.
12882 	 *
12883 	 * IPv4 handling has a clear separation of ip options and ip header
12884 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12885 	 * does the right thing below to provide length of just ip options
12886 	 * and thus checking for ipoptlen is enough to decide if ip options
12887 	 * are present.
12888 	 */
12889 #ifdef INET6
12890 	if (isipv6)
12891 		ipoptlen = ip6_optlen(inp);
12892 	else
12893 #endif
12894 	if (inp->inp_options)
12895 		ipoptlen = inp->inp_options->m_len -
12896 		    offsetof(struct ipoption, ipopt_list);
12897 	else
12898 		ipoptlen = 0;
12899 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12900 	/*
12901 	 * Pre-calculate here as we save another lookup into the darknesses
12902 	 * of IPsec that way and can actually decide if TSO is ok.
12903 	 */
12904 #ifdef INET6
12905 	if (isipv6 && IPSEC_ENABLED(ipv6))
12906 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12907 #ifdef INET
12908 	else
12909 #endif
12910 #endif				/* INET6 */
12911 #ifdef INET
12912 	if (IPSEC_ENABLED(ipv4))
12913 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12914 #endif				/* INET */
12915 #endif				/* IPSEC */
12916 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12917 	ipoptlen += ipsec_optlen;
12918 #endif
12919 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12920 	    (len > maxseg) &&
12921 	    (tp->t_port == 0) &&
12922 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12923 	    tp->rcv_numsacks == 0 &&
12924 	    ipoptlen == 0)
12925 		tso = 1;
12926 
12927 	recwin = min(max(sbspace(&so->so_rcv), 0),
12928 	    TCP_MAXWIN << tp->rcv_scale);
12929 	/*
12930 	 * Sender silly window avoidance.   We transmit under the following
12931 	 * conditions when len is non-zero:
12932 	 *
12933 	 * - We have a full segment (or more with TSO) - This is the last
12934 	 * buffer in a write()/send() and we are either idle or running
12935 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12936 	 * then 1/2 the maximum send window's worth of data (receiver may be
12937 	 * limited the window size) - we need to retransmit
12938 	 */
12939 	if (rsm)
12940 		goto send;
12941 	if (len) {
12942 		if (sack_rxmit)
12943 			goto send;
12944 		if (len >= p_maxseg)
12945 			goto send;
12946 		/*
12947 		 * NOTE! on localhost connections an 'ack' from the remote
12948 		 * end may occur synchronously with the output and cause us
12949 		 * to flush a buffer queued with moretocome.  XXX
12950 		 *
12951 		 */
12952 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12953 		    ((tp->t_flags & TF_NODELAY) ||
12954 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12955 		    (tp->t_flags & TF_NOPUSH) == 0) {
12956 			goto send;
12957 		}
12958 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12959 			goto send;
12960 		}
12961 		if (tp->t_flags & TF_FORCEDATA) {	/* typ. timeout case */
12962 			goto send;
12963 		}
12964 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12965 			goto send;
12966 		}
12967 	}
12968 	/*
12969 	 * Sending of standalone window updates.
12970 	 *
12971 	 * Window updates are important when we close our window due to a
12972 	 * full socket buffer and are opening it again after the application
12973 	 * reads data from it.  Once the window has opened again and the
12974 	 * remote end starts to send again the ACK clock takes over and
12975 	 * provides the most current window information.
12976 	 *
12977 	 * We must avoid the silly window syndrome whereas every read from
12978 	 * the receive buffer, no matter how small, causes a window update
12979 	 * to be sent.  We also should avoid sending a flurry of window
12980 	 * updates when the socket buffer had queued a lot of data and the
12981 	 * application is doing small reads.
12982 	 *
12983 	 * Prevent a flurry of pointless window updates by only sending an
12984 	 * update when we can increase the advertized window by more than
12985 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12986 	 * full or is very small be more aggressive and send an update
12987 	 * whenever we can increase by two mss sized segments. In all other
12988 	 * situations the ACK's to new incoming data will carry further
12989 	 * window increases.
12990 	 *
12991 	 * Don't send an independent window update if a delayed ACK is
12992 	 * pending (it will get piggy-backed on it) or the remote side
12993 	 * already has done a half-close and won't send more data.  Skip
12994 	 * this if the connection is in T/TCP half-open state.
12995 	 */
12996 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12997 	    !(tp->t_flags & TF_DELACK) &&
12998 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12999 		/* Check to see if we should do a window update */
13000 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
13001 			goto send;
13002 	}
13003 	/*
13004 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
13005 	 * is also a catch-all for the retransmit timer timeout case.
13006 	 */
13007 	if (tp->t_flags & TF_ACKNOW) {
13008 		goto send;
13009 	}
13010 	if (((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0)) {
13011 		goto send;
13012 	}
13013 	if (SEQ_GT(tp->snd_up, tp->snd_una)) {
13014 		goto send;
13015 	}
13016 	/*
13017 	 * If our state indicates that FIN should be sent and we have not
13018 	 * yet done so, then we need to send.
13019 	 */
13020 	if (flags & TH_FIN &&
13021 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
13022 		goto send;
13023 	}
13024 	/*
13025 	 * No reason to send a segment, just return.
13026 	 */
13027 just_return:
13028 	SOCKBUF_UNLOCK(sb);
13029 just_return_nolock:
13030 	if (tot_len)
13031 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13032 	if (bbr->rc_no_pacing)
13033 		slot = 0;
13034 	if (tot_len == 0) {
13035 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
13036 		    tp->snd_wnd) {
13037 			BBR_STAT_INC(bbr_rwnd_limited);
13038 			app_limited = BBR_JR_RWND_LIMITED;
13039 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
13040 			if ((bbr->rc_in_persist == 0) &&
13041 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
13042 			    (tp->snd_max == tp->snd_una) &&
13043 			    sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
13044 				/* No send window.. we must enter persist */
13045 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
13046 			}
13047 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
13048 			BBR_STAT_INC(bbr_app_limited);
13049 			app_limited = BBR_JR_APP_LIMITED;
13050 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
13051 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13052 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
13053 			BBR_STAT_INC(bbr_cwnd_limited);
13054  			app_limited = BBR_JR_CWND_LIMITED;
13055 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13056 									bbr->r_ctl.rc_lost_bytes)));
13057 			bbr->rc_cwnd_limited = 1;
13058 		} else {
13059 			BBR_STAT_INC(bbr_app_limited);
13060 			app_limited = BBR_JR_APP_LIMITED;
13061 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
13062 		}
13063 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13064 		bbr->r_agg_early_set = 0;
13065 		bbr->r_ctl.rc_agg_early = 0;
13066 		bbr->r_ctl.rc_last_delay_val = 0;
13067 	} else if (bbr->rc_use_google == 0)
13068 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13069 	/* Are we app limited? */
13070 	if ((app_limited == BBR_JR_APP_LIMITED) ||
13071 	    (app_limited == BBR_JR_RWND_LIMITED)) {
13072 		/**
13073 		 * We are application limited.
13074 		 */
13075 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13076 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
13077 	}
13078 	if (tot_len == 0)
13079 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
13080 	tp->t_flags &= ~TF_FORCEDATA;
13081 	/* Dont update the time if we did not send */
13082 	bbr->r_ctl.rc_last_delay_val = 0;
13083 	bbr->rc_output_starts_timer = 1;
13084 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
13085 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
13086 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13087 		/* Make sure snd_nxt is drug up */
13088 		tp->snd_nxt = tp->snd_max;
13089 	}
13090 	return (error);
13091 
13092 send:
13093 	if (doing_tlp == 0) {
13094 		/*
13095 		 * Data not a TLP, and its not the rxt firing. If it is the
13096 		 * rxt firing, we want to leave the tlp_in_progress flag on
13097 		 * so we don't send another TLP. It has to be a rack timer
13098 		 * or normal send (response to acked data) to clear the tlp
13099 		 * in progress flag.
13100 		 */
13101 		bbr->rc_tlp_in_progress = 0;
13102 		bbr->rc_tlp_rtx_out = 0;
13103 	} else {
13104 		/*
13105 		 * Its a TLP.
13106 		 */
13107 		bbr->rc_tlp_in_progress = 1;
13108 	}
13109 	bbr_timer_cancel(bbr, __LINE__, cts);
13110 	if (rsm == NULL) {
13111 		if (sbused(sb) > 0) {
13112 			/*
13113 			 * This is sub-optimal. We only send a stand alone
13114 			 * FIN on its own segment.
13115 			 */
13116 			if (flags & TH_FIN) {
13117 				flags &= ~TH_FIN;
13118 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
13119 					/* Lets not send this */
13120 					slot = 0;
13121 					goto just_return;
13122 				}
13123 			}
13124 		}
13125 	} else {
13126 		/*
13127 		 * We do *not* send a FIN on a retransmit if it has data.
13128 		 * The if clause here where len > 1 should never come true.
13129 		 */
13130 		if ((len > 0) &&
13131 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
13132 		    (flags & TH_FIN))) {
13133 			flags &= ~TH_FIN;
13134 			len--;
13135 		}
13136 	}
13137 	SOCKBUF_LOCK_ASSERT(sb);
13138 	if (len > 0) {
13139 		if ((tp->snd_una == tp->snd_max) &&
13140 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
13141 			/*
13142 			 * This qualifies as a RTT_PROBE session since we
13143 			 * drop the data outstanding to nothing and waited
13144 			 * more than bbr_rtt_probe_time.
13145 			 */
13146 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
13147 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
13148 		}
13149 		if (len >= maxseg)
13150 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
13151 		else
13152 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
13153 	}
13154 	/*
13155 	 * Before ESTABLISHED, force sending of initial options unless TCP
13156 	 * set not to do any options. NOTE: we assume that the IP/TCP header
13157 	 * plus TCP options always fit in a single mbuf, leaving room for a
13158 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
13159 	 * + optlen <= MCLBYTES
13160 	 */
13161 	optlen = 0;
13162 #ifdef INET6
13163 	if (isipv6)
13164 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
13165 	else
13166 #endif
13167 		hdrlen = sizeof(struct tcpiphdr);
13168 
13169 	/*
13170 	 * Compute options for segment. We only have to care about SYN and
13171 	 * established connection segments.  Options for SYN-ACK segments
13172 	 * are handled in TCP syncache.
13173 	 */
13174 	to.to_flags = 0;
13175 	local_options = 0;
13176 	if ((tp->t_flags & TF_NOOPT) == 0) {
13177 		/* Maximum segment size. */
13178 		if (flags & TH_SYN) {
13179 			to.to_mss = tcp_mssopt(&inp->inp_inc);
13180 #ifdef NETFLIX_TCPOUDP
13181 			if (tp->t_port)
13182 				to.to_mss -= V_tcp_udp_tunneling_overhead;
13183 #endif
13184 			to.to_flags |= TOF_MSS;
13185 			/*
13186 			 * On SYN or SYN|ACK transmits on TFO connections,
13187 			 * only include the TFO option if it is not a
13188 			 * retransmit, as the presence of the TFO option may
13189 			 * have caused the original SYN or SYN|ACK to have
13190 			 * been dropped by a middlebox.
13191 			 */
13192 			if (IS_FASTOPEN(tp->t_flags) &&
13193 			    (tp->t_rxtshift == 0)) {
13194 				if (tp->t_state == TCPS_SYN_RECEIVED) {
13195 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
13196 					to.to_tfo_cookie =
13197 					    (u_int8_t *)&tp->t_tfo_cookie.server;
13198 					to.to_flags |= TOF_FASTOPEN;
13199 					wanted_cookie = 1;
13200 				} else if (tp->t_state == TCPS_SYN_SENT) {
13201 					to.to_tfo_len =
13202 					    tp->t_tfo_client_cookie_len;
13203 					to.to_tfo_cookie =
13204 					    tp->t_tfo_cookie.client;
13205 					to.to_flags |= TOF_FASTOPEN;
13206 					wanted_cookie = 1;
13207 				}
13208 			}
13209 		}
13210 		/* Window scaling. */
13211 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
13212 			to.to_wscale = tp->request_r_scale;
13213 			to.to_flags |= TOF_SCALE;
13214 		}
13215 		/* Timestamps. */
13216 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
13217 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
13218 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
13219 			to.to_tsecr = tp->ts_recent;
13220 			to.to_flags |= TOF_TS;
13221 			local_options += TCPOLEN_TIMESTAMP + 2;
13222 		}
13223 		/* Set receive buffer autosizing timestamp. */
13224 		if (tp->rfbuf_ts == 0 &&
13225 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
13226 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
13227 		/* Selective ACK's. */
13228 		if (flags & TH_SYN)
13229 			to.to_flags |= TOF_SACKPERM;
13230 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13231 		    tp->rcv_numsacks > 0) {
13232 			to.to_flags |= TOF_SACK;
13233 			to.to_nsacks = tp->rcv_numsacks;
13234 			to.to_sacks = (u_char *)tp->sackblks;
13235 		}
13236 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13237 		/* TCP-MD5 (RFC2385). */
13238 		if (tp->t_flags & TF_SIGNATURE)
13239 			to.to_flags |= TOF_SIGNATURE;
13240 #endif				/* TCP_SIGNATURE */
13241 
13242 		/* Processing the options. */
13243 		hdrlen += (optlen = tcp_addoptions(&to, opt));
13244 		/*
13245 		 * If we wanted a TFO option to be added, but it was unable
13246 		 * to fit, ensure no data is sent.
13247 		 */
13248 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13249 		    !(to.to_flags & TOF_FASTOPEN))
13250 			len = 0;
13251 	}
13252 #ifdef NETFLIX_TCPOUDP
13253 	if (tp->t_port) {
13254 		if (V_tcp_udp_tunneling_port == 0) {
13255 			/* The port was removed?? */
13256 			SOCKBUF_UNLOCK(&so->so_snd);
13257 			return (EHOSTUNREACH);
13258 		}
13259 
13260 		hdrlen += sizeof(struct udphdr);
13261 	}
13262 #endif
13263 #ifdef INET6
13264 	if (isipv6)
13265 		ipoptlen = ip6_optlen(tp->t_inpcb);
13266 	else
13267 #endif
13268 	if (tp->t_inpcb->inp_options)
13269 		ipoptlen = tp->t_inpcb->inp_options->m_len -
13270 		    offsetof(struct ipoption, ipopt_list);
13271 	else
13272 		ipoptlen = 0;
13273 	ipoptlen = 0;
13274 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13275 	ipoptlen += ipsec_optlen;
13276 #endif
13277 	if (bbr->rc_last_options != local_options) {
13278 		/*
13279 		 * Cache the options length this generally does not change
13280 		 * on a connection. We use this to calculate TSO.
13281 		 */
13282 		bbr->rc_last_options = local_options;
13283 	}
13284 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
13285 	p_maxseg = min(maxseg, pace_max_segs);
13286 	/*
13287 	 * Adjust data length if insertion of options will bump the packet
13288 	 * length beyond the t_maxseg length. Clear the FIN bit because we
13289 	 * cut off the tail of the segment.
13290 	 */
13291 #ifdef KERN_TLS
13292  	/* force TSO for so TLS offload can get mss */
13293  	if (sb->sb_flags & SB_TLS_IFNET) {
13294  		force_tso = 1;
13295  	}
13296 #endif
13297 
13298 	if (len > maxseg) {
13299 		if (len != 0 && (flags & TH_FIN)) {
13300 			flags &= ~TH_FIN;
13301 		}
13302 		if (tso) {
13303 			uint32_t moff;
13304 			int32_t max_len;
13305 
13306 			/* extract TSO information */
13307 			if_hw_tsomax = tp->t_tsomax;
13308 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13309 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13310 			KASSERT(ipoptlen == 0,
13311 			    ("%s: TSO can't do IP options", __func__));
13312 
13313 			/*
13314 			 * Check if we should limit by maximum payload
13315 			 * length:
13316 			 */
13317 			if (if_hw_tsomax != 0) {
13318 				/* compute maximum TSO length */
13319 				max_len = (if_hw_tsomax - hdrlen -
13320 				    max_linkhdr);
13321 				if (max_len <= 0) {
13322 					len = 0;
13323 				} else if (len > max_len) {
13324 					len = max_len;
13325 				}
13326 			}
13327 			/*
13328 			 * Prevent the last segment from being fractional
13329 			 * unless the send sockbuf can be emptied:
13330 			 */
13331 			if (((sb_offset + len) < sbavail(sb)) &&
13332 			    (hw_tls == 0)) {
13333 				moff = len % (uint32_t)maxseg;
13334 				if (moff != 0) {
13335 					len -= moff;
13336 				}
13337 			}
13338 			/*
13339 			 * In case there are too many small fragments don't
13340 			 * use TSO:
13341 			 */
13342 			if (len <= maxseg) {
13343 				len = maxseg;
13344 				tso = 0;
13345 			}
13346 		} else {
13347 			/* Not doing TSO */
13348 			if (optlen + ipoptlen >= tp->t_maxseg) {
13349 				/*
13350 				 * Since we don't have enough space to put
13351 				 * the IP header chain and the TCP header in
13352 				 * one packet as required by RFC 7112, don't
13353 				 * send it. Also ensure that at least one
13354 				 * byte of the payload can be put into the
13355 				 * TCP segment.
13356 				 */
13357 				SOCKBUF_UNLOCK(&so->so_snd);
13358 				error = EMSGSIZE;
13359 				sack_rxmit = 0;
13360 				goto out;
13361 			}
13362 			len = maxseg;
13363 		}
13364 	} else {
13365 		/* Not doing TSO */
13366 		if_hw_tsomaxsegcount = 0;
13367 		tso = 0;
13368 	}
13369 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13370 	    ("%s: len > IP_MAXPACKET", __func__));
13371 #ifdef DIAGNOSTIC
13372 #ifdef INET6
13373 	if (max_linkhdr + hdrlen > MCLBYTES)
13374 #else
13375 	if (max_linkhdr + hdrlen > MHLEN)
13376 #endif
13377 		panic("tcphdr too big");
13378 #endif
13379 	/*
13380 	 * This KASSERT is here to catch edge cases at a well defined place.
13381 	 * Before, those had triggered (random) panic conditions further
13382 	 * down.
13383 	 */
13384 #ifdef BBR_INVARIANTS
13385 	if (sack_rxmit) {
13386 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13387 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13388 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13389 		}
13390 	}
13391 #endif
13392 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13393 	if ((len == 0) &&
13394 	    (flags & TH_FIN) &&
13395 	    (sbused(sb))) {
13396 		/*
13397 		 * We have outstanding data, don't send a fin by itself!.
13398 		 */
13399 		slot = 0;
13400 		goto just_return;
13401 	}
13402 	/*
13403 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13404 	 * and initialize the header from the template for sends on this
13405 	 * connection.
13406 	 */
13407 	if (len) {
13408 		uint32_t moff;
13409 		uint32_t orig_len;
13410 
13411 		/*
13412 		 * We place a limit on sending with hptsi.
13413 		 */
13414 		if ((rsm == NULL) && len > pace_max_segs)
13415 			len = pace_max_segs;
13416 		if (len <= maxseg)
13417 			tso = 0;
13418 #ifdef INET6
13419 		if (MHLEN < hdrlen + max_linkhdr)
13420 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13421 		else
13422 #endif
13423 			m = m_gethdr(M_NOWAIT, MT_DATA);
13424 
13425 		if (m == NULL) {
13426 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13427 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13428 			SOCKBUF_UNLOCK(sb);
13429 			error = ENOBUFS;
13430 			sack_rxmit = 0;
13431 			goto out;
13432 		}
13433 		m->m_data += max_linkhdr;
13434 		m->m_len = hdrlen;
13435 		/*
13436 		 * Start the m_copy functions from the closest mbuf to the
13437 		 * sb_offset in the socket buffer chain.
13438 		 */
13439 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13440 #ifdef BBR_INVARIANTS
13441 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13442 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13443 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13444 				    doing_retran_from,
13445 				    picked_up_retran,
13446 				    doing_tlp);
13447 
13448 #endif
13449 			/*
13450 			 * In this messed up situation we have two choices,
13451 			 * a) pretend the send worked, and just start timers
13452 			 * and what not (not good since that may lead us
13453 			 * back here a lot). <or> b) Send the lowest segment
13454 			 * in the map. <or> c) Drop the connection. Lets do
13455 			 * <b> which if it continues to happen will lead to
13456 			 * <c> via timeouts.
13457 			 */
13458 			BBR_STAT_INC(bbr_offset_recovery);
13459 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13460 			sb_offset = 0;
13461 			if (rsm == NULL) {
13462 				sack_rxmit = 0;
13463 				len = sbavail(sb);
13464 			} else {
13465 				sack_rxmit = 1;
13466 				if (rsm->r_start != tp->snd_una) {
13467 					/*
13468 					 * Things are really messed up, <c>
13469 					 * is the only thing to do.
13470 					 */
13471 					BBR_STAT_INC(bbr_offset_drop);
13472 					tcp_set_inp_to_drop(inp, EFAULT);
13473 					return (0);
13474 				}
13475 				len = rsm->r_end - rsm->r_start;
13476 			}
13477 			if (len > sbavail(sb))
13478 				len = sbavail(sb);
13479 			if (len > maxseg)
13480 				len = maxseg;
13481 		}
13482 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13483 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13484 			m_copydata(mb, moff, (int)len,
13485 			    mtod(m, caddr_t)+hdrlen);
13486 			if (rsm == NULL)
13487 				sbsndptr_adv(sb, mb, len);
13488 			m->m_len += len;
13489 		} else {
13490 			struct sockbuf *msb;
13491 
13492 			if (rsm)
13493 				msb = NULL;
13494 			else
13495 				msb = sb;
13496 #ifdef BBR_INVARIANTS
13497 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13498 				if (rsm) {
13499 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u rsm:%p snd_una:%u rsm_start:%u flg:%x %u:%u:%u sr:%d ",
13500 					    tp, bbr, len, moff,
13501 					    sbavail(sb), rsm,
13502 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13503 					    doing_retran_from,
13504 					    picked_up_retran,
13505 					    doing_tlp, sack_rxmit);
13506 				} else {
13507 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13508 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13509 				}
13510 			}
13511 #endif
13512 			orig_len = len;
13513 			m->m_next = tcp_m_copym(
13514 #ifdef NETFLIX_COPY_ARGS
13515 				tp,
13516 #endif
13517 				mb, moff, &len,
13518 				if_hw_tsomaxsegcount,
13519 				if_hw_tsomaxsegsize, msb,
13520 				((rsm == NULL) ? hw_tls : 0)
13521 #ifdef NETFLIX_COPY_ARGS
13522 				, &filled_all
13523 #endif
13524 				);
13525 			if (len <= maxseg && !force_tso) {
13526 				/*
13527 				 * Must have ran out of mbufs for the copy
13528 				 * shorten it to no longer need tso. Lets
13529 				 * not put on sendalot since we are low on
13530 				 * mbufs.
13531 				 */
13532 				tso = 0;
13533 			}
13534 			if (m->m_next == NULL) {
13535 				SOCKBUF_UNLOCK(sb);
13536 				(void)m_free(m);
13537 				error = ENOBUFS;
13538 				sack_rxmit = 0;
13539 				goto out;
13540 			}
13541 		}
13542 #ifdef BBR_INVARIANTS
13543 		if (tso && len < maxseg) {
13544 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13545 			    tp, len, maxseg);
13546 		}
13547 		if (tso && if_hw_tsomaxsegcount) {
13548 			int32_t seg_cnt = 0;
13549 			struct mbuf *foo;
13550 
13551 			foo = m;
13552 			while (foo) {
13553 				seg_cnt++;
13554 				foo = foo->m_next;
13555 			}
13556 			if (seg_cnt > if_hw_tsomaxsegcount) {
13557 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13558 			}
13559 		}
13560 #endif
13561 		/*
13562 		 * If we're sending everything we've got, set PUSH. (This
13563 		 * will keep happy those implementations which only give
13564 		 * data to the user when a buffer fills or a PUSH comes in.)
13565 		 */
13566 		if (sb_offset + len == sbused(sb) &&
13567 		    sbused(sb) &&
13568 		    !(flags & TH_SYN)) {
13569 			flags |= TH_PUSH;
13570 		}
13571 		SOCKBUF_UNLOCK(sb);
13572 	} else {
13573 		SOCKBUF_UNLOCK(sb);
13574 		if (tp->t_flags & TF_ACKNOW)
13575 			TCPSTAT_INC(tcps_sndacks);
13576 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13577 			TCPSTAT_INC(tcps_sndctrl);
13578 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
13579 			TCPSTAT_INC(tcps_sndurg);
13580 		else
13581 			TCPSTAT_INC(tcps_sndwinup);
13582 
13583 		m = m_gethdr(M_NOWAIT, MT_DATA);
13584 		if (m == NULL) {
13585 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13586 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13587 			error = ENOBUFS;
13588 			/* Fudge the send time since we could not send */
13589 			sack_rxmit = 0;
13590 			goto out;
13591 		}
13592 #ifdef INET6
13593 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13594 		    MHLEN >= hdrlen) {
13595 			M_ALIGN(m, hdrlen);
13596 		} else
13597 #endif
13598 			m->m_data += max_linkhdr;
13599 		m->m_len = hdrlen;
13600 	}
13601 	SOCKBUF_UNLOCK_ASSERT(sb);
13602 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13603 #ifdef MAC
13604 	mac_inpcb_create_mbuf(inp, m);
13605 #endif
13606 #ifdef INET6
13607 	if (isipv6) {
13608 		ip6 = mtod(m, struct ip6_hdr *);
13609 #ifdef NETFLIX_TCPOUDP
13610 		if (tp->t_port) {
13611 			udp = (struct udphdr *)((caddr_t)ip6 + ipoptlen + sizeof(struct ip6_hdr));
13612 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13613 			udp->uh_dport = tp->t_port;
13614 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13615 			udp->uh_ulen = htons(ulen);
13616 			th = (struct tcphdr *)(udp + 1);
13617 		} else {
13618 #endif
13619 			th = (struct tcphdr *)(ip6 + 1);
13620 
13621 #ifdef NETFLIX_TCPOUDP
13622 		}
13623 #endif
13624 		tcpip_fillheaders(inp,
13625 #ifdef NETFLIX_TCPOUDP
13626 				  tp->t_port,
13627 #endif
13628 				  ip6, th);
13629 	} else
13630 #endif				/* INET6 */
13631 	{
13632 		ip = mtod(m, struct ip *);
13633 #ifdef TCPDEBUG
13634 		ipov = (struct ipovly *)ip;
13635 #endif
13636 #ifdef NETFLIX_TCPOUDP
13637 		if (tp->t_port) {
13638 			udp = (struct udphdr *)((caddr_t)ip + ipoptlen + sizeof(struct ip));
13639 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13640 			udp->uh_dport = tp->t_port;
13641 			ulen = hdrlen + len - sizeof(struct ip);
13642 			udp->uh_ulen = htons(ulen);
13643 			th = (struct tcphdr *)(udp + 1);
13644 		} else
13645 #endif
13646 			th = (struct tcphdr *)(ip + 1);
13647 		tcpip_fillheaders(inp,
13648 #ifdef NETFLIX_TCPOUDP
13649 				  tp->t_port,
13650 #endif
13651 				  ip, th);
13652 	}
13653 	/*
13654 	 * If we are doing retransmissions, then snd_nxt will not reflect
13655 	 * the first unsent octet.  For ACK only packets, we do not want the
13656 	 * sequence number of the retransmitted packet, we want the sequence
13657 	 * number of the next unsent octet.  So, if there is no data (and no
13658 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13659 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13660 	 * one byte beyond the right edge of the window, so use snd_nxt in
13661 	 * that case, since we know we aren't doing a retransmission.
13662 	 * (retransmit and persist are mutually exclusive...)
13663 	 */
13664 	if (sack_rxmit == 0) {
13665 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13666 			/* New data (including new persists) */
13667 			th->th_seq = htonl(tp->snd_max);
13668 			bbr_seq = tp->snd_max;
13669 		} else if (flags & TH_SYN) {
13670 			/* Syn's always send from iss */
13671 			th->th_seq = htonl(tp->iss);
13672 			bbr_seq = tp->iss;
13673 		} else if (flags & TH_FIN) {
13674 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13675 				/*
13676 				 * If we sent the fin already its 1 minus
13677 				 * snd_max
13678 				 */
13679 				th->th_seq = (htonl(tp->snd_max - 1));
13680 				bbr_seq = (tp->snd_max - 1);
13681 			} else {
13682 				/* First time FIN use snd_max */
13683 				th->th_seq = htonl(tp->snd_max);
13684 				bbr_seq = tp->snd_max;
13685 			}
13686 		} else if (flags & TH_RST) {
13687 			/*
13688 			 * For a Reset send the last cum ack in sequence
13689 			 * (this like any other choice may still generate a
13690 			 * challenge ack, if a ack-update packet is in
13691 			 * flight).
13692 			 */
13693 			th->th_seq = htonl(tp->snd_una);
13694 			bbr_seq = tp->snd_una;
13695 		} else {
13696 			/*
13697 			 * len == 0 and not persist we use snd_max, sending
13698 			 * an ack unless we have sent the fin then its 1
13699 			 * minus.
13700 			 */
13701 			/*
13702 			 * XXXRRS Question if we are in persists and we have
13703 			 * nothing outstanding to send and we have not sent
13704 			 * a FIN, we will send an ACK. In such a case it
13705 			 * might be better to send (tp->snd_una - 1) which
13706 			 * would force the peer to ack.
13707 			 */
13708 			if (tp->t_flags & TF_SENTFIN) {
13709 				th->th_seq = htonl(tp->snd_max - 1);
13710 				bbr_seq = (tp->snd_max - 1);
13711 			} else {
13712 				th->th_seq = htonl(tp->snd_max);
13713 				bbr_seq = tp->snd_max;
13714 			}
13715 		}
13716 	} else {
13717 		/* All retransmits use the rsm to guide the send */
13718 		th->th_seq = htonl(rsm->r_start);
13719 		bbr_seq = rsm->r_start;
13720 	}
13721 	th->th_ack = htonl(tp->rcv_nxt);
13722 	if (optlen) {
13723 		bcopy(opt, th + 1, optlen);
13724 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13725 	}
13726 	th->th_flags = flags;
13727 	/*
13728 	 * Calculate receive window.  Don't shrink window, but avoid silly
13729 	 * window syndrome.
13730 	 */
13731 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13732 				  recwin < maxseg)))
13733 		recwin = 0;
13734 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13735 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13736 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13737 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13738 		recwin = TCP_MAXWIN << tp->rcv_scale;
13739 
13740 	/*
13741 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13742 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13743 	 * handled in syncache.
13744 	 */
13745 	if (flags & TH_SYN)
13746 		th->th_win = htons((u_short)
13747 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13748 	else
13749 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13750 	/*
13751 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13752 	 * window.  This may cause the remote transmitter to stall.  This
13753 	 * flag tells soreceive() to disable delayed acknowledgements when
13754 	 * draining the buffer.  This can occur if the receiver is
13755 	 * attempting to read more data than can be buffered prior to
13756 	 * transmitting on the connection.
13757 	 */
13758 	if (th->th_win == 0) {
13759 		tp->t_sndzerowin++;
13760 		tp->t_flags |= TF_RXWIN0SENT;
13761 	} else
13762 		tp->t_flags &= ~TF_RXWIN0SENT;
13763 	if (SEQ_GT(tp->snd_up, tp->snd_max)) {
13764 		th->th_urp = htons((u_short)(tp->snd_up - tp->snd_max));
13765 		th->th_flags |= TH_URG;
13766 	} else
13767 		/*
13768 		 * If no urgent pointer to send, then we pull the urgent
13769 		 * pointer to the left edge of the send window so that it
13770 		 * doesn't drift into the send window on sequence number
13771 		 * wraparound.
13772 		 */
13773 		tp->snd_up = tp->snd_una;	/* drag it along */
13774 
13775 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13776 	if (to.to_flags & TOF_SIGNATURE) {
13777 		/*
13778 		 * Calculate MD5 signature and put it into the place
13779 		 * determined before. NOTE: since TCP options buffer doesn't
13780 		 * point into mbuf's data, calculate offset and use it.
13781 		 */
13782 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13783 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13784 			/*
13785 			 * Do not send segment if the calculation of MD5
13786 			 * digest has failed.
13787 			 */
13788 			goto out;
13789 		}
13790 	}
13791 #endif
13792 
13793 	/*
13794 	 * Put TCP length in extended header, and then checksum extended
13795 	 * header and data.
13796 	 */
13797 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13798 #ifdef INET6
13799 	if (isipv6) {
13800 		/*
13801 		 * ip6_plen is not need to be filled now, and will be filled
13802 		 * in ip6_output.
13803 		 */
13804 #ifdef NETFLIX_TCPOUDP
13805 		if (tp->t_port) {
13806 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13807 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13808 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13809 			th->th_sum = htons(0);
13810 			UDPSTAT_INC(udps_opackets);
13811 		} else {
13812 #endif
13813 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13814 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13815 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13816 			    optlen + len, IPPROTO_TCP, 0);
13817 #ifdef NETFLIX_TCPOUDP
13818 		}
13819 #endif
13820 	}
13821 #endif
13822 #if defined(INET6) && defined(INET)
13823 	else
13824 #endif
13825 #ifdef INET
13826 	{
13827 #ifdef NETFLIX_TCPOUDP
13828 		if (tp->t_port) {
13829 			m->m_pkthdr.csum_flags = CSUM_UDP;
13830 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13831 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13832 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13833 			th->th_sum = htons(0);
13834 			UDPSTAT_INC(udps_opackets);
13835 		} else {
13836 #endif
13837 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13838 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13839 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13840 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13841 			    IPPROTO_TCP + len + optlen));
13842 #ifdef NETFLIX_TCPOUDP
13843 		}
13844 #endif
13845 		/* IP version must be set here for ipv4/ipv6 checking later */
13846 		KASSERT(ip->ip_v == IPVERSION,
13847 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13848 	}
13849 #endif
13850 
13851 	/*
13852 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13853 	 * header checksum is always provided. XXX: Fixme: This is currently
13854 	 * not the case for IPv6.
13855 	 */
13856 	if (tso || force_tso) {
13857 		KASSERT(force_tso || len > maxseg,
13858 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13859 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13860 		csum_flags |= CSUM_TSO;
13861 		m->m_pkthdr.tso_segsz = maxseg;
13862 	}
13863 	KASSERT(len + hdrlen == m_length(m, NULL),
13864 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13865 	    __func__, len, hdrlen, m_length(m, NULL)));
13866 
13867 #ifdef TCP_HHOOK
13868 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13869 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13870 #endif
13871 #ifdef TCPDEBUG
13872 	/*
13873 	 * Trace.
13874 	 */
13875 	if (so->so_options & SO_DEBUG) {
13876 		u_short save = 0;
13877 
13878 #ifdef INET6
13879 		if (!isipv6)
13880 #endif
13881 		{
13882 			save = ipov->ih_len;
13883 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13884 			      * (th->th_off << 2) */ );
13885 		}
13886 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13887 #ifdef INET6
13888 		if (!isipv6)
13889 #endif
13890 			ipov->ih_len = save;
13891 	}
13892 #endif				/* TCPDEBUG */
13893 
13894 	/* Log to the black box */
13895 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13896 		union tcp_log_stackspecific log;
13897 
13898 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13899 		/* Record info on type of transmission */
13900 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13901 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13902 		log.u_bbr.flex3 = maxseg;
13903 		log.u_bbr.flex4 = delay_calc;
13904 		/* Encode filled_all into the upper flex5 bit */
13905 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13906 		log.u_bbr.flex5 <<= 1;
13907 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13908 		log.u_bbr.flex5 <<= 29;
13909 		if (filled_all)
13910 			log.u_bbr.flex5 |= 0x80000000;
13911 		log.u_bbr.flex5 |= tp->t_maxseg;
13912 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13913 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13914 		/* lets poke in the low and the high here for debugging */
13915 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13916 		if (rsm || sack_rxmit) {
13917 			if (doing_tlp)
13918 				log.u_bbr.flex8 = 2;
13919 			else
13920 				log.u_bbr.flex8 = 1;
13921 		} else {
13922 			log.u_bbr.flex8 = 0;
13923 		}
13924 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13925 		    len, &log, false, NULL, NULL, 0, tv);
13926 	} else {
13927 		lgb = NULL;
13928 	}
13929 	/*
13930 	 * Fill in IP length and desired time to live and send to IP level.
13931 	 * There should be a better way to handle ttl and tos; we could keep
13932 	 * them in the template, but need a way to checksum without them.
13933 	 */
13934 	/*
13935 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13936 	 * because in6_cksum() need it.
13937 	 */
13938 #ifdef INET6
13939 	if (isipv6) {
13940 		/*
13941 		 * we separately set hoplimit for every segment, since the
13942 		 * user might want to change the value via setsockopt. Also,
13943 		 * desired default hop limit might be changed via Neighbor
13944 		 * Discovery.
13945 		 */
13946 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13947 
13948 		/*
13949 		 * Set the packet size here for the benefit of DTrace
13950 		 * probes. ip6_output() will set it properly; it's supposed
13951 		 * to include the option header lengths as well.
13952 		 */
13953 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13954 
13955 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13956 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13957 		else
13958 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13959 
13960 		if (tp->t_state == TCPS_SYN_SENT)
13961 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13962 
13963 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13964 		/* TODO: IPv6 IP6TOS_ECT bit on */
13965 		error = ip6_output(m, inp->in6p_outputopts,
13966 		    &inp->inp_route6,
13967 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13968 		    NULL, NULL, inp);
13969 
13970 		if (error == EMSGSIZE && inp->inp_route6.ro_rt != NULL)
13971 			mtu = inp->inp_route6.ro_rt->rt_mtu;
13972 	}
13973 #endif				/* INET6 */
13974 #if defined(INET) && defined(INET6)
13975 	else
13976 #endif
13977 #ifdef INET
13978 	{
13979 		ip->ip_len = htons(m->m_pkthdr.len);
13980 #ifdef INET6
13981 		if (isipv6)
13982 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13983 #endif				/* INET6 */
13984 		/*
13985 		 * If we do path MTU discovery, then we set DF on every
13986 		 * packet. This might not be the best thing to do according
13987 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13988 		 * the problem so it affects only the first tcp connection
13989 		 * with a host.
13990 		 *
13991 		 * NB: Don't set DF on small MTU/MSS to have a safe
13992 		 * fallback.
13993 		 */
13994 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13995 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13996 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13997 				ip->ip_off |= htons(IP_DF);
13998 			}
13999 		} else {
14000 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
14001 		}
14002 
14003 		if (tp->t_state == TCPS_SYN_SENT)
14004 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
14005 
14006 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
14007 
14008 		error = ip_output(m, inp->inp_options, &inp->inp_route,
14009 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
14010 		    inp);
14011 		if (error == EMSGSIZE && inp->inp_route.ro_rt != NULL)
14012 			mtu = inp->inp_route.ro_rt->rt_mtu;
14013 	}
14014 #endif				/* INET */
14015 out:
14016 
14017 	if (lgb) {
14018 		lgb->tlb_errno = error;
14019 		lgb = NULL;
14020 	}
14021 	/*
14022 	 * In transmit state, time the transmission and arrange for the
14023 	 * retransmit.  In persist state, just set snd_max.
14024 	 */
14025 	if (error == 0) {
14026 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
14027 		    (tp->t_flags & TF_SACK_PERMIT) &&
14028 		    tp->rcv_numsacks > 0)
14029 			tcp_clean_dsack_blocks(tp);
14030 		/* We sent an ack clear the bbr_segs_rcvd count */
14031 		bbr->output_error_seen = 0;
14032 		bbr->oerror_cnt = 0;
14033 		bbr->bbr_segs_rcvd = 0;
14034 		if (len == 0)
14035 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
14036 		else if (hw_tls) {
14037 			if (filled_all ||
14038 			    (len >= bbr->r_ctl.rc_pace_max_segs))
14039 				BBR_STAT_INC(bbr_meets_tso_thresh);
14040 			else {
14041 				if (doing_tlp) {
14042 					BBR_STAT_INC(bbr_miss_tlp);
14043 					bbr_log_type_hrdwtso(tp, bbr, len, 1, what_we_can);
14044 
14045 
14046 				} else if (rsm) {
14047 					BBR_STAT_INC(bbr_miss_retran);
14048 					bbr_log_type_hrdwtso(tp, bbr, len, 2, what_we_can);
14049 				} else if ((ctf_outstanding(tp) + bbr->r_ctl.rc_pace_max_segs) > sbavail(sb)) {
14050 					BBR_STAT_INC(bbr_miss_tso_app);
14051 					bbr_log_type_hrdwtso(tp, bbr, len, 3, what_we_can);
14052 				} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14053 								 bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_pace_max_segs) > tp->snd_cwnd) {
14054 					BBR_STAT_INC(bbr_miss_tso_cwnd);
14055 					bbr_log_type_hrdwtso(tp, bbr, len, 4, what_we_can);
14056 				} else if ((ctf_outstanding(tp) + bbr->r_ctl.rc_pace_max_segs) > tp->snd_wnd) {
14057 					BBR_STAT_INC(bbr_miss_tso_rwnd);
14058 					bbr_log_type_hrdwtso(tp, bbr, len, 5, what_we_can);
14059 				} else {
14060 					BBR_STAT_INC(bbr_miss_unknown);
14061 					bbr_log_type_hrdwtso(tp, bbr, len, 6, what_we_can);
14062 				}
14063 			}
14064 		}
14065 		/* Do accounting for new sends */
14066 		if ((len > 0) && (rsm == NULL)) {
14067 			int idx;
14068 			if (tp->snd_una == tp->snd_max) {
14069 				/*
14070 				 * Special case to match google, when
14071 				 * nothing is in flight the delivered
14072 				 * time does get updated to the current
14073 				 * time (see tcp_rate_bsd.c).
14074 				 */
14075 				bbr->r_ctl.rc_del_time = cts;
14076 			}
14077 			if (len >= maxseg) {
14078 				idx = (len / maxseg) + 3;
14079 				if (idx >= TCP_MSS_ACCT_ATIMER)
14080 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
14081 				else
14082 					counter_u64_add(bbr_out_size[idx], 1);
14083 			} else {
14084 				/* smaller than a MSS */
14085 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
14086 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
14087 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
14088 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
14089 			}
14090 		}
14091 	}
14092 	abandon = 0;
14093 	/*
14094 	 * We must do the send accounting before we log the output,
14095 	 * otherwise the state of the rsm could change and we account to the
14096 	 * wrong bucket.
14097 	 */
14098 	if (len > 0) {
14099 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
14100 		if (error == 0) {
14101 			if (tp->snd_una == tp->snd_max)
14102 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
14103 		}
14104 	}
14105 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
14106 	    cts, mb, &abandon, rsm, 0, sb);
14107 	if (abandon) {
14108 		/*
14109 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
14110 		 * sent we should hit this condition.
14111 		 */
14112 		return (0);
14113 	}
14114 	if (((tp->t_flags & TF_FORCEDATA) == 0) ||
14115 	    (bbr->rc_in_persist == 0)) {
14116 		/*
14117 		 * Advance snd_nxt over sequence space of this segment.
14118 		 */
14119 		if (error)
14120 			/* We don't log or do anything with errors */
14121 			goto skip_upd;
14122 
14123 		if (tp->snd_una == tp->snd_max &&
14124 		    (len || (flags & (TH_SYN | TH_FIN)))) {
14125 			/*
14126 			 * Update the time we just added data since none was
14127 			 * outstanding.
14128 			 */
14129 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
14130 			bbr->rc_tp->t_acktime  = ticks;
14131 		}
14132 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
14133 			if (flags & TH_SYN) {
14134 				tp->snd_max++;
14135 			}
14136 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
14137 				tp->snd_max++;
14138 				tp->t_flags |= TF_SENTFIN;
14139 			}
14140 		}
14141 		if (sack_rxmit == 0)
14142 			tp->snd_max += len;
14143 skip_upd:
14144 		if ((error == 0) && len)
14145 			tot_len += len;
14146 	} else {
14147 		/* Persists case */
14148 		int32_t xlen = len;
14149 
14150 		if (error)
14151 			goto nomore;
14152 
14153 		if (flags & TH_SYN)
14154 			++xlen;
14155 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
14156 			++xlen;
14157 			tp->t_flags |= TF_SENTFIN;
14158 		}
14159 		if (xlen && (tp->snd_una == tp->snd_max)) {
14160 			/*
14161 			 * Update the time we just added data since none was
14162 			 * outstanding.
14163 			 */
14164 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
14165 			bbr->rc_tp->t_acktime = ticks;
14166 		}
14167 		if (sack_rxmit == 0)
14168 			tp->snd_max += xlen;
14169 		tot_len += (len + optlen + ipoptlen);
14170 	}
14171 nomore:
14172 	if (error) {
14173 		/*
14174 		 * Failures do not advance the seq counter above. For the
14175 		 * case of ENOBUFS we will fall out and become ack-clocked.
14176 		 * capping the cwnd at the current flight.
14177 		 * Everything else will just have to retransmit with the timer
14178 		 * (no pacer).
14179 		 */
14180 		SOCKBUF_UNLOCK_ASSERT(sb);
14181 		BBR_STAT_INC(bbr_saw_oerr);
14182 		/* Clear all delay/early tracks */
14183 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
14184 		bbr->r_ctl.rc_agg_early = 0;
14185 		bbr->r_agg_early_set = 0;
14186 		bbr->output_error_seen = 1;
14187 		if (bbr->oerror_cnt < 0xf)
14188 			bbr->oerror_cnt++;
14189 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
14190 			/* drop the session */
14191 			tcp_set_inp_to_drop(inp, ENETDOWN);
14192 		}
14193 		switch (error) {
14194 		case ENOBUFS:
14195 			/*
14196 			 * Make this guy have to get ack's to send
14197 			 * more but lets make sure we don't
14198 			 * slam him below a T-O (1MSS).
14199 			 */
14200 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
14201 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14202 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
14203 				if (tp->snd_cwnd < maxseg)
14204 					tp->snd_cwnd = maxseg;
14205 			}
14206 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
14207 			BBR_STAT_INC(bbr_saw_enobuf);
14208 			if (bbr->bbr_hdrw_pacing)
14209 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
14210 			else
14211 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
14212 			/*
14213 			 * Here even in the enobuf's case we want to do our
14214 			 * state update. The reason being we may have been
14215 			 * called by the input function. If so we have had
14216 			 * things change.
14217 			 */
14218 			error = 0;
14219 			goto enobufs;
14220 		case EMSGSIZE:
14221 			/*
14222 			 * For some reason the interface we used initially
14223 			 * to send segments changed to another or lowered
14224 			 * its MTU. If TSO was active we either got an
14225 			 * interface without TSO capabilits or TSO was
14226 			 * turned off. If we obtained mtu from ip_output()
14227 			 * then update it and try again.
14228 			 */
14229 			/* Turn on tracing (or try to) */
14230 			{
14231 				int old_maxseg;
14232 
14233 				old_maxseg = tp->t_maxseg;
14234 				BBR_STAT_INC(bbr_saw_emsgsiz);
14235 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
14236 				if (mtu != 0)
14237 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
14238 				if (old_maxseg <= tp->t_maxseg) {
14239 					/* Huh it did not shrink? */
14240 					tp->t_maxseg = old_maxseg - 40;
14241 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
14242 				}
14243 				tp->t_flags &= ~TF_FORCEDATA;
14244 				/*
14245 				 * Nuke all other things that can interfere
14246 				 * with slot
14247 				 */
14248 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
14249 					slot = bbr_get_pacing_delay(bbr,
14250 					    bbr->r_ctl.rc_bbr_hptsi_gain,
14251 					    (tot_len + len), cts, 0);
14252 					if (slot < bbr_error_base_paceout)
14253 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
14254 				} else
14255 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
14256 				bbr->rc_output_starts_timer = 1;
14257 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
14258 				    tot_len);
14259 				return (error);
14260 			}
14261 		case EPERM:
14262 			tp->t_softerror = error;
14263 			/* Fall through */
14264 		case EHOSTDOWN:
14265 		case EHOSTUNREACH:
14266 		case ENETDOWN:
14267 		case ENETUNREACH:
14268 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
14269 				tp->t_softerror = error;
14270 			}
14271 			/* FALLTHROUGH */
14272 		default:
14273 			tp->t_flags &= ~TF_FORCEDATA;
14274 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
14275 			bbr->rc_output_starts_timer = 1;
14276 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
14277 			return (error);
14278 		}
14279 #ifdef NETFLIX_STATS
14280 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
14281 		    len &&
14282 		    (rsm == NULL) &&
14283 	    (bbr->rc_in_persist == 0)) {
14284 		tp->gput_seq = bbr_seq;
14285 		tp->gput_ack = bbr_seq +
14286 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
14287 		tp->gput_ts = cts;
14288 		tp->t_flags |= TF_GPUTINPROG;
14289 #endif
14290 	}
14291 	TCPSTAT_INC(tcps_sndtotal);
14292 	if ((bbr->bbr_hdw_pace_ena) &&
14293 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
14294 	    (bbr->rc_past_init_win) &&
14295 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
14296 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
14297 	    (inp->inp_route.ro_rt &&
14298 	     inp->inp_route.ro_rt->rt_ifp)) {
14299 		/*
14300 		 * We are past the initial window and
14301 		 * have at least one measurement so we
14302 		 * could use hardware pacing if its available.
14303 		 * We have an interface and we have not attempted
14304 		 * to setup hardware pacing, lets try to now.
14305 		 */
14306 		uint64_t rate_wanted;
14307 		int err = 0;
14308 
14309 		rate_wanted = bbr_get_hardware_rate(bbr);
14310 		bbr->bbr_attempt_hdwr_pace = 1;
14311 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
14312 						      inp->inp_route.ro_rt->rt_ifp,
14313 						      rate_wanted,
14314 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
14315 						      &err);
14316 		if (bbr->r_ctl.crte) {
14317 			bbr_type_log_hdwr_pacing(bbr,
14318 						 bbr->r_ctl.crte->ptbl->rs_ifp,
14319 						 rate_wanted,
14320 						 bbr->r_ctl.crte->rate,
14321 						 __LINE__, cts, err);
14322 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14323 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14324 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
14325 			bbr->bbr_hdrw_pacing = 1;
14326 			/* Now what is our gain status? */
14327 			if (bbr->r_ctl.crte->rate < rate_wanted) {
14328 				/* We have a problem */
14329 				bbr_setup_less_of_rate(bbr, cts,
14330 						       bbr->r_ctl.crte->rate, rate_wanted);
14331 			} else {
14332 				/* We are good */
14333 				bbr->gain_is_limited = 0;
14334 				bbr->skip_gain = 0;
14335 			}
14336 			tcp_bbr_tso_size_check(bbr, cts);
14337 		} else {
14338 			bbr_type_log_hdwr_pacing(bbr,
14339 						 inp->inp_route.ro_rt->rt_ifp,
14340 						 rate_wanted,
14341 						 0,
14342 						 __LINE__, cts, err);
14343 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14344 		}
14345 	}
14346 	if (bbr->bbr_hdrw_pacing) {
14347 		/*
14348 		 * Worry about cases where the route
14349 		 * changes or something happened that we
14350 		 * lost our hardware pacing possibly during
14351 		 * the last ip_output call.
14352 		 */
14353 		if (inp->inp_snd_tag == NULL) {
14354 			/* A change during ip output disabled hw pacing? */
14355 			bbr->bbr_hdrw_pacing = 0;
14356 		} else if ((inp->inp_route.ro_rt == NULL) ||
14357 		    (inp->inp_route.ro_rt->rt_ifp != inp->inp_snd_tag->ifp)) {
14358 			/*
14359 			 * We had an interface or route change,
14360 			 * detach from the current hdwr pacing
14361 			 * and setup to re-attempt next go
14362 			 * round.
14363 			 */
14364 			bbr->bbr_hdrw_pacing = 0;
14365 			bbr->bbr_attempt_hdwr_pace = 0;
14366 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14367 			tcp_bbr_tso_size_check(bbr, cts);
14368 		}
14369 	}
14370 	/*
14371 	 * Data sent (as far as we can tell). If this advertises a larger
14372 	 * window than any other segment, then remember the size of the
14373 	 * advertised window. Any pending ACK has now been sent.
14374 	 */
14375 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14376 		tp->rcv_adv = tp->rcv_nxt + recwin;
14377 
14378 	tp->last_ack_sent = tp->rcv_nxt;
14379 	if ((error == 0) &&
14380 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14381 	    (doing_tlp == 0) &&
14382 	    (tso == 0) &&
14383 	    (hw_tls == 0) &&
14384 	    (len > 0) &&
14385 	    ((flags & TH_RST) == 0) &&
14386 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14387 	    (bbr->rc_in_persist == 0) &&
14388 	    ((tp->t_flags & TF_FORCEDATA) == 0) &&
14389 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14390 		/*
14391 		 * For non-tso we need to goto again until we have sent out
14392 		 * enough data to match what we are hptsi out every hptsi
14393 		 * interval.
14394 		 */
14395 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14396 			/* Make sure snd_nxt is drug up */
14397 			tp->snd_nxt = tp->snd_max;
14398 		}
14399 		if (rsm != NULL) {
14400 			rsm = NULL;
14401 			goto skip_again;
14402 		}
14403 		rsm = NULL;
14404 		sack_rxmit = 0;
14405 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK | TF_FORCEDATA);
14406 		goto again;
14407 	}
14408 skip_again:
14409 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14410 		/*
14411 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14412 		 * what we have sent so far
14413 		 */
14414 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14415 		if (bbr->rc_no_pacing)
14416 			slot = 0;
14417 	}
14418 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK | TF_FORCEDATA);
14419 enobufs:
14420 	if (bbr->rc_use_google == 0)
14421 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14422 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14423 							bbr->r_ctl.rc_lost_bytes)));
14424 	bbr->rc_output_starts_timer = 1;
14425 	if (bbr->bbr_use_rack_cheat &&
14426 	    (more_to_rxt ||
14427 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14428 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14429 		if (slot > 1000)
14430 			slot = 1000;
14431 	}
14432 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14433 		/*
14434 		 * We don't change the tso size until some number of sends
14435 		 * to give the hardware commands time to get down
14436 		 * to the interface.
14437 		 */
14438 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14439 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14440 			bbr->hw_pacing_set = 1;
14441 			tcp_bbr_tso_size_check(bbr, cts);
14442 		}
14443 	}
14444 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14445 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14446 		/* Make sure snd_nxt is drug up */
14447 		tp->snd_nxt = tp->snd_max;
14448 	}
14449 	return (error);
14450 
14451 }
14452 
14453 /*
14454  * See bbr_output_wtime() for return values.
14455  */
14456 static int
14457 bbr_output(struct tcpcb *tp)
14458 {
14459 	int32_t ret;
14460 	struct timeval tv;
14461 	struct tcp_bbr *bbr;
14462 
14463 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14464 	INP_WLOCK_ASSERT(tp->t_inpcb);
14465 	(void)tcp_get_usecs(&tv);
14466 	ret = bbr_output_wtime(tp, &tv);
14467 	return (ret);
14468 }
14469 
14470 static void
14471 bbr_mtu_chg(struct tcpcb *tp)
14472 {
14473 	struct tcp_bbr *bbr;
14474 	struct bbr_sendmap *rsm, *frsm = NULL;
14475 	uint32_t maxseg;
14476 
14477 	/*
14478 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14479 	 * over the current size as SACK_PASS so a retransmit will occur.
14480 	 */
14481 
14482 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14483 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14484 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14485 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14486 		/* Don't mess with ones acked (by sack?) */
14487 		if (rsm->r_flags & BBR_ACKED)
14488 			continue;
14489 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14490 			/*
14491 			 * We mark sack-passed on all the previous large
14492 			 * sends we did. This will force them to retransmit.
14493 			 */
14494 			rsm->r_flags |= BBR_SACK_PASSED;
14495 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14496 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14497 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14498 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14499 				rsm->r_flags |= BBR_MARKED_LOST;
14500 			}
14501 			if (frsm == NULL)
14502 				frsm = rsm;
14503 		}
14504 	}
14505 	if (frsm) {
14506 		bbr->r_ctl.rc_resend = frsm;
14507 	}
14508 }
14509 
14510 /*
14511  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14512  * socket option arguments.  When it re-acquires the lock after the copy, it
14513  * has to revalidate that the connection is still valid for the socket
14514  * option.
14515  */
14516 static int
14517 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14518 		struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14519 {
14520 	int32_t error = 0, optval;
14521 
14522 	switch (sopt->sopt_name) {
14523 	case TCP_RACK_PACE_MAX_SEG:
14524 	case TCP_RACK_MIN_TO:
14525 	case TCP_RACK_REORD_THRESH:
14526 	case TCP_RACK_REORD_FADE:
14527 	case TCP_RACK_TLP_THRESH:
14528 	case TCP_RACK_PKT_DELAY:
14529 	case TCP_BBR_ALGORITHM:
14530 	case TCP_BBR_TSLIMITS:
14531 	case TCP_BBR_IWINTSO:
14532 	case TCP_BBR_RECFORCE:
14533 	case TCP_BBR_STARTUP_PG:
14534 	case TCP_BBR_DRAIN_PG:
14535 	case TCP_BBR_RWND_IS_APP:
14536 	case TCP_BBR_PROBE_RTT_INT:
14537 	case TCP_BBR_PROBE_RTT_GAIN:
14538 	case TCP_BBR_PROBE_RTT_LEN:
14539 	case TCP_BBR_STARTUP_LOSS_EXIT:
14540 	case TCP_BBR_USEDEL_RATE:
14541 	case TCP_BBR_MIN_RTO:
14542 	case TCP_BBR_MAX_RTO:
14543 	case TCP_BBR_PACE_PER_SEC:
14544 	case TCP_DELACK:
14545 	case TCP_BBR_PACE_DEL_TAR:
14546 	case TCP_BBR_SEND_IWND_IN_TSO:
14547 	case TCP_BBR_EXTRA_STATE:
14548 	case TCP_BBR_UTTER_MAX_TSO:
14549 	case TCP_BBR_MIN_TOPACEOUT:
14550 	case TCP_BBR_FLOOR_MIN_TSO:
14551 	case TCP_BBR_TSTMP_RAISES:
14552 	case TCP_BBR_POLICER_DETECT:
14553 	case TCP_BBR_USE_RACK_CHEAT:
14554 	case TCP_DATA_AFTER_CLOSE:
14555 	case TCP_BBR_HDWR_PACE:
14556 	case TCP_BBR_PACE_SEG_MAX:
14557 	case TCP_BBR_PACE_SEG_MIN:
14558 	case TCP_BBR_PACE_CROSS:
14559 	case TCP_BBR_PACE_OH:
14560 #ifdef NETFLIX_PEAKRATE
14561 	case TCP_MAXPEAKRATE:
14562 #endif
14563 	case TCP_BBR_TMR_PACE_OH:
14564 	case TCP_BBR_RACK_RTT_USE:
14565 	case TCP_BBR_RETRAN_WTSO:
14566 		break;
14567 	default:
14568 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14569 		break;
14570 	}
14571 	INP_WUNLOCK(inp);
14572 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14573 	if (error)
14574 		return (error);
14575 	INP_WLOCK(inp);
14576 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14577 		INP_WUNLOCK(inp);
14578 		return (ECONNRESET);
14579 	}
14580 	tp = intotcpcb(inp);
14581 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14582 	switch (sopt->sopt_name) {
14583 	case TCP_BBR_PACE_PER_SEC:
14584 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14585 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14586 		break;
14587 	case TCP_BBR_PACE_DEL_TAR:
14588 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14589 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14590 		break;
14591 	case TCP_BBR_PACE_SEG_MAX:
14592 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14593 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14594 		break;
14595 	case TCP_BBR_PACE_SEG_MIN:
14596 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14597 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14598 		break;
14599 	case TCP_BBR_PACE_CROSS:
14600 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14601 		bbr->r_ctl.bbr_cross_over = optval;
14602 		break;
14603 	case TCP_BBR_ALGORITHM:
14604 		BBR_OPTS_INC(tcp_bbr_algorithm);
14605 		if (optval && (bbr->rc_use_google == 0)) {
14606 			/* Turn on the google mode */
14607 			bbr_google_mode_on(bbr);
14608 			if ((optval > 3) && (optval < 500)) {
14609 				/*
14610 				 * Must be at least greater than .3%
14611 				 * and must be less than 50.0%.
14612 				 */
14613 				bbr->r_ctl.bbr_google_discount = optval;
14614 			}
14615 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14616 			/* Turn off the google mode */
14617 			bbr_google_mode_off(bbr);
14618 		}
14619 		break;
14620 	case TCP_BBR_TSLIMITS:
14621 		BBR_OPTS_INC(tcp_bbr_tslimits);
14622 		if (optval == 1)
14623 			bbr->rc_use_ts_limit = 1;
14624 		else if (optval == 0)
14625 			bbr->rc_use_ts_limit = 0;
14626 		else
14627 			error = EINVAL;
14628 		break;
14629 
14630 	case TCP_BBR_IWINTSO:
14631 		BBR_OPTS_INC(tcp_bbr_iwintso);
14632 		if ((optval >= 0) && (optval < 128)) {
14633 			uint32_t twin;
14634 
14635 			bbr->rc_init_win = optval;
14636 			twin = bbr_initial_cwnd(bbr, tp);
14637 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14638 				tp->snd_cwnd = twin;
14639 			else
14640 				error = EBUSY;
14641 		} else
14642 			error = EINVAL;
14643 		break;
14644 	case TCP_BBR_STARTUP_PG:
14645 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14646 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14647 			bbr->r_ctl.rc_startup_pg = optval;
14648 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14649 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14650 			}
14651 		} else
14652 			error = EINVAL;
14653 		break;
14654 	case TCP_BBR_DRAIN_PG:
14655 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14656 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14657 			bbr->r_ctl.rc_drain_pg = optval;
14658 		else
14659 			error = EINVAL;
14660 		break;
14661 	case TCP_BBR_PROBE_RTT_LEN:
14662 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14663 		if (optval <= 1)
14664 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14665 		else
14666 			error = EINVAL;
14667 		break;
14668 	case TCP_BBR_PROBE_RTT_GAIN:
14669 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14670 		if (optval <= BBR_UNIT)
14671 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14672 		else
14673 			error = EINVAL;
14674 		break;
14675 	case TCP_BBR_PROBE_RTT_INT:
14676 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14677 		if (optval > 1000)
14678 			bbr->r_ctl.rc_probertt_int = optval;
14679 		else
14680 			error = EINVAL;
14681 		break;
14682 	case TCP_BBR_MIN_TOPACEOUT:
14683 		BBR_OPTS_INC(tcp_bbr_topaceout);
14684 		if (optval == 0) {
14685 			bbr->no_pacing_until = 0;
14686 			bbr->rc_no_pacing = 0;
14687 		} else if (optval <= 0x00ff) {
14688 			bbr->no_pacing_until = optval;
14689 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14690 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14691 				/* Turn on no pacing */
14692 				bbr->rc_no_pacing = 1;
14693 			}
14694 		} else
14695 			error = EINVAL;
14696 		break;
14697 	case TCP_BBR_STARTUP_LOSS_EXIT:
14698 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14699 		bbr->rc_loss_exit = optval;
14700 		break;
14701 	case TCP_BBR_USEDEL_RATE:
14702 		error = EINVAL;
14703 		break;
14704 	case TCP_BBR_MIN_RTO:
14705 		BBR_OPTS_INC(tcp_bbr_min_rto);
14706 		bbr->r_ctl.rc_min_rto_ms = optval;
14707 		break;
14708 	case TCP_BBR_MAX_RTO:
14709 		BBR_OPTS_INC(tcp_bbr_max_rto);
14710 		bbr->rc_max_rto_sec = optval;
14711 		break;
14712 	case TCP_RACK_MIN_TO:
14713 		/* Minimum time between rack t-o's in ms */
14714 		BBR_OPTS_INC(tcp_rack_min_to);
14715 		bbr->r_ctl.rc_min_to = optval;
14716 		break;
14717 	case TCP_RACK_REORD_THRESH:
14718 		/* RACK reorder threshold (shift amount) */
14719 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14720 		if ((optval > 0) && (optval < 31))
14721 			bbr->r_ctl.rc_reorder_shift = optval;
14722 		else
14723 			error = EINVAL;
14724 		break;
14725 	case TCP_RACK_REORD_FADE:
14726 		/* Does reordering fade after ms time */
14727 		BBR_OPTS_INC(tcp_rack_reord_fade);
14728 		bbr->r_ctl.rc_reorder_fade = optval;
14729 		break;
14730 	case TCP_RACK_TLP_THRESH:
14731 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14732 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14733 		if (optval)
14734 			bbr->rc_tlp_threshold = optval;
14735 		else
14736 			error = EINVAL;
14737 		break;
14738 	case TCP_BBR_USE_RACK_CHEAT:
14739 		BBR_OPTS_INC(tcp_use_rackcheat);
14740 		if (bbr->rc_use_google) {
14741 			error = EINVAL;
14742 			break;
14743 		}
14744 		BBR_OPTS_INC(tcp_rack_cheat);
14745 		if (optval)
14746 			bbr->bbr_use_rack_cheat = 1;
14747 		else
14748 			bbr->bbr_use_rack_cheat = 0;
14749 		break;
14750 	case TCP_BBR_FLOOR_MIN_TSO:
14751 		BBR_OPTS_INC(tcp_utter_max_tso);
14752 		if ((optval >= 0) && (optval < 40))
14753 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14754 		else
14755 			error = EINVAL;
14756 		break;
14757 	case TCP_BBR_UTTER_MAX_TSO:
14758 		BBR_OPTS_INC(tcp_utter_max_tso);
14759 		if ((optval >= 0) && (optval < 0xffff))
14760 			bbr->r_ctl.bbr_utter_max = optval;
14761 		else
14762 			error = EINVAL;
14763 		break;
14764 
14765 	case TCP_BBR_EXTRA_STATE:
14766 		BBR_OPTS_INC(tcp_extra_state);
14767 		if (optval)
14768 			bbr->rc_use_idle_restart = 1;
14769 		else
14770 			bbr->rc_use_idle_restart = 0;
14771 		break;
14772 	case TCP_BBR_SEND_IWND_IN_TSO:
14773 		BBR_OPTS_INC(tcp_iwnd_tso);
14774 		if (optval) {
14775 			bbr->bbr_init_win_cheat = 1;
14776 			if (bbr->rc_past_init_win == 0) {
14777 				uint32_t cts;
14778 				cts = tcp_get_usecs(&bbr->rc_tv);
14779 				tcp_bbr_tso_size_check(bbr, cts);
14780 			}
14781 		} else
14782 			bbr->bbr_init_win_cheat = 0;
14783 		break;
14784 	case TCP_BBR_HDWR_PACE:
14785 		BBR_OPTS_INC(tcp_hdwr_pacing);
14786 		if (optval){
14787 			bbr->bbr_hdw_pace_ena = 1;
14788 			bbr->bbr_attempt_hdwr_pace = 0;
14789 		} else {
14790 			bbr->bbr_hdw_pace_ena = 0;
14791 #ifdef RATELIMIT
14792 			if (bbr->bbr_hdrw_pacing) {
14793 				bbr->bbr_hdrw_pacing = 0;
14794 				in_pcbdetach_txrtlmt(bbr->rc_inp);
14795 			}
14796 #endif
14797 		}
14798 		break;
14799 
14800 	case TCP_DELACK:
14801 		BBR_OPTS_INC(tcp_delack);
14802 		if (optval < 100) {
14803 			if (optval == 0) /* off */
14804 				tp->t_delayed_ack = 0;
14805 			else if (optval == 1) /* on which is 2 */
14806 				tp->t_delayed_ack = 2;
14807 			else /* higher than 2 and less than 100 */
14808 				tp->t_delayed_ack = optval;
14809 			if (tp->t_flags & TF_DELACK) {
14810 				tp->t_flags &= ~TF_DELACK;
14811 				tp->t_flags |= TF_ACKNOW;
14812 				bbr_output(tp);
14813 			}
14814 		} else
14815 			error = EINVAL;
14816 		break;
14817 	case TCP_RACK_PKT_DELAY:
14818 		/* RACK added ms i.e. rack-rtt + reord + N */
14819 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14820 		bbr->r_ctl.rc_pkt_delay = optval;
14821 		break;
14822 #ifdef NETFLIX_PEAKRATE
14823 	case TCP_MAXPEAKRATE:
14824 		BBR_OPTS_INC(tcp_maxpeak);
14825 		error = tcp_set_maxpeakrate(tp, optval);
14826 		if (!error)
14827 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14828 		break;
14829 #endif
14830 	case TCP_BBR_RETRAN_WTSO:
14831 		BBR_OPTS_INC(tcp_retran_wtso);
14832 		if (optval)
14833 			bbr->rc_resends_use_tso = 1;
14834 		else
14835 			bbr->rc_resends_use_tso = 0;
14836 		break;
14837 	case TCP_DATA_AFTER_CLOSE:
14838 		BBR_OPTS_INC(tcp_data_ac);
14839 		if (optval)
14840 			bbr->rc_allow_data_af_clo = 1;
14841 		else
14842 			bbr->rc_allow_data_af_clo = 0;
14843 		break;
14844 	case TCP_BBR_POLICER_DETECT:
14845 		BBR_OPTS_INC(tcp_policer_det);
14846 		if (bbr->rc_use_google == 0)
14847 			error = EINVAL;
14848 		else if (optval)
14849 			bbr->r_use_policer = 1;
14850 		else
14851 			bbr->r_use_policer = 0;
14852 		break;
14853 
14854 	case TCP_BBR_TSTMP_RAISES:
14855 		BBR_OPTS_INC(tcp_ts_raises);
14856 		if (optval)
14857 			bbr->ts_can_raise = 1;
14858 		else
14859 			bbr->ts_can_raise = 0;
14860 		break;
14861 	case TCP_BBR_TMR_PACE_OH:
14862 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14863 		if (bbr->rc_use_google) {
14864 			error = EINVAL;
14865 		} else {
14866 			if (optval)
14867 				bbr->r_ctl.rc_incr_tmrs = 1;
14868 			else
14869 				bbr->r_ctl.rc_incr_tmrs = 0;
14870 		}
14871 		break;
14872 	case TCP_BBR_PACE_OH:
14873 		BBR_OPTS_INC(tcp_pacing_oh);
14874 		if (bbr->rc_use_google) {
14875 			error = EINVAL;
14876 		} else {
14877 			if (optval > (BBR_INCL_TCP_OH|
14878 				      BBR_INCL_IP_OH|
14879 				      BBR_INCL_ENET_OH)) {
14880 				error = EINVAL;
14881 				break;
14882 			}
14883 			if (optval & BBR_INCL_TCP_OH)
14884 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14885 			else
14886 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14887 			if (optval & BBR_INCL_IP_OH)
14888 				bbr->r_ctl.rc_inc_ip_oh = 1;
14889 			else
14890 				bbr->r_ctl.rc_inc_ip_oh = 0;
14891 			if (optval & BBR_INCL_ENET_OH)
14892 				bbr->r_ctl.rc_inc_enet_oh = 1;
14893 			else
14894 				bbr->r_ctl.rc_inc_enet_oh = 0;
14895 		}
14896 		break;
14897 	default:
14898 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14899 		break;
14900 	}
14901 #ifdef NETFLIX_STATS
14902 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14903 #endif
14904 	INP_WUNLOCK(inp);
14905 	return (error);
14906 }
14907 
14908 /*
14909  * return 0 on success, error-num on failure
14910  */
14911 static int
14912 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14913     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14914 {
14915 	int32_t error, optval;
14916 
14917 	/*
14918 	 * Because all our options are either boolean or an int, we can just
14919 	 * pull everything into optval and then unlock and copy. If we ever
14920 	 * add a option that is not a int, then this will have quite an
14921 	 * impact to this routine.
14922 	 */
14923 	switch (sopt->sopt_name) {
14924 	case TCP_BBR_PACE_PER_SEC:
14925 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14926 		break;
14927 	case TCP_BBR_PACE_DEL_TAR:
14928 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14929 		break;
14930 	case TCP_BBR_PACE_SEG_MAX:
14931 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14932 		break;
14933 	case TCP_BBR_MIN_TOPACEOUT:
14934 		optval = bbr->no_pacing_until;
14935 		break;
14936 	case TCP_BBR_PACE_SEG_MIN:
14937 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14938 		break;
14939 	case TCP_BBR_PACE_CROSS:
14940 		optval = bbr->r_ctl.bbr_cross_over;
14941 		break;
14942 	case TCP_BBR_ALGORITHM:
14943 		optval = bbr->rc_use_google;
14944 		break;
14945 	case TCP_BBR_TSLIMITS:
14946 		optval = bbr->rc_use_ts_limit;
14947 		break;
14948 	case TCP_BBR_IWINTSO:
14949 		optval = bbr->rc_init_win;
14950 		break;
14951 	case TCP_BBR_STARTUP_PG:
14952 		optval = bbr->r_ctl.rc_startup_pg;
14953 		break;
14954 	case TCP_BBR_DRAIN_PG:
14955 		optval = bbr->r_ctl.rc_drain_pg;
14956 		break;
14957 	case TCP_BBR_PROBE_RTT_INT:
14958 		optval = bbr->r_ctl.rc_probertt_int;
14959 		break;
14960 	case TCP_BBR_PROBE_RTT_LEN:
14961 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14962 		break;
14963 	case TCP_BBR_PROBE_RTT_GAIN:
14964 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14965 		break;
14966 	case TCP_BBR_STARTUP_LOSS_EXIT:
14967 		optval = bbr->rc_loss_exit;
14968 		break;
14969 	case TCP_BBR_USEDEL_RATE:
14970 		error = EINVAL;
14971 		break;
14972 	case TCP_BBR_MIN_RTO:
14973 		optval = bbr->r_ctl.rc_min_rto_ms;
14974 		break;
14975 	case TCP_BBR_MAX_RTO:
14976 		optval = bbr->rc_max_rto_sec;
14977 		break;
14978 	case TCP_RACK_PACE_MAX_SEG:
14979 		/* Max segments in a pace */
14980 		optval = bbr->r_ctl.rc_pace_max_segs;
14981 		break;
14982 	case TCP_RACK_MIN_TO:
14983 		/* Minimum time between rack t-o's in ms */
14984 		optval = bbr->r_ctl.rc_min_to;
14985 		break;
14986 	case TCP_RACK_REORD_THRESH:
14987 		/* RACK reorder threshold (shift amount) */
14988 		optval = bbr->r_ctl.rc_reorder_shift;
14989 		break;
14990 	case TCP_RACK_REORD_FADE:
14991 		/* Does reordering fade after ms time */
14992 		optval = bbr->r_ctl.rc_reorder_fade;
14993 		break;
14994 	case TCP_BBR_USE_RACK_CHEAT:
14995 		/* Do we use the rack cheat for rxt */
14996 		optval = bbr->bbr_use_rack_cheat;
14997 		break;
14998 	case TCP_BBR_FLOOR_MIN_TSO:
14999 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
15000 		break;
15001 	case TCP_BBR_UTTER_MAX_TSO:
15002 		optval = bbr->r_ctl.bbr_utter_max;
15003 		break;
15004 	case TCP_BBR_SEND_IWND_IN_TSO:
15005 		/* Do we send TSO size segments initially */
15006 		optval = bbr->bbr_init_win_cheat;
15007 		break;
15008 	case TCP_BBR_EXTRA_STATE:
15009 		optval = bbr->rc_use_idle_restart;
15010 		break;
15011 	case TCP_RACK_TLP_THRESH:
15012 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
15013 		optval = bbr->rc_tlp_threshold;
15014 		break;
15015 	case TCP_RACK_PKT_DELAY:
15016 		/* RACK added ms i.e. rack-rtt + reord + N */
15017 		optval = bbr->r_ctl.rc_pkt_delay;
15018 		break;
15019 	case TCP_BBR_RETRAN_WTSO:
15020 		optval = bbr->rc_resends_use_tso;
15021 		break;
15022 	case TCP_DATA_AFTER_CLOSE:
15023 		optval = bbr->rc_allow_data_af_clo;
15024 		break;
15025 	case TCP_DELACK:
15026 		optval = tp->t_delayed_ack;
15027 		break;
15028 	case TCP_BBR_HDWR_PACE:
15029 		optval = bbr->bbr_hdw_pace_ena;
15030 		break;
15031 	case TCP_BBR_POLICER_DETECT:
15032 		optval = bbr->r_use_policer;
15033 		break;
15034 	case TCP_BBR_TSTMP_RAISES:
15035 		optval = bbr->ts_can_raise;
15036 		break;
15037 	case TCP_BBR_TMR_PACE_OH:
15038 		optval = bbr->r_ctl.rc_incr_tmrs;
15039 		break;
15040 	case TCP_BBR_PACE_OH:
15041 		optval = 0;
15042 		if (bbr->r_ctl.rc_inc_tcp_oh)
15043 			optval |= BBR_INCL_TCP_OH;
15044 		if (bbr->r_ctl.rc_inc_ip_oh)
15045 			optval |= BBR_INCL_IP_OH;
15046 		if (bbr->r_ctl.rc_inc_enet_oh)
15047 			optval |= BBR_INCL_ENET_OH;
15048 		break;
15049 	default:
15050 		return (tcp_default_ctloutput(so, sopt, inp, tp));
15051 		break;
15052 	}
15053 	INP_WUNLOCK(inp);
15054 	error = sooptcopyout(sopt, &optval, sizeof optval);
15055 	return (error);
15056 }
15057 
15058 /*
15059  * return 0 on success, error-num on failure
15060  */
15061 static int
15062 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
15063 {
15064 	int32_t error = EINVAL;
15065 	struct tcp_bbr *bbr;
15066 
15067 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
15068 	if (bbr == NULL) {
15069 		/* Huh? */
15070 		goto out;
15071 	}
15072 	if (sopt->sopt_dir == SOPT_SET) {
15073 		return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
15074 	} else if (sopt->sopt_dir == SOPT_GET) {
15075 		return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
15076 	}
15077 out:
15078 	INP_WUNLOCK(inp);
15079 	return (error);
15080 }
15081 
15082 
15083 struct tcp_function_block __tcp_bbr = {
15084 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
15085 	.tfb_tcp_output = bbr_output,
15086 	.tfb_do_queued_segments = ctf_do_queued_segments,
15087 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
15088 	.tfb_tcp_do_segment = bbr_do_segment,
15089 	.tfb_tcp_ctloutput = bbr_ctloutput,
15090 	.tfb_tcp_fb_init = bbr_init,
15091 	.tfb_tcp_fb_fini = bbr_fini,
15092 	.tfb_tcp_timer_stop_all = bbr_stopall,
15093 	.tfb_tcp_timer_activate = bbr_timer_activate,
15094 	.tfb_tcp_timer_active = bbr_timer_active,
15095 	.tfb_tcp_timer_stop = bbr_timer_stop,
15096 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
15097 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
15098 	.tfb_tcp_mtu_chg = bbr_mtu_chg
15099 };
15100 
15101 static const char *bbr_stack_names[] = {
15102 	__XSTRING(STACKNAME),
15103 #ifdef STACKALIAS
15104 	__XSTRING(STACKALIAS),
15105 #endif
15106 };
15107 
15108 static bool bbr_mod_inited = false;
15109 
15110 static int
15111 tcp_addbbr(module_t mod, int32_t type, void *data)
15112 {
15113 	int32_t err = 0;
15114 	int num_stacks;
15115 
15116 	switch (type) {
15117 	case MOD_LOAD:
15118 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
15119 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
15120 		    sizeof(struct bbr_sendmap),
15121 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
15122 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
15123 		    sizeof(struct tcp_bbr),
15124 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
15125 		sysctl_ctx_init(&bbr_sysctl_ctx);
15126 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
15127 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
15128 		    OID_AUTO,
15129 #ifdef STACKALIAS
15130 		    __XSTRING(STACKALIAS),
15131 #else
15132 		    __XSTRING(STACKNAME),
15133 #endif
15134 		    CTLFLAG_RW, 0,
15135 		    "");
15136 		if (bbr_sysctl_root == NULL) {
15137 			printf("Failed to add sysctl node\n");
15138 			err = EFAULT;
15139 			goto free_uma;
15140 		}
15141 		bbr_init_sysctls();
15142 		num_stacks = nitems(bbr_stack_names);
15143 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
15144 		    bbr_stack_names, &num_stacks);
15145 		if (err) {
15146 			printf("Failed to register %s stack name for "
15147 			    "%s module\n", bbr_stack_names[num_stacks],
15148 			    __XSTRING(MODNAME));
15149 			sysctl_ctx_free(&bbr_sysctl_ctx);
15150 	free_uma:
15151 			uma_zdestroy(bbr_zone);
15152 			uma_zdestroy(bbr_pcb_zone);
15153 			bbr_counter_destroy();
15154 			printf("Failed to register " __XSTRING(MODNAME)
15155 			    " module err:%d\n", err);
15156 			return (err);
15157 		}
15158 		tcp_lro_reg_mbufq();
15159 		bbr_mod_inited = true;
15160 		printf(__XSTRING(MODNAME) " is now available\n");
15161 		break;
15162 	case MOD_QUIESCE:
15163 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
15164 		break;
15165 	case MOD_UNLOAD:
15166 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
15167 		if (err == EBUSY)
15168 			break;
15169 		if (bbr_mod_inited) {
15170 			uma_zdestroy(bbr_zone);
15171 			uma_zdestroy(bbr_pcb_zone);
15172 			sysctl_ctx_free(&bbr_sysctl_ctx);
15173 			bbr_counter_destroy();
15174 			printf(__XSTRING(MODNAME)
15175 			    " is now no longer available\n");
15176 			bbr_mod_inited = false;
15177 		}
15178 		tcp_lro_dereg_mbufq();
15179 		err = 0;
15180 		break;
15181 	default:
15182 		return (EOPNOTSUPP);
15183 	}
15184 	return (err);
15185 }
15186 
15187 static moduledata_t tcp_bbr = {
15188 	.name = __XSTRING(MODNAME),
15189 	    .evhand = tcp_addbbr,
15190 	    .priv = 0
15191 };
15192 
15193 MODULE_VERSION(MODNAME, 1);
15194 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
15195 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
15196