xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision eea7c61590ae8968b3f1f609cf0bc8633222a94f)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include <sys/param.h>
42 #include <sys/arb.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #include <sys/libkern.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #ifdef STATS
57 #include <sys/qmath.h>
58 #include <sys/tree.h>
59 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
60 #endif
61 #include <sys/refcount.h>
62 #include <sys/queue.h>
63 #include <sys/eventhandler.h>
64 #include <sys/smp.h>
65 #include <sys/kthread.h>
66 #include <sys/lock.h>
67 #include <sys/mutex.h>
68 #include <sys/tim_filter.h>
69 #include <sys/time.h>
70 #include <sys/protosw.h>
71 #include <vm/uma.h>
72 #include <sys/kern_prefetch.h>
73 
74 #include <net/route.h>
75 #include <net/route/nhop.h>
76 #include <net/vnet.h>
77 
78 #define TCPSTATES		/* for logging */
79 
80 #include <netinet/in.h>
81 #include <netinet/in_kdtrace.h>
82 #include <netinet/in_pcb.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
85 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/ip6_var.h>
90 #define	TCPOUTFLAGS
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_hpts.h>
98 #include <netinet/cc/cc.h>
99 #include <netinet/tcp_log_buf.h>
100 #include <netinet/tcp_ratelimit.h>
101 #include <netinet/tcp_lro.h>
102 #ifdef TCPDEBUG
103 #include <netinet/tcp_debug.h>
104 #endif				/* TCPDEBUG */
105 #ifdef TCP_OFFLOAD
106 #include <netinet/tcp_offload.h>
107 #endif
108 #ifdef INET6
109 #include <netinet6/tcp6_var.h>
110 #endif
111 #include <netinet/tcp_fastopen.h>
112 
113 #include <netipsec/ipsec_support.h>
114 #include <net/if.h>
115 #include <net/if_var.h>
116 #include <net/ethernet.h>
117 
118 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif				/* IPSEC */
122 
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
125 #include <machine/in_cksum.h>
126 
127 #ifdef MAC
128 #include <security/mac/mac_framework.h>
129 #endif
130 
131 #include "sack_filter.h"
132 #include "tcp_bbr.h"
133 #include "rack_bbr_common.h"
134 uma_zone_t bbr_zone;
135 uma_zone_t bbr_pcb_zone;
136 
137 struct sysctl_ctx_list bbr_sysctl_ctx;
138 struct sysctl_oid *bbr_sysctl_root;
139 
140 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
141 	(tv) = (value); \
142 	if ((u_long)(tv) < (u_long)(tvmin)) \
143 		(tv) = (tvmin); \
144 	if ((u_long)(tv) > (u_long)(tvmax)) \
145 		(tv) = (tvmax); \
146 } while(0)
147 
148 /*#define BBR_INVARIANT 1*/
149 
150 /*
151  * initial window
152  */
153 static uint32_t bbr_def_init_win = 10;
154 static int32_t bbr_persist_min = 250000;	/* 250ms */
155 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
156 static int32_t bbr_cwnd_may_shrink = 0;
157 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
158 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
159 static int32_t bbr_hardware_pacing_limit = 8000;
160 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
161 static int32_t bbr_no_retran = 0;
162 
163 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
164 static int32_t bbr_max_net_error_cnt = 10;
165 /* Should the following be dynamic too -- loss wise */
166 static int32_t bbr_rtt_gain_thresh = 0;
167 /* Measurement controls */
168 static int32_t bbr_use_google_algo = 1;
169 static int32_t bbr_ts_limiting = 1;
170 static int32_t bbr_ts_can_raise = 0;
171 static int32_t bbr_do_red = 600;
172 static int32_t bbr_red_scale = 20000;
173 static int32_t bbr_red_mul = 1;
174 static int32_t bbr_red_div = 2;
175 static int32_t bbr_red_growth_restrict = 1;
176 static int32_t  bbr_target_is_bbunit = 0;
177 static int32_t bbr_drop_limit = 0;
178 /*
179  * How much gain do we need to see to
180  * stay in startup?
181  */
182 static int32_t bbr_marks_rxt_sack_passed = 0;
183 static int32_t bbr_start_exit = 25;
184 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
185 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
186 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
187 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
188 					 * if we go back ever to where the pacer
189 					 * has priority over timers.
190 					 */
191 static int32_t bbr_policer_call_from_rack_to = 0;
192 static int32_t bbr_policer_detection_enabled = 1;
193 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
194 						 * measurement before we are
195 						 * "good" note that 2 == 1.
196 						 * This is because we use a >
197 						 * comparison. This means if
198 						 * min_measure was 0, it takes
199 						 * num-measures > min(0) and
200 						 * you get 1 measurement and
201 						 * you are good. Set to 1, you
202 						 * have to have two
203 						 * measurements (this is done
204 						 * to prevent it from being ok
205 						 * to have no measurements). */
206 static int32_t bbr_no_pacing_until = 4;
207 
208 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
209 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
210 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
211 
212 static int32_t bbr_target_cwnd_mult_limit = 8;
213 /*
214  * bbr_cwnd_min_val is the number of
215  * segments we hold to in the RTT probe
216  * state typically 4.
217  */
218 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
219 
220 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
221 
222 static int32_t bbr_gain_to_target = 1;
223 static int32_t bbr_gain_gets_extra_too = 1;
224 /*
225  * bbr_high_gain is the 2/ln(2) value we need
226  * to double the sending rate in startup. This
227  * is used for both cwnd and hptsi gain's.
228  */
229 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
230 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
231 static int32_t bbr_use_lower_gain_in_startup = 1;
232 
233 /* thresholds for reduction on drain in sub-states/drain */
234 static int32_t bbr_drain_rtt = BBR_SRTT;
235 static int32_t bbr_drain_floor = 88;
236 static int32_t google_allow_early_out = 1;
237 static int32_t google_consider_lost = 1;
238 static int32_t bbr_drain_drop_mul = 4;
239 static int32_t bbr_drain_drop_div = 5;
240 static int32_t bbr_rand_ot = 50;
241 static int32_t bbr_can_force_probertt = 0;
242 static int32_t bbr_can_adjust_probertt = 1;
243 static int32_t bbr_probertt_sets_rtt = 0;
244 static int32_t bbr_can_use_ts_for_rtt = 1;
245 static int32_t bbr_is_ratio = 0;
246 static int32_t bbr_sub_drain_app_limit = 1;
247 static int32_t bbr_prtt_slam_cwnd = 1;
248 static int32_t bbr_sub_drain_slam_cwnd = 1;
249 static int32_t bbr_slam_cwnd_in_main_drain = 1;
250 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
251 					 * hold */
252 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
253 /*
254  * bbr_drain_gain is the reverse of the high_gain
255  * designed to drain back out the standing queue
256  * that is formed in startup by causing a larger
257  * hptsi gain and thus drainging the packets
258  * in flight.
259  */
260 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
261 static int32_t bbr_rttprobe_gain = 192;
262 
263 /*
264  * The cwnd_gain is the default cwnd gain applied when
265  * calculating a target cwnd. Note that the cwnd is
266  * a secondary factor in the way BBR works (see the
267  * paper and think about it, it will take some time).
268  * Basically the hptsi_gain spreads the packets out
269  * so you never get more than BDP to the peer even
270  * if the cwnd is high. In our implemenation that
271  * means in non-recovery/retransmission scenarios
272  * cwnd will never be reached by the flight-size.
273  */
274 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
275 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
276 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
277 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
278 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
279 static int32_t bbr_ignore_data_after_close = 1;
280 static int16_t bbr_hptsi_gain[] = {
281 	(BBR_UNIT *5 / 4),
282 	(BBR_UNIT * 3 / 4),
283 	BBR_UNIT,
284 	BBR_UNIT,
285 	BBR_UNIT,
286 	BBR_UNIT,
287 	BBR_UNIT,
288 	BBR_UNIT
289 };
290 int32_t bbr_use_rack_resend_cheat = 1;
291 int32_t bbr_sends_full_iwnd = 1;
292 
293 #define BBR_HPTSI_GAIN_MAX 8
294 /*
295  * The BBR module incorporates a number of
296  * TCP ideas that have been put out into the IETF
297  * over the last few years:
298  * - Yuchung Cheng's RACK TCP (for which its named) that
299  *    will stop us using the number of dup acks and instead
300  *    use time as the gage of when we retransmit.
301  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
302  *    of Dukkipati et.al.
303  * - Van Jacobson's et.al BBR.
304  *
305  * RACK depends on SACK, so if an endpoint arrives that
306  * cannot do SACK the state machine below will shuttle the
307  * connection back to using the "default" TCP stack that is
308  * in FreeBSD.
309  *
310  * To implement BBR and RACK the original TCP stack was first decomposed
311  * into a functional state machine with individual states
312  * for each of the possible TCP connection states. The do_segment
313  * functions role in life is to mandate the connection supports SACK
314  * initially and then assure that the RACK state matches the conenction
315  * state before calling the states do_segment function. Data processing
316  * of inbound segments also now happens in the hpts_do_segment in general
317  * with only one exception. This is so we can keep the connection on
318  * a single CPU.
319  *
320  * Each state is simplified due to the fact that the original do_segment
321  * has been decomposed and we *know* what state we are in (no
322  * switches on the state) and all tests for SACK are gone. This
323  * greatly simplifies what each state does.
324  *
325  * TCP output is also over-written with a new version since it
326  * must maintain the new rack scoreboard and has had hptsi
327  * integrated as a requirment. Still todo is to eliminate the
328  * use of the callout_() system and use the hpts for all
329  * timers as well.
330  */
331 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
332 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
333 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
334 						 * free list */
335 static int32_t bbr_tlp_thresh = 1;
336 static int32_t bbr_reorder_thresh = 2;
337 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
338 						 * 60,000,000 - 60 seconds */
339 static int32_t bbr_pkt_delay = 1000;
340 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
341 static int32_t bbr_incr_timers = 1;
342 
343 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
344 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
345 static int32_t bbr_exit_startup_at_loss = 1;
346 
347 /*
348  * bbr_lt_bw_ratio is 1/8th
349  * bbr_lt_bw_diff is  < 4 Kbit/sec
350  */
351 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
352 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
353 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
354 						 * the lt_bw for */
355 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
356 						 * lt_bw */
357 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
358 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
359 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
360 
361 static int32_t bbr_verbose_logging = 0;
362 /*
363  * Currently regular tcp has a rto_min of 30ms
364  * the backoff goes 12 times so that ends up
365  * being a total of 122.850 seconds before a
366  * connection is killed.
367  */
368 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
369 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
370 
371 /****************************************************/
372 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
373 /****************************************************/
374 /* What amount is our formula using to get TSO size */
375 static int32_t bbr_hptsi_per_second = 1000;
376 
377 /*
378  * For hptsi under bbr_cross_over connections what is delay
379  * target 7ms (in usec) combined with a seg_max of 2
380  * gets us close to identical google behavior in
381  * TSO size selection (possibly more 1MSS sends).
382  */
383 static int32_t bbr_hptsi_segments_delay_tar = 7000;
384 
385 /* Does pacing delay include overhead's in its time calculations? */
386 static int32_t bbr_include_enet_oh = 0;
387 static int32_t bbr_include_ip_oh = 1;
388 static int32_t bbr_include_tcp_oh = 1;
389 static int32_t bbr_google_discount = 10;
390 
391 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
392 static int32_t bbr_state_is_pkt_epoch = 0;
393 static int32_t bbr_state_drain_2_tar = 1;
394 /* What is the max the 0 - bbr_cross_over MBPS TSO target
395  * can reach using our delay target. Note that this
396  * value becomes the floor for the cross over
397  * algorithm.
398  */
399 static int32_t bbr_hptsi_segments_max = 2;
400 static int32_t bbr_hptsi_segments_floor = 1;
401 static int32_t bbr_hptsi_utter_max = 0;
402 
403 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
404 static int32_t bbr_hptsi_bytes_min = 1460;
405 static int32_t bbr_all_get_min = 0;
406 
407 /* Cross over point from algo-a to algo-b */
408 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
409 
410 /* Do we deal with our restart state? */
411 static int32_t bbr_uses_idle_restart = 0;
412 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
413 
414 /* Do we allow hardware pacing? */
415 static int32_t bbr_allow_hdwr_pacing = 0;
416 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
417 static int32_t bbr_hdwr_pace_floor = 1;
418 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
419 
420 /****************************************************/
421 static int32_t bbr_resends_use_tso = 0;
422 static int32_t bbr_tlp_max_resend = 2;
423 static int32_t bbr_sack_block_limit = 128;
424 
425 #define  BBR_MAX_STAT 19
426 counter_u64_t bbr_state_time[BBR_MAX_STAT];
427 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
428 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
429 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
430 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
431 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
432 counter_u64_t bbr_flows_whdwr_pacing;
433 counter_u64_t bbr_flows_nohdwr_pacing;
434 
435 counter_u64_t bbr_nohdwr_pacing_enobuf;
436 counter_u64_t bbr_hdwr_pacing_enobuf;
437 
438 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
439 
440 /*
441  * Static defintions we need for forward declarations.
442  */
443 static uint32_t
444 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
445     uint32_t useconds_time, uint64_t bw);
446 static uint32_t
447 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
448 static void
449      bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
450 static void
451 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
452 static void
453 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
454 		    int dolog);
455 static uint32_t
456 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
457 static void
458 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
459 		 int32_t pkt_epoch, uint32_t losses);
460 static uint32_t
461 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm);
462 static uint32_t bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
463 static uint32_t
464 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
465     struct bbr_sendmap *rsm, uint32_t srtt,
466     uint32_t cts);
467 static void
468 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
469     int32_t line);
470 static void
471      bbr_set_state_target(struct tcp_bbr *bbr, int line);
472 static void
473      bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
474 
475 static void
476      bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line);
477 
478 static void
479      tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
480 
481 static void
482      bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
483 
484 static void
485      bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied, uint32_t rtt,
486 			 uint32_t line, uint8_t is_start, uint16_t set);
487 
488 static struct bbr_sendmap *
489 	    bbr_find_lowest_rsm(struct tcp_bbr *bbr);
490 static __inline uint32_t
491 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
492 static void
493      bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which);
494 
495 static void
496 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
497     uint32_t thresh, uint32_t to);
498 static void
499      bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
500 
501 static void
502 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
503     uint32_t del_by, uint32_t cts, uint32_t sloton, uint32_t prev_delay);
504 
505 static void
506 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr,
507     uint32_t cts, int32_t line);
508 static void
509      bbr_stop_all_timers(struct tcpcb *tp);
510 static void
511      bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
512 static void
513      bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
514 static void
515      bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
516 
517 static void
518 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
519     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod);
520 
521 static int
522 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp,
523     struct tcpcb *tp);
524 
525 static inline uint8_t
526 bbr_state_val(struct tcp_bbr *bbr)
527 {
528 	return(bbr->rc_bbr_substate);
529 }
530 
531 static inline uint32_t
532 get_min_cwnd(struct tcp_bbr *bbr)
533 {
534 	int mss;
535 
536 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
537 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
538 		return (bbr_cwnd_min_val_hs * mss);
539 	else
540 		return (bbr_cwnd_min_val * mss);
541 }
542 
543 static uint32_t
544 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
545 {
546 	uint64_t srtt, var;
547 	uint64_t ret_val;
548 
549 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
550 	if (tp->t_srtt == 0) {
551 		srtt = (uint64_t)BBR_INITIAL_RTO;
552 		var = 0;
553 	} else {
554 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
555 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
556 	}
557 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
558 	    bbr_persist_min, bbr_persist_max);
559 	return ((uint32_t)ret_val);
560 }
561 
562 static uint32_t
563 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
564 {
565 	/*
566 	 * Start the FR timer, we do this based on getting the first one in
567 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
568 	 * events we need to stop the running timer (if its running) before
569 	 * starting the new one.
570 	 */
571 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
572 	int32_t idx;
573 	int32_t is_tlp_timer = 0;
574 	struct bbr_sendmap *rsm;
575 
576 	if (bbr->rc_all_timers_stopped) {
577 		/* All timers have been stopped none are to run */
578 		return (0);
579 	}
580 	if (bbr->rc_in_persist) {
581 		/* We can't start any timer in persists */
582 		return (bbr_get_persists_timer_val(tp, bbr));
583 	}
584 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
585 	if ((rsm == NULL) ||
586 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
587 	    (tp->t_state < TCPS_ESTABLISHED)) {
588 		/* Nothing on the send map */
589 activate_rxt:
590 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
591 			uint64_t tov;
592 
593 			time_since_sent = 0;
594 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
595 			if (rsm) {
596 				idx = rsm->r_rtr_cnt - 1;
597 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
598 					tstmp_touse = rsm->r_tim_lastsent[idx];
599 				else
600 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
601 				if (TSTMP_GT(tstmp_touse, cts))
602 				    time_since_sent = cts - tstmp_touse;
603 			}
604 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
605 			if (tp->t_srtt == 0)
606 				tov = BBR_INITIAL_RTO;
607 			else
608 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
609 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
610 			if (tp->t_rxtshift)
611 				tov *= tcp_backoff[tp->t_rxtshift];
612 			if (tov > time_since_sent)
613 				tov -= time_since_sent;
614 			else
615 				tov = bbr->r_ctl.rc_min_to;
616 			TCPT_RANGESET_NOSLOP(to, tov,
617 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
618 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
619 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
620 			return (to);
621 		}
622 		return (0);
623 	}
624 	if (rsm->r_flags & BBR_ACKED) {
625 		rsm = bbr_find_lowest_rsm(bbr);
626 		if (rsm == NULL) {
627 			/* No lowest? */
628 			goto activate_rxt;
629 		}
630 	}
631 	/* Convert from ms to usecs */
632 	if (rsm->r_flags & BBR_SACK_PASSED) {
633 		if ((tp->t_flags & TF_SENTFIN) &&
634 		    ((tp->snd_max - tp->snd_una) == 1) &&
635 		    (rsm->r_flags & BBR_HAS_FIN)) {
636 			/*
637 			 * We don't start a bbr rack timer if all we have is
638 			 * a FIN outstanding.
639 			 */
640 			goto activate_rxt;
641 		}
642 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
643 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
644 		idx = rsm->r_rtr_cnt - 1;
645 		exp = rsm->r_tim_lastsent[idx] + thresh;
646 		if (SEQ_GEQ(exp, cts)) {
647 			to = exp - cts;
648 			if (to < bbr->r_ctl.rc_min_to) {
649 				to = bbr->r_ctl.rc_min_to;
650 			}
651 		} else {
652 			to = bbr->r_ctl.rc_min_to;
653 		}
654 	} else {
655 		/* Ok we need to do a TLP not RACK */
656 		if (bbr->rc_tlp_in_progress != 0) {
657 			/*
658 			 * The previous send was a TLP.
659 			 */
660 			goto activate_rxt;
661 		}
662 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
663 		if (rsm == NULL) {
664 			/* We found no rsm to TLP with. */
665 			goto activate_rxt;
666 		}
667 		if (rsm->r_flags & BBR_HAS_FIN) {
668 			/* If its a FIN we don't do TLP */
669 			rsm = NULL;
670 			goto activate_rxt;
671 		}
672 		time_since_sent = 0;
673 		idx = rsm->r_rtr_cnt - 1;
674 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
675 			tstmp_touse = rsm->r_tim_lastsent[idx];
676 		else
677 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
678 		if (TSTMP_GT(tstmp_touse, cts))
679 		    time_since_sent = cts - tstmp_touse;
680 		is_tlp_timer = 1;
681 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
682 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
683 		if (thresh > time_since_sent)
684 			to = thresh - time_since_sent;
685 		else
686 			to = bbr->r_ctl.rc_min_to;
687 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
688 			/*
689 			 * If the TLP time works out to larger than the max
690 			 * RTO lets not do TLP.. just RTO.
691 			 */
692 			goto activate_rxt;
693 		}
694 		if ((bbr->rc_tlp_rtx_out == 1) &&
695 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
696 			/*
697 			 * Second retransmit of the same TLP
698 			 * lets not.
699 			 */
700 			bbr->rc_tlp_rtx_out = 0;
701 			goto activate_rxt;
702 		}
703 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
704 			/*
705 			 * The tail is no longer the last one I did a probe
706 			 * on
707 			 */
708 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
709 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
710 		}
711 	}
712 	if (is_tlp_timer == 0) {
713 		BBR_STAT_INC(bbr_to_arm_rack);
714 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
715 	} else {
716 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
717 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
718 			/*
719 			 * We have exceeded how many times we can retran the
720 			 * current TLP timer, switch to the RTO timer.
721 			 */
722 			goto activate_rxt;
723 		} else {
724 			BBR_STAT_INC(bbr_to_arm_tlp);
725 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
726 		}
727 	}
728 	return (to);
729 }
730 
731 static inline int32_t
732 bbr_minseg(struct tcp_bbr *bbr)
733 {
734 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
735 }
736 
737 static void
738 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
739 {
740 	struct inpcb *inp;
741 	struct hpts_diag diag;
742 	uint32_t delayed_ack = 0;
743 	uint32_t left = 0;
744 	uint32_t hpts_timeout;
745 	uint8_t stopped;
746 	int32_t delay_calc = 0;
747 	uint32_t prev_delay = 0;
748 
749 	inp = tp->t_inpcb;
750 	if (tcp_in_hpts(inp)) {
751 		/* A previous call is already set up */
752 		return;
753 	}
754 	if ((tp->t_state == TCPS_CLOSED) ||
755 	    (tp->t_state == TCPS_LISTEN)) {
756 		return;
757 	}
758 	stopped = bbr->rc_tmr_stopped;
759 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
760 		left = bbr->r_ctl.rc_timer_exp - cts;
761 	}
762 	bbr->r_ctl.rc_hpts_flags = 0;
763 	bbr->r_ctl.rc_timer_exp = 0;
764 	prev_delay = bbr->r_ctl.rc_last_delay_val;
765 	if (bbr->r_ctl.rc_last_delay_val &&
766 	    (slot == 0)) {
767 		/*
768 		 * If a previous pacer delay was in place we
769 		 * are not coming from the output side (where
770 		 * we calculate a delay, more likely a timer).
771 		 */
772 		slot = bbr->r_ctl.rc_last_delay_val;
773 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
774 			/* Compensate for time passed  */
775 			delay_calc = cts - bbr->rc_pacer_started;
776 			if (delay_calc <= slot)
777 				slot -= delay_calc;
778 		}
779 	}
780 	/* Do we have early to make up for by pushing out the pacing time? */
781 	if (bbr->r_agg_early_set) {
782 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
783 		slot += bbr->r_ctl.rc_agg_early;
784 		bbr->r_ctl.rc_agg_early = 0;
785 		bbr->r_agg_early_set = 0;
786 	}
787 	/* Are we running a total debt that needs to be compensated for? */
788 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
789 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
790 			/* We nuke the delay */
791 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
792 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
793 		} else {
794 			/* We nuke some of the delay, put in a minimal 100usecs  */
795 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
796 			bbr->r_ctl.rc_last_delay_val = slot = 100;
797 		}
798 	}
799 	bbr->r_ctl.rc_last_delay_val = slot;
800 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
801 	if (tp->t_flags & TF_DELACK) {
802 		if (bbr->rc_in_persist == 0) {
803 			delayed_ack = bbr_delack_time;
804 		} else {
805 			/*
806 			 * We are in persists and have
807 			 * gotten a new data element.
808 			 */
809 			if (hpts_timeout > bbr_delack_time) {
810 				/*
811 				 * Lets make the persists timer (which acks)
812 				 * be the smaller of hpts_timeout and bbr_delack_time.
813 				 */
814 				hpts_timeout = bbr_delack_time;
815 			}
816 		}
817 	}
818 	if (delayed_ack &&
819 	    ((hpts_timeout == 0) ||
820 	     (delayed_ack < hpts_timeout))) {
821 		/* We need a Delayed ack timer */
822 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
823 		hpts_timeout = delayed_ack;
824 	}
825 	if (slot) {
826 		/* Mark that we have a pacing timer up */
827 		BBR_STAT_INC(bbr_paced_segments);
828 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
829 	}
830 	/*
831 	 * If no timers are going to run and we will fall off thfe hptsi
832 	 * wheel, we resort to a keep-alive timer if its configured.
833 	 */
834 	if ((hpts_timeout == 0) &&
835 	    (slot == 0)) {
836 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
837 		    (tp->t_state <= TCPS_CLOSING)) {
838 			/*
839 			 * Ok we have no timer (persists, rack, tlp, rxt  or
840 			 * del-ack), we don't have segments being paced. So
841 			 * all that is left is the keepalive timer.
842 			 */
843 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
844 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
845 			} else {
846 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
847 			}
848 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
849 		}
850 	}
851 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
852 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
853 		/*
854 		 * RACK, TLP, persists and RXT timers all are restartable
855 		 * based on actions input .. i.e we received a packet (ack
856 		 * or sack) and that changes things (rw, or snd_una etc).
857 		 * Thus we can restart them with a new value. For
858 		 * keep-alive, delayed_ack we keep track of what was left
859 		 * and restart the timer with a smaller value.
860 		 */
861 		if (left < hpts_timeout)
862 			hpts_timeout = left;
863 	}
864 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
865 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
866 		/*
867 		 * If configured to do so, and the timer is either
868 		 * the TLP or RXT timer, we need to increase the timeout
869 		 * by the pacing time. Consider the bottleneck at my
870 		 * machine as an example, we are sending something
871 		 * to start a TLP on. The last packet won't be emitted
872 		 * fully until the pacing time (the bottleneck will hold
873 		 * the data in place). Once the packet is emitted that
874 		 * is when we want to start waiting for the TLP. This
875 		 * is most evident with hardware pacing (where the nic
876 		 * is holding the packet(s) before emitting). But it
877 		 * can also show up in the network so we do it for all
878 		 * cases. Technically we would take off one packet from
879 		 * this extra delay but this is easier and being more
880 		 * conservative is probably better.
881 		 */
882 		hpts_timeout += slot;
883 	}
884 	if (hpts_timeout) {
885 		/*
886 		 * Hack alert for now we can't time-out over 2147 seconds (a
887 		 * bit more than 35min)
888 		 */
889 		if (hpts_timeout > 0x7ffffffe)
890 			hpts_timeout = 0x7ffffffe;
891 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
892 	} else
893 		bbr->r_ctl.rc_timer_exp = 0;
894 	if ((slot) &&
895 	    (bbr->rc_use_google ||
896 	     bbr->output_error_seen ||
897 	     (slot <= hpts_timeout))  ) {
898 		/*
899 		 * Tell LRO that it can queue packets while
900 		 * we pace.
901 		 */
902 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
903 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
904 		    (bbr->rc_cwnd_limited == 0)) {
905 			/*
906 			 * If we are not cwnd limited and we
907 			 * are running a rack timer we put on
908 			 * the do not disturbe even for sack.
909 			 */
910 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
911 		} else
912 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
913 		bbr->rc_pacer_started = cts;
914 
915 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
916 					   __LINE__, &diag);
917 		bbr->rc_timer_first = 0;
918 		bbr->bbr_timer_src = frm;
919 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
920 		bbr_log_hpts_diag(bbr, cts, &diag);
921 	} else if (hpts_timeout) {
922 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
923 					   __LINE__, &diag);
924 		/*
925 		 * We add the flag here as well if the slot is set,
926 		 * since hpts will call in to clear the queue first before
927 		 * calling the output routine (which does our timers).
928 		 * We don't want to set the flag if its just a timer
929 		 * else the arrival of data might (that causes us
930 		 * to send more) might get delayed. Imagine being
931 		 * on a keep-alive timer and a request comes in for
932 		 * more data.
933 		 */
934 		if (slot)
935 			bbr->rc_pacer_started = cts;
936 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
937 		    (bbr->rc_cwnd_limited == 0)) {
938 			/*
939 			 * For a rack timer, don't wake us even
940 			 * if a sack arrives as long as we are
941 			 * not cwnd limited.
942 			 */
943 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
944 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
945 		} else {
946 			/* All other timers wake us up */
947 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
948 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
949 		}
950 		bbr->bbr_timer_src = frm;
951 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
952 		bbr_log_hpts_diag(bbr, cts, &diag);
953 		bbr->rc_timer_first = 1;
954 	}
955 	bbr->rc_tmr_stopped = 0;
956 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
957 }
958 
959 static void
960 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
961 {
962 	/*
963 	 * We received an ack, and then did not call send or were bounced
964 	 * out due to the hpts was running. Now a timer is up as well, is it
965 	 * the right timer?
966 	 */
967 	struct inpcb *inp;
968 	struct bbr_sendmap *rsm;
969 	uint32_t hpts_timeout;
970 	int tmr_up;
971 
972 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
973 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
974 		return;
975 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
976 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
977 	    (tmr_up == PACE_TMR_RXT)) {
978 		/* Should be an RXT */
979 		return;
980 	}
981 	inp = bbr->rc_inp;
982 	if (rsm == NULL) {
983 		/* Nothing outstanding? */
984 		if (tp->t_flags & TF_DELACK) {
985 			if (tmr_up == PACE_TMR_DELACK)
986 				/*
987 				 * We are supposed to have delayed ack up
988 				 * and we do
989 				 */
990 				return;
991 		} else if (sbavail(&inp->inp_socket->so_snd) &&
992 		    (tmr_up == PACE_TMR_RXT)) {
993 			/*
994 			 * if we hit enobufs then we would expect the
995 			 * possiblity of nothing outstanding and the RXT up
996 			 * (and the hptsi timer).
997 			 */
998 			return;
999 		} else if (((V_tcp_always_keepalive ||
1000 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
1001 			    (tp->t_state <= TCPS_CLOSING)) &&
1002 			    (tmr_up == PACE_TMR_KEEP) &&
1003 		    (tp->snd_max == tp->snd_una)) {
1004 			/* We should have keep alive up and we do */
1005 			return;
1006 		}
1007 	}
1008 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1009 		if ((tp->t_flags & TF_SENTFIN) &&
1010 		    ((tp->snd_max - tp->snd_una) == 1) &&
1011 		    (rsm->r_flags & BBR_HAS_FIN)) {
1012 			/* needs to be a RXT */
1013 			if (tmr_up == PACE_TMR_RXT)
1014 				return;
1015 			else
1016 				goto wrong_timer;
1017 		} else if (tmr_up == PACE_TMR_RACK)
1018 			return;
1019 		else
1020 			goto wrong_timer;
1021 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1022 		/* Rack timer has priority if we have data out */
1023 		return;
1024 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1025 		    ((tmr_up == PACE_TMR_TLP) ||
1026 	    (tmr_up == PACE_TMR_RXT))) {
1027 		/*
1028 		 * Either a TLP or RXT is fine if no sack-passed is in place
1029 		 * and data is outstanding.
1030 		 */
1031 		return;
1032 	} else if (tmr_up == PACE_TMR_DELACK) {
1033 		/*
1034 		 * If the delayed ack was going to go off before the
1035 		 * rtx/tlp/rack timer were going to expire, then that would
1036 		 * be the timer in control. Note we don't check the time
1037 		 * here trusting the code is correct.
1038 		 */
1039 		return;
1040 	}
1041 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1042 	    ((tmr_up == PACE_TMR_RXT) ||
1043 	     (tmr_up == PACE_TMR_TLP) ||
1044 	     (tmr_up == PACE_TMR_RACK))) {
1045 		/*
1046 		 * We have outstanding data and
1047 		 * we *do* have a RACK, TLP or RXT
1048 		 * timer running. We won't restart
1049 		 * anything here since thats probably ok we
1050 		 * will get called with some timer here shortly.
1051 		 */
1052 		return;
1053 	}
1054 	/*
1055 	 * Ok the timer originally started is not what we want now. We will
1056 	 * force the hpts to be stopped if any, and restart with the slot
1057 	 * set to what was in the saved slot.
1058 	 */
1059 wrong_timer:
1060 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1061 		if (tcp_in_hpts(inp))
1062 			tcp_hpts_remove(inp);
1063 		bbr_timer_cancel(bbr, __LINE__, cts);
1064 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1065 		    0);
1066 	} else {
1067 		/*
1068 		 * Output is hptsi so we just need to switch the type of
1069 		 * timer. We don't bother with keep-alive, since when we
1070 		 * jump through the output, it will start the keep-alive if
1071 		 * nothing is sent.
1072 		 *
1073 		 * We only need a delayed-ack added and or the hpts_timeout.
1074 		 */
1075 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1076 		if (tp->t_flags & TF_DELACK) {
1077 			if (hpts_timeout == 0) {
1078 				hpts_timeout = bbr_delack_time;
1079 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1080 			}
1081 			else if (hpts_timeout > bbr_delack_time) {
1082 				hpts_timeout = bbr_delack_time;
1083 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1084 			}
1085 		}
1086 		if (hpts_timeout) {
1087 			if (hpts_timeout > 0x7ffffffe)
1088 				hpts_timeout = 0x7ffffffe;
1089 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1090 		}
1091 	}
1092 }
1093 
1094 int32_t bbr_clear_lost = 0;
1095 
1096 /*
1097  * Considers the two time values now (cts) and earlier.
1098  * If cts is smaller than earlier, we could have
1099  * had a sequence wrap (our counter wraps every
1100  * 70 min or so) or it could be just clock skew
1101  * getting us two differnt time values. Clock skew
1102  * will show up within 10ms or so. So in such
1103  * a case (where cts is behind earlier time by
1104  * less than 10ms) we return 0. Otherwise we
1105  * return the true difference between them.
1106  */
1107 static inline uint32_t
1108 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1109 	/*
1110 	 * Given two timestamps, the current time stamp cts, and some other
1111 	 * time-stamp taken in theory earlier return the difference. The
1112 	 * trick is here sometimes locking will get the other timestamp
1113 	 * after the cts. If this occurs we need to return 0.
1114 	 */
1115 	if (TSTMP_GEQ(cts, earlier_time))
1116 		return (cts - earlier_time);
1117 	/*
1118 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1119 	 * If its more than 10ms difference then we had a time wrap. Else
1120 	 * its just the normal locking foo. I wonder if we should not go to
1121 	 * 64bit TS and get rid of this issue.
1122 	 */
1123 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1124 		return (0);
1125 	/*
1126 	 * Ok the time must have wrapped. So we need to answer a large
1127 	 * amount of time, which the normal subtraction should do.
1128 	 */
1129 	return (cts - earlier_time);
1130 }
1131 
1132 static int
1133 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1134 {
1135 	uint32_t stat;
1136 	int32_t error;
1137 
1138 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1139 	if (error || req->newptr == NULL)
1140 		return error;
1141 
1142 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1143 	if (error)
1144 		return (error);
1145 	if (stat == 1) {
1146 #ifdef BBR_INVARIANTS
1147 		printf("Clearing BBR lost counters\n");
1148 #endif
1149 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1150 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1151 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1152 	} else if (stat == 2) {
1153 #ifdef BBR_INVARIANTS
1154 		printf("Clearing BBR option counters\n");
1155 #endif
1156 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1157 	} else if (stat == 3) {
1158 #ifdef BBR_INVARIANTS
1159 		printf("Clearing BBR stats counters\n");
1160 #endif
1161 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1162 	} else if (stat == 4) {
1163 #ifdef BBR_INVARIANTS
1164 		printf("Clearing BBR out-size counters\n");
1165 #endif
1166 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1167 	}
1168 	bbr_clear_lost = 0;
1169 	return (0);
1170 }
1171 
1172 static void
1173 bbr_init_sysctls(void)
1174 {
1175 	struct sysctl_oid *bbr_probertt;
1176 	struct sysctl_oid *bbr_hptsi;
1177 	struct sysctl_oid *bbr_measure;
1178 	struct sysctl_oid *bbr_cwnd;
1179 	struct sysctl_oid *bbr_timeout;
1180 	struct sysctl_oid *bbr_states;
1181 	struct sysctl_oid *bbr_startup;
1182 	struct sysctl_oid *bbr_policer;
1183 
1184 	/* Probe rtt controls */
1185 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1186 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1187 	    OID_AUTO,
1188 	    "probertt",
1189 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1190 	    "");
1191 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1192 	    SYSCTL_CHILDREN(bbr_probertt),
1193 	    OID_AUTO, "gain", CTLFLAG_RW,
1194 	    &bbr_rttprobe_gain, 192,
1195 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1196 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197 	    SYSCTL_CHILDREN(bbr_probertt),
1198 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1199 	    &bbr_rtt_probe_cwndtarg, 4,
1200 	    "How many mss's are outstanding during probe-rtt");
1201 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1202 	    SYSCTL_CHILDREN(bbr_probertt),
1203 	    OID_AUTO, "int", CTLFLAG_RW,
1204 	    &bbr_rtt_probe_limit, 4000000,
1205 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1206 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1207 	    SYSCTL_CHILDREN(bbr_probertt),
1208 	    OID_AUTO, "mintime", CTLFLAG_RW,
1209 	    &bbr_rtt_probe_time, 200000,
1210 	    "How many microseconds in probe-rtt");
1211 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212 	    SYSCTL_CHILDREN(bbr_probertt),
1213 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1214 	    &bbr_filter_len_sec, 6,
1215 	    "How long in seconds does the rttProp filter run?");
1216 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217 	    SYSCTL_CHILDREN(bbr_probertt),
1218 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1219 	    &bbr_drain_rtt, BBR_SRTT,
1220 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1221 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222 	    SYSCTL_CHILDREN(bbr_probertt),
1223 	    OID_AUTO, "can_force", CTLFLAG_RW,
1224 	    &bbr_can_force_probertt, 0,
1225 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1226 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227 	    SYSCTL_CHILDREN(bbr_probertt),
1228 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1229 	    &bbr_probertt_sets_rtt, 0,
1230 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1231 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232 	    SYSCTL_CHILDREN(bbr_probertt),
1233 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1234 	    &bbr_can_adjust_probertt, 1,
1235 	    "Can we dynamically adjust the probe-rtt limits and times?");
1236 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237 	    SYSCTL_CHILDREN(bbr_probertt),
1238 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1239 	    &bbr_is_ratio, 0,
1240 	    "is the limit to filter a ratio?");
1241 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1242 	    SYSCTL_CHILDREN(bbr_probertt),
1243 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1244 	    &bbr_prtt_slam_cwnd, 0,
1245 	    "Should we set/recover cwnd?");
1246 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1247 	    SYSCTL_CHILDREN(bbr_probertt),
1248 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1249 	    &bbr_can_use_ts_for_rtt, 1,
1250 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1251 
1252 	/* Pacing controls */
1253 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1254 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1255 	    OID_AUTO,
1256 	    "pacing",
1257 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1258 	    "");
1259 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260 	    SYSCTL_CHILDREN(bbr_hptsi),
1261 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1262 	    &bbr_allow_hdwr_pacing, 1,
1263 	    "Do we allow hardware pacing?");
1264 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265 	    SYSCTL_CHILDREN(bbr_hptsi),
1266 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1267 	    &bbr_hardware_pacing_limit, 4000,
1268 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1269 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270 	    SYSCTL_CHILDREN(bbr_hptsi),
1271 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1272 	    &bbr_hdwr_pace_adjust, 2,
1273 	    "Multiplier to calculated tso size?");
1274 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275 	    SYSCTL_CHILDREN(bbr_hptsi),
1276 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1277 	    &bbr_hdwr_pace_floor, 1,
1278 	    "Do we invoke the hardware pacing floor?");
1279 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1280 	    SYSCTL_CHILDREN(bbr_hptsi),
1281 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1282 	    &bbr_hdwr_pacing_delay_cnt, 10,
1283 	    "How many packets must be sent after hdwr pacing is enabled");
1284 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1285 	    SYSCTL_CHILDREN(bbr_hptsi),
1286 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1287 	    &bbr_cross_over, 3000000,
1288 	    "What is the point where we cross over to linux like TSO size set");
1289 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290 	    SYSCTL_CHILDREN(bbr_hptsi),
1291 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1292 	    &bbr_hptsi_segments_delay_tar, 7000,
1293 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1294 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295 	    SYSCTL_CHILDREN(bbr_hptsi),
1296 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1297 	    &bbr_include_enet_oh, 0,
1298 	    "Do we include the ethernet overhead in calculating pacing delay?");
1299 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300 	    SYSCTL_CHILDREN(bbr_hptsi),
1301 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1302 	    &bbr_include_ip_oh, 1,
1303 	    "Do we include the IP overhead in calculating pacing delay?");
1304 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305 	    SYSCTL_CHILDREN(bbr_hptsi),
1306 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1307 	    &bbr_include_tcp_oh, 0,
1308 	    "Do we include the TCP overhead in calculating pacing delay?");
1309 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310 	    SYSCTL_CHILDREN(bbr_hptsi),
1311 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1312 	    &bbr_google_discount, 10,
1313 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1314 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315 	    SYSCTL_CHILDREN(bbr_hptsi),
1316 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1317 	    &bbr_all_get_min, 0,
1318 	    "If you are less than a MSS do you just get the min?");
1319 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320 	    SYSCTL_CHILDREN(bbr_hptsi),
1321 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1322 	    &bbr_hptsi_bytes_min, 1460,
1323 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1324 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(bbr_hptsi),
1326 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1327 	    &bbr_hptsi_segments_max, 6,
1328 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1329 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330 	    SYSCTL_CHILDREN(bbr_hptsi),
1331 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1332 	    &bbr_hptsi_segments_floor, 1,
1333 	    "Minimum TSO size we will fall too in segments");
1334 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335 	    SYSCTL_CHILDREN(bbr_hptsi),
1336 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1337 	    &bbr_hptsi_utter_max, 0,
1338 	    "The absolute maximum that any pacing (outside of hardware) can be");
1339 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340 	    SYSCTL_CHILDREN(bbr_hptsi),
1341 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1342 	    &bbr_hptsi_per_second, 100,
1343 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1344 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1345 	    SYSCTL_CHILDREN(bbr_hptsi),
1346 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1347 	    &bbr_hptsi_max_mul, 1,
1348 	    "The multiplier for pace len max");
1349 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1350 	    SYSCTL_CHILDREN(bbr_hptsi),
1351 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1352 	    &bbr_hptsi_max_div, 2,
1353 	    "The divisor for pace len max");
1354 	/* Measurement controls */
1355 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1356 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1357 	    OID_AUTO,
1358 	    "measure",
1359 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1360 	    "Measurement controls");
1361 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1362 	    SYSCTL_CHILDREN(bbr_measure),
1363 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1364 	    &bbr_initial_bw_bps, 62500,
1365 	    "Minimum initial b/w in bytes per second");
1366 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(bbr_measure),
1368 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1369 	    &bbr_sack_not_required, 0,
1370 	    "Do we allow bbr to run on connections not supporting SACK?");
1371 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372 	    SYSCTL_CHILDREN(bbr_measure),
1373 	    OID_AUTO, "use_google", CTLFLAG_RW,
1374 	    &bbr_use_google_algo, 0,
1375 	    "Use has close to google V1.0 has possible?");
1376 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377 	    SYSCTL_CHILDREN(bbr_measure),
1378 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1379 	    &bbr_ts_limiting, 1,
1380 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1381 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382 	    SYSCTL_CHILDREN(bbr_measure),
1383 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1384 	    &bbr_ts_can_raise, 0,
1385 	    "Can we raise the b/w via timestamp b/w calculation?");
1386 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387 	    SYSCTL_CHILDREN(bbr_measure),
1388 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1389 	    &bbr_min_usec_delta, 20000,
1390 	    "How long in usec between ts of our sends in ts validation code?");
1391 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392 	    SYSCTL_CHILDREN(bbr_measure),
1393 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1394 	    &bbr_min_peer_delta, 20,
1395 	    "What min numerical value should be between the peer deltas?");
1396 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397 	    SYSCTL_CHILDREN(bbr_measure),
1398 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1399 	    &bbr_delta_percent, 150,
1400 	    "What percentage (150 = 15.0) do we allow variance for?");
1401 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402 	    SYSCTL_CHILDREN(bbr_measure),
1403 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1404 	    &bbr_min_measurements_req, 1,
1405 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1406 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407 	    SYSCTL_CHILDREN(bbr_measure),
1408 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1409 	    &bbr_no_pacing_until, 4,
1410 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1411 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1412 	    SYSCTL_CHILDREN(bbr_measure),
1413 	    OID_AUTO, "quanta", CTLFLAG_RW,
1414 	    &bbr_quanta, 2,
1415 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1416 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1417 	    SYSCTL_CHILDREN(bbr_measure),
1418 	    OID_AUTO, "noretran", CTLFLAG_RW,
1419 	    &bbr_no_retran, 0,
1420 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1421 	/* State controls */
1422 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1423 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1424 	    OID_AUTO,
1425 	    "states",
1426 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1427 	    "State controls");
1428 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429 	    SYSCTL_CHILDREN(bbr_states),
1430 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1431 	    &bbr_uses_idle_restart, 0,
1432 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1433 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434 	    SYSCTL_CHILDREN(bbr_states),
1435 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1436 	    &bbr_idle_restart_threshold, 100000,
1437 	    "How long must we be idle before we restart??");
1438 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439 	    SYSCTL_CHILDREN(bbr_states),
1440 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1441 	    &bbr_state_is_pkt_epoch, 0,
1442 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1443 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444 	    SYSCTL_CHILDREN(bbr_states),
1445 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1446 	    &bbr_rtt_gain_thresh, 0,
1447 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1448 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449 	    SYSCTL_CHILDREN(bbr_states),
1450 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1451 	    &bbr_drain_floor, 88,
1452 	    "What is the lowest we can drain (pg) too?");
1453 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454 	    SYSCTL_CHILDREN(bbr_states),
1455 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1456 	    &bbr_state_drain_2_tar, 1,
1457 	    "Do we drain to target in drain substate?");
1458 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459 	    SYSCTL_CHILDREN(bbr_states),
1460 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1461 	    &bbr_gain_to_target, 1,
1462 	    "Does probe bw gain to target??");
1463 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464 	    SYSCTL_CHILDREN(bbr_states),
1465 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1466 	    &bbr_gain_gets_extra_too, 1,
1467 	    "Does probe bw gain get the extra time too?");
1468 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469 	    SYSCTL_CHILDREN(bbr_states),
1470 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1471 	    &bbr_drain_drop_div, 5,
1472 	    "Long drain drop divider?");
1473 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474 	    SYSCTL_CHILDREN(bbr_states),
1475 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1476 	    &bbr_drain_drop_mul, 4,
1477 	    "Long drain drop multiplier?");
1478 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479 	    SYSCTL_CHILDREN(bbr_states),
1480 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1481 	    &bbr_rand_ot, 50,
1482 	    "Random discount of the ot?");
1483 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484 	    SYSCTL_CHILDREN(bbr_states),
1485 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1486 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1487 	    "How many packet-epochs does the b/w delivery rate last?");
1488 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489 	    SYSCTL_CHILDREN(bbr_states),
1490 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1491 	    &bbr_sub_drain_app_limit, 0,
1492 	    "Does our sub-state drain invoke app limited if its long?");
1493 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(bbr_states),
1495 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1496 	    &bbr_sub_drain_slam_cwnd, 0,
1497 	    "Should we set/recover cwnd for sub-state drain?");
1498 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499 	    SYSCTL_CHILDREN(bbr_states),
1500 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1501 	    &bbr_slam_cwnd_in_main_drain, 0,
1502 	    "Should we set/recover cwnd for main-state drain?");
1503 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1504 	    SYSCTL_CHILDREN(bbr_states),
1505 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1506 	    &google_allow_early_out, 1,
1507 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1508 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1509 	    SYSCTL_CHILDREN(bbr_states),
1510 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1511 	    &google_consider_lost, 1,
1512 	    "Should we have losses exit gain of probebw in google mode??");
1513 	/* Startup controls */
1514 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1515 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1516 	    OID_AUTO,
1517 	    "startup",
1518 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1519 	    "Startup controls");
1520 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521 	    SYSCTL_CHILDREN(bbr_startup),
1522 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1523 	    &bbr_sends_full_iwnd, 1,
1524 	    "Do we not pace but burst out initial windows has our TSO size?");
1525 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1526 	    SYSCTL_CHILDREN(bbr_startup),
1527 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1528 	    &bbr_startup_loss_thresh, 2000,
1529 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1530 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1531 	    SYSCTL_CHILDREN(bbr_startup),
1532 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1533 	    &bbr_use_lower_gain_in_startup, 1,
1534 	    "Should we use a lower hptsi gain if we see loss in startup?");
1535 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(bbr_startup),
1537 	    OID_AUTO, "gain", CTLFLAG_RW,
1538 	    &bbr_start_exit, 25,
1539 	    "What gain percent do we need to see to stay in startup??");
1540 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1541 	    SYSCTL_CHILDREN(bbr_startup),
1542 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1543 	    &bbr_low_start_exit, 15,
1544 	    "What gain percent do we need to see to stay in the lower gain startup??");
1545 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1546 	    SYSCTL_CHILDREN(bbr_startup),
1547 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1548 	    &bbr_exit_startup_at_loss, 1,
1549 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1550 	/* CWND controls */
1551 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1552 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1553 	    OID_AUTO,
1554 	    "cwnd",
1555 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1556 	    "Cwnd controls");
1557 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(bbr_cwnd),
1559 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1560 	    &bbr_cwndtarget_rtt_touse, 0,
1561 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1562 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(bbr_cwnd),
1564 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1565 	    &bbr_cwnd_may_shrink, 0,
1566 	    "Can the cwnd shrink if it would grow to more than the target?");
1567 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1568 	    SYSCTL_CHILDREN(bbr_cwnd),
1569 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1570 	    &bbr_target_cwnd_mult_limit, 8,
1571 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1572 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573 	    SYSCTL_CHILDREN(bbr_cwnd),
1574 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1575 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1576 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1577 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1578 	    SYSCTL_CHILDREN(bbr_cwnd),
1579 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1580 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1581 	    "What is the min cwnd (rttProp > 1ms)");
1582 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1583 	    SYSCTL_CHILDREN(bbr_cwnd),
1584 	    OID_AUTO, "initwin", CTLFLAG_RW,
1585 	    &bbr_def_init_win, 10,
1586 	    "What is the BBR initial window, if 0 use tcp version");
1587 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588 	    SYSCTL_CHILDREN(bbr_cwnd),
1589 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1590 	    &bbr_do_red, 600,
1591 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1592 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593 	    SYSCTL_CHILDREN(bbr_cwnd),
1594 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1595 	    &bbr_red_scale, 20000,
1596 	    "What RTT do we scale with?");
1597 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598 	    SYSCTL_CHILDREN(bbr_cwnd),
1599 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1600 	    &bbr_red_growth_restrict, 1,
1601 	    "Do we restrict cwnd growth for whats in flight?");
1602 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603 	    SYSCTL_CHILDREN(bbr_cwnd),
1604 	    OID_AUTO, "red_div", CTLFLAG_RW,
1605 	    &bbr_red_div, 2,
1606 	    "If we reduce whats the divisor?");
1607 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(bbr_cwnd),
1609 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1610 	    &bbr_red_mul, 1,
1611 	    "If we reduce whats the mulitiplier?");
1612 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1613 	    SYSCTL_CHILDREN(bbr_cwnd),
1614 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1615 	    &bbr_target_is_bbunit, 0,
1616 	    "Is the state target the pacing_gain or BBR_UNIT?");
1617 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1618 	    SYSCTL_CHILDREN(bbr_cwnd),
1619 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1620 	    &bbr_drop_limit, 0,
1621 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1622 
1623 	/* Timeout controls */
1624 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1625 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1626 	    OID_AUTO,
1627 	    "timeout",
1628 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1629 	    "Time out controls");
1630 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1631 	    SYSCTL_CHILDREN(bbr_timeout),
1632 	    OID_AUTO, "delack", CTLFLAG_RW,
1633 	    &bbr_delack_time, 100000,
1634 	    "BBR's delayed ack time");
1635 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1636 	    SYSCTL_CHILDREN(bbr_timeout),
1637 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1638 	    &bbr_tlp_type_to_use, 3,
1639 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1640 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1641 	    SYSCTL_CHILDREN(bbr_timeout),
1642 	    OID_AUTO, "persmin", CTLFLAG_RW,
1643 	    &bbr_persist_min, 250000,
1644 	    "What is the minimum time in microseconds between persists");
1645 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1646 	    SYSCTL_CHILDREN(bbr_timeout),
1647 	    OID_AUTO, "persmax", CTLFLAG_RW,
1648 	    &bbr_persist_max, 1000000,
1649 	    "What is the largest delay in microseconds between persists");
1650 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651 	    SYSCTL_CHILDREN(bbr_timeout),
1652 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1653 	    &bbr_tlp_min, 10000,
1654 	    "TLP Min timeout in usecs");
1655 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(bbr_timeout),
1657 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1658 	    &bbr_delayed_ack_time, 200000,
1659 	    "TLP delayed ack compensation value");
1660 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1662 	    OID_AUTO, "minrto", CTLFLAG_RW,
1663 	    &bbr_rto_min_ms, 30,
1664 	    "Minimum RTO in ms");
1665 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666 	    SYSCTL_CHILDREN(bbr_timeout),
1667 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1668 	    &bbr_rto_max_sec, 4,
1669 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1670 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671 	    SYSCTL_CHILDREN(bbr_timeout),
1672 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1673 	    &bbr_tlp_max_resend, 2,
1674 	    "How many times does TLP retry a single segment or multiple with no ACK");
1675 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676 	    SYSCTL_CHILDREN(bbr_timeout),
1677 	    OID_AUTO, "minto", CTLFLAG_RW,
1678 	    &bbr_min_to, 1000,
1679 	    "Minimum rack timeout in useconds");
1680 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681 	    SYSCTL_CHILDREN(bbr_timeout),
1682 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1683 	    &bbr_pkt_delay, 1000,
1684 	    "Extra RACK time (in useconds) besides reordering thresh");
1685 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1686 	    SYSCTL_CHILDREN(bbr_timeout),
1687 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1688 	    &bbr_incr_timers, 1,
1689 	    "Increase the RXT/TLP timer by the pacing time used?");
1690 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1691 	    SYSCTL_CHILDREN(bbr_timeout),
1692 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1693 	    &bbr_marks_rxt_sack_passed, 0,
1694 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1695 	/* Policer controls */
1696 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1697 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1698 	    OID_AUTO,
1699 	    "policer",
1700 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1701 	    "Policer controls");
1702 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1703 	    SYSCTL_CHILDREN(bbr_policer),
1704 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1705 	    &bbr_policer_detection_enabled, 1,
1706 	    "Is policer detection enabled??");
1707 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1708 	    SYSCTL_CHILDREN(bbr_policer),
1709 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1710 	    &bbr_lt_intvl_min_rtts, 4,
1711 	    "Minimum number of PE's?");
1712 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1713 	    SYSCTL_CHILDREN(bbr_policer),
1714 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1715 	    &bbr_lt_bw_diff, (4000/8),
1716 	    "Minimal bw diff?");
1717 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1718 	    SYSCTL_CHILDREN(bbr_policer),
1719 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1720 	    &bbr_lt_bw_ratio, 8,
1721 	    "Minimal bw diff?");
1722 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723 	    SYSCTL_CHILDREN(bbr_policer),
1724 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1725 	    &bbr_policer_call_from_rack_to, 0,
1726 	    "Do we call the policer detection code from a rack-timeout?");
1727 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(bbr_policer),
1729 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1730 	    &bbr_lt_intvl_fp, 0,
1731 	    "What packet epoch do we do false-postive detection at (0=no)?");
1732 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1733 	    SYSCTL_CHILDREN(bbr_policer),
1734 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1735 	    &bbr_lt_loss_thresh, 196,
1736 	    "Loss threshold 196 = 19.6%?");
1737 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1738 	    SYSCTL_CHILDREN(bbr_policer),
1739 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1740 	    &bbr_lt_fd_thresh, 100,
1741 	    "What percentage is the false detection threshold (150=15.0)?");
1742 	/* All the rest */
1743 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1745 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1746 	    &bbr_use_rack_resend_cheat, 0,
1747 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1748 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1750 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1751 	    &bbr_error_base_paceout, 10000,
1752 	    "When we hit an error what is the min to pace out in usec's?");
1753 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1755 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1756 	    &bbr_max_net_error_cnt, 10,
1757 	    "When we hit this many errors in a row, kill the session?");
1758 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1760 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1761 	    &bbr_ignore_data_after_close, 1,
1762 	    "Do we hold off sending a RST until all pending data is ack'd");
1763 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1765 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1766 	    &bbr_resends_use_tso, 0,
1767 	    "Can resends use TSO?");
1768 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1770 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1771 	    &bbr_sack_block_limit, 128,
1772 	    "When do we start ignoring small sack blocks");
1773 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1775 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1776 	    &bbr_verbose_logging, 0,
1777 	    "Should BBR black box logging be verbose");
1778 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1780 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1781 	    &bbr_reorder_thresh, 2,
1782 	    "What factor for rack will be added when seeing reordering (shift right)");
1783 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1784 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1785 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1786 	    &bbr_reorder_fade, 0,
1787 	    "Does reorder detection fade, if so how many ms (0 means never)");
1788 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1789 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1790 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1791 	    &bbr_tlp_thresh, 1,
1792 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1793 	/* Stats and counters */
1794 	/* The pacing counters for hdwr/software can't be in the array */
1795 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1796 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1797 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1798 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1799 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1800 	    &bbr_hdwr_pacing_enobuf,
1801 	    "Total number of enobufs for hardware paced flows");
1802 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1803 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1804 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1805 	    &bbr_nohdwr_pacing_enobuf,
1806 	    "Total number of enobufs for non-hardware paced flows");
1807 
1808 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1809 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1810 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1811 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1812 	    &bbr_flows_whdwr_pacing,
1813 	    "Total number of hardware paced flows");
1814 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1816 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1817 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1818 	    &bbr_flows_nohdwr_pacing,
1819 	    "Total number of software paced flows");
1820 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1821 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1822 	    OID_AUTO, "stats", CTLFLAG_RD,
1823 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1824 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1825 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1826 	    OID_AUTO, "opts", CTLFLAG_RD,
1827 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1828 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1829 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1830 	    OID_AUTO, "lost", CTLFLAG_RD,
1831 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1832 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1833 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1834 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1835 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1836 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1837 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1838 	    OID_AUTO, "statetime", CTLFLAG_RD,
1839 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1840 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1841 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1842 	    OID_AUTO, "outsize", CTLFLAG_RD,
1843 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1844 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1845 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1846 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1847 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1848 }
1849 
1850 static void
1851 bbr_counter_destroy(void)
1852 {
1853 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1854 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1855 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1856 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1857 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1858 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1859 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1860 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1861 	counter_u64_free(bbr_flows_whdwr_pacing);
1862 	counter_u64_free(bbr_flows_nohdwr_pacing);
1863 
1864 }
1865 
1866 static __inline void
1867 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1868 {
1869 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1870 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1871 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1872 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1873 	l->bw_inuse = bbr_get_bw(bbr);
1874 	l->inflight = ctf_flight_size(bbr->rc_tp,
1875 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1876 	l->applimited = bbr->r_ctl.r_app_limited_until;
1877 	l->delivered = bbr->r_ctl.rc_delivered;
1878 	l->timeStamp = cts;
1879 	l->lost = bbr->r_ctl.rc_lost;
1880 	l->bbr_state = bbr->rc_bbr_state;
1881 	l->bbr_substate = bbr_state_val(bbr);
1882 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1883 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1884 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1885 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1886 	l->inhpts = tcp_in_hpts(bbr->rc_inp);
1887 	l->use_lt_bw = bbr->rc_lt_use_bw;
1888 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1889 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1890 }
1891 
1892 static void
1893 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1894 {
1895 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1896 		union tcp_log_stackspecific log;
1897 
1898 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1899 		log.u_bbr.flex1 = 0;
1900 		log.u_bbr.flex2 = 0;
1901 		log.u_bbr.flex5 = 0;
1902 		log.u_bbr.flex3 = 0;
1903 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1904 		log.u_bbr.flex7 = reason;
1905 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1906 		log.u_bbr.flex8 = 0;
1907 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1908 		    &bbr->rc_inp->inp_socket->so_rcv,
1909 		    &bbr->rc_inp->inp_socket->so_snd,
1910 		    BBR_LOG_BW_RED_EV, 0,
1911 		    0, &log, false, &bbr->rc_tv);
1912 	}
1913 }
1914 
1915 static void
1916 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1917 {
1918 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1919 		union tcp_log_stackspecific log;
1920 
1921 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1922 		log.u_bbr.flex1 = seq;
1923 		log.u_bbr.flex2 = count;
1924 		log.u_bbr.flex8 = mode;
1925 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1926 		    &bbr->rc_inp->inp_socket->so_rcv,
1927 		    &bbr->rc_inp->inp_socket->so_snd,
1928 		    BBR_LOG_LOWGAIN, 0,
1929 		    0, &log, false, &bbr->rc_tv);
1930 	}
1931 }
1932 
1933 static void
1934 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1935     uint8_t reason, uint32_t p_maxseg, int len)
1936 {
1937 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1938 		union tcp_log_stackspecific log;
1939 
1940 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1941 		log.u_bbr.flex1 = p_maxseg;
1942 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1943 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1944 		log.u_bbr.flex4 = reason;
1945 		log.u_bbr.flex5 = bbr->rc_in_persist;
1946 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1947 		log.u_bbr.flex7 = p_maxseg;
1948 		log.u_bbr.flex8 = bbr->rc_in_persist;
1949 		log.u_bbr.pkts_out = 0;
1950 		log.u_bbr.applimited = len;
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_JUSTRET, 0,
1955 		    tlen, &log, false, &bbr->rc_tv);
1956 	}
1957 }
1958 
1959 static void
1960 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1961 {
1962 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1963 		union tcp_log_stackspecific log;
1964 
1965 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1966 		log.u_bbr.flex1 = seq;
1967 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1968 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1969 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1970 		    &bbr->rc_inp->inp_socket->so_rcv,
1971 		    &bbr->rc_inp->inp_socket->so_snd,
1972 		    BBR_LOG_ENTREC, 0,
1973 		    0, &log, false, &bbr->rc_tv);
1974 	}
1975 }
1976 
1977 static void
1978 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)
1979 {
1980 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1981 		union tcp_log_stackspecific log;
1982 
1983 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1984 		log.u_bbr.flex1 = tso;
1985 		log.u_bbr.flex2 = maxseg;
1986 		log.u_bbr.flex3 = mtu;
1987 		log.u_bbr.flex4 = csum_flags;
1988 		TCP_LOG_EVENTP(tp, NULL,
1989 		    &bbr->rc_inp->inp_socket->so_rcv,
1990 		    &bbr->rc_inp->inp_socket->so_snd,
1991 		    BBR_LOG_MSGSIZE, 0,
1992 		    0, &log, false, &bbr->rc_tv);
1993 	}
1994 }
1995 
1996 static void
1997 bbr_log_flowend(struct tcp_bbr *bbr)
1998 {
1999 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2000 		union tcp_log_stackspecific log;
2001 		struct sockbuf *r, *s;
2002 		struct timeval tv;
2003 
2004 		if (bbr->rc_inp->inp_socket) {
2005 			r = &bbr->rc_inp->inp_socket->so_rcv;
2006 			s = &bbr->rc_inp->inp_socket->so_snd;
2007 		} else {
2008 			r = s = NULL;
2009 		}
2010 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2011 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2012 		    r, s,
2013 		    TCP_LOG_FLOWEND, 0,
2014 		    0, &log, false, &tv);
2015 	}
2016 }
2017 
2018 static void
2019 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2020     uint32_t lost, uint32_t del)
2021 {
2022 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2023 		union tcp_log_stackspecific log;
2024 
2025 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2026 		log.u_bbr.flex1 = lost;
2027 		log.u_bbr.flex2 = del;
2028 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2029 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2030 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2031 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2032 		log.u_bbr.flex7 = line;
2033 		log.u_bbr.flex8 = 0;
2034 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2035 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2036 		    &bbr->rc_inp->inp_socket->so_rcv,
2037 		    &bbr->rc_inp->inp_socket->so_snd,
2038 		    BBR_LOG_PKT_EPOCH, 0,
2039 		    0, &log, false, &bbr->rc_tv);
2040 	}
2041 }
2042 
2043 static void
2044 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2045 {
2046 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2047 		union tcp_log_stackspecific log;
2048 
2049 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2050 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2051 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2052 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2053 		log.u_bbr.flex7 = line;
2054 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2055 		    &bbr->rc_inp->inp_socket->so_rcv,
2056 		    &bbr->rc_inp->inp_socket->so_snd,
2057 		    BBR_LOG_TIME_EPOCH, 0,
2058 		    0, &log, false, &bbr->rc_tv);
2059 	}
2060 }
2061 
2062 static void
2063 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2064 {
2065 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2066 		union tcp_log_stackspecific log;
2067 
2068 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2069 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2070 		log.u_bbr.flex2 = new_tar;
2071 		log.u_bbr.flex3 = line;
2072 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2073 		log.u_bbr.flex5 = bbr_quanta;
2074 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2075 		log.u_bbr.flex7 = bbr->rc_last_options;
2076 		log.u_bbr.flex8 = meth;
2077 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2078 		    &bbr->rc_inp->inp_socket->so_rcv,
2079 		    &bbr->rc_inp->inp_socket->so_snd,
2080 		    BBR_LOG_STATE_TARGET, 0,
2081 		    0, &log, false, &bbr->rc_tv);
2082 	}
2083 
2084 }
2085 
2086 static void
2087 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2088 {
2089 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2090 		union tcp_log_stackspecific log;
2091 
2092 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2093 		log.u_bbr.flex1 = line;
2094 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2095 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2096 		if (bbr_state_is_pkt_epoch)
2097 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2098 		else
2099 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2100 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2101 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2102 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2103 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2104 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2105 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2106 		    &bbr->rc_inp->inp_socket->so_rcv,
2107 		    &bbr->rc_inp->inp_socket->so_snd,
2108 		    BBR_LOG_STATE, 0,
2109 		    0, &log, false, &bbr->rc_tv);
2110 	}
2111 }
2112 
2113 static void
2114 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2115 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2116 {
2117 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2118 		union tcp_log_stackspecific log;
2119 
2120 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2121 		log.u_bbr.flex1 = line;
2122 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2123 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2124 		log.u_bbr.flex4 = applied;
2125 		log.u_bbr.flex5 = rtt;
2126 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2127 		log.u_bbr.flex7 = cond;
2128 		log.u_bbr.flex8 = reas;
2129 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2130 		    &bbr->rc_inp->inp_socket->so_rcv,
2131 		    &bbr->rc_inp->inp_socket->so_snd,
2132 		    BBR_LOG_RTT_SHRINKS, 0,
2133 		    0, &log, false, &bbr->rc_tv);
2134 	}
2135 }
2136 
2137 static void
2138 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2139 {
2140 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2141 		union tcp_log_stackspecific log;
2142 
2143 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2144 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2145 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2146 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2147 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2148 		    &bbr->rc_inp->inp_socket->so_rcv,
2149 		    &bbr->rc_inp->inp_socket->so_snd,
2150 		    BBR_LOG_EXITREC, 0,
2151 		    0, &log, false, &bbr->rc_tv);
2152 	}
2153 }
2154 
2155 static void
2156 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2157     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2158 {
2159 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2160 		union tcp_log_stackspecific log;
2161 
2162 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2163 		log.u_bbr.flex1 = line;
2164 		log.u_bbr.flex2 = prev_acked;
2165 		log.u_bbr.flex3 = bytes_this_ack;
2166 		log.u_bbr.flex4 = chg;
2167 		log.u_bbr.flex5 = th_ack;
2168 		log.u_bbr.flex6 = target;
2169 		log.u_bbr.flex8 = meth;
2170 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2171 		    &bbr->rc_inp->inp_socket->so_rcv,
2172 		    &bbr->rc_inp->inp_socket->so_snd,
2173 		    BBR_LOG_CWND, 0,
2174 		    0, &log, false, &bbr->rc_tv);
2175 	}
2176 }
2177 
2178 static void
2179 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2180 {
2181 	/*
2182 	 * Log the rtt sample we are applying to the srtt algorithm in
2183 	 * useconds.
2184 	 */
2185 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2186 		union tcp_log_stackspecific log;
2187 
2188 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2189 		log.u_bbr.flex1 = rtt;
2190 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2191 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2192 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2193 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2194 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2195 		log.u_bbr.flex6 = tsin;
2196 		log.u_bbr.flex7 = 0;
2197 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2198 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2199 		    &bbr->rc_inp->inp_socket->so_rcv,
2200 		    &bbr->rc_inp->inp_socket->so_snd,
2201 		    TCP_LOG_RTT, 0,
2202 		    0, &log, false, &bbr->rc_tv);
2203 	}
2204 }
2205 
2206 static void
2207 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2208 {
2209 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2210 		union tcp_log_stackspecific log;
2211 
2212 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2213 		log.u_bbr.flex1 = time_in;
2214 		log.u_bbr.flex2 = line;
2215 		log.u_bbr.flex8 = enter_exit;
2216 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2217 		    &bbr->rc_inp->inp_socket->so_rcv,
2218 		    &bbr->rc_inp->inp_socket->so_snd,
2219 		    BBR_LOG_PERSIST, 0,
2220 		    0, &log, false, &bbr->rc_tv);
2221 	}
2222 }
2223 static void
2224 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2225 {
2226 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2227 		union tcp_log_stackspecific log;
2228 
2229 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2230 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2231 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2232 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2233 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2234 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2235 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2236 		    &bbr->rc_inp->inp_socket->so_rcv,
2237 		    &bbr->rc_inp->inp_socket->so_snd,
2238 		    BBR_LOG_ACKCLEAR, 0,
2239 		    0, &log, false, &bbr->rc_tv);
2240 	}
2241 }
2242 
2243 static void
2244 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2245 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2246 {
2247 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2248 		union tcp_log_stackspecific log;
2249 		struct timeval tv;
2250 
2251 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2252 		log.u_bbr.flex1 = nsegs;
2253 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2254 		if (m) {
2255 			struct timespec ts;
2256 
2257 			log.u_bbr.flex3 = m->m_flags;
2258 			if (m->m_flags & M_TSTMP) {
2259 				mbuf_tstmp2timespec(m, &ts);
2260 				tv.tv_sec = ts.tv_sec;
2261 				tv.tv_usec = ts.tv_nsec / 1000;
2262 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2263 			} else {
2264 				log.u_bbr.lt_epoch = 0;
2265 			}
2266 			if (m->m_flags & M_TSTMP_LRO) {
2267 				tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2268 				tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2269 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2270 			} else {
2271 				/* No arrival timestamp */
2272 				log.u_bbr.flex5 = 0;
2273 			}
2274 
2275 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2276 		} else {
2277 			log.u_bbr.flex3 = 0;
2278 			log.u_bbr.flex5 = 0;
2279 			log.u_bbr.flex6 = 0;
2280 			log.u_bbr.pkts_out = 0;
2281 		}
2282 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2283 		log.u_bbr.flex7 = bbr->r_wanted_output;
2284 		log.u_bbr.flex8 = bbr->rc_in_persist;
2285 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2286 		    &bbr->rc_inp->inp_socket->so_rcv,
2287 		    &bbr->rc_inp->inp_socket->so_snd,
2288 		    TCP_LOG_IN, 0,
2289 		    tlen, &log, true, &bbr->rc_tv);
2290 	}
2291 }
2292 
2293 static void
2294 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2295 {
2296 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2297 		union tcp_log_stackspecific log;
2298 
2299 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2300 		log.u_bbr.flex1 = did_out;
2301 		log.u_bbr.flex2 = nxt_pkt;
2302 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2303 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2304 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2305 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2306 		log.u_bbr.flex7 = bbr->r_wanted_output;
2307 		log.u_bbr.flex8 = bbr->rc_in_persist;
2308 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2309 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2310 		    &bbr->rc_inp->inp_socket->so_rcv,
2311 		    &bbr->rc_inp->inp_socket->so_snd,
2312 		    BBR_LOG_DOSEG_DONE, 0,
2313 		    0, &log, true, &bbr->rc_tv);
2314 	}
2315 }
2316 
2317 static void
2318 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2319     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2320 {
2321 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2322 		union tcp_log_stackspecific log;
2323 
2324 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2325 		log.u_bbr.flex1 = line;
2326 		log.u_bbr.flex2 = o_len;
2327 		log.u_bbr.flex3 = segcnt;
2328 		log.u_bbr.flex4 = segsiz;
2329 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2330 		    &bbr->rc_inp->inp_socket->so_rcv,
2331 		    &bbr->rc_inp->inp_socket->so_snd,
2332 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2333 		    len, &log, true, &bbr->rc_tv);
2334 	}
2335 }
2336 
2337 static void
2338 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2339 {
2340 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2341 		union tcp_log_stackspecific log;
2342 
2343 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2344 		log.u_bbr.flex1 = timers;
2345 		log.u_bbr.flex2 = ret;
2346 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2347 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2348 		log.u_bbr.flex5 = cts;
2349 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2350 		log.u_bbr.flex8 = hpts_calling;
2351 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2352 		    &bbr->rc_inp->inp_socket->so_rcv,
2353 		    &bbr->rc_inp->inp_socket->so_snd,
2354 		    BBR_LOG_TO_PROCESS, 0,
2355 		    0, &log, false, &bbr->rc_tv);
2356 	}
2357 }
2358 
2359 static void
2360 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2361 {
2362 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2363 		union tcp_log_stackspecific log;
2364 		uint64_t ar;
2365 
2366 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2367 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2368 		log.u_bbr.flex2 = 0;
2369 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2370 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2371 		ar >>= 32;
2372 		ar &= 0x00000000ffffffff;
2373 		log.u_bbr.flex4 = (uint32_t)ar;
2374 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2375 		ar &= 0x00000000ffffffff;
2376 		log.u_bbr.flex5 = (uint32_t)ar;
2377 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2378 		log.u_bbr.flex8 = to_num;
2379 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2380 		    &bbr->rc_inp->inp_socket->so_rcv,
2381 		    &bbr->rc_inp->inp_socket->so_snd,
2382 		    BBR_LOG_RTO, 0,
2383 		    0, &log, false, &bbr->rc_tv);
2384 	}
2385 }
2386 
2387 static void
2388 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2389 {
2390 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2391 		union tcp_log_stackspecific log;
2392 
2393 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2394 		log.u_bbr.flex1 = flex1;
2395 		log.u_bbr.flex2 = flex2;
2396 		log.u_bbr.flex3 = flex3;
2397 		log.u_bbr.flex4 = 0;
2398 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2399 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2400 		log.u_bbr.flex8 = reason;
2401 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2402 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2403 		    &bbr->rc_inp->inp_socket->so_rcv,
2404 		    &bbr->rc_inp->inp_socket->so_snd,
2405 		    BBR_LOG_REDUCE, 0,
2406 		    0, &log, false, &bbr->rc_tv);
2407 	}
2408 }
2409 
2410 static void
2411 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2412 {
2413 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2414 		union tcp_log_stackspecific log;
2415 
2416 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2417 		log.u_bbr.flex1 = diag->p_nxt_slot;
2418 		log.u_bbr.flex2 = diag->p_cur_slot;
2419 		log.u_bbr.flex3 = diag->slot_req;
2420 		log.u_bbr.flex4 = diag->inp_hptsslot;
2421 		log.u_bbr.flex5 = diag->slot_remaining;
2422 		log.u_bbr.flex6 = diag->need_new_to;
2423 		log.u_bbr.flex7 = diag->p_hpts_active;
2424 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2425 		/* Hijack other fields as needed  */
2426 		log.u_bbr.epoch = diag->have_slept;
2427 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2428 		log.u_bbr.pkts_out = diag->co_ret;
2429 		log.u_bbr.applimited = diag->hpts_sleep_time;
2430 		log.u_bbr.delivered = diag->p_prev_slot;
2431 		log.u_bbr.inflight = diag->p_runningslot;
2432 		log.u_bbr.bw_inuse = diag->wheel_slot;
2433 		log.u_bbr.rttProp = diag->wheel_cts;
2434 		log.u_bbr.delRate = diag->maxslots;
2435 		log.u_bbr.cur_del_rate = diag->p_curtick;
2436 		log.u_bbr.cur_del_rate <<= 32;
2437 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2438 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2439 		    &bbr->rc_inp->inp_socket->so_rcv,
2440 		    &bbr->rc_inp->inp_socket->so_snd,
2441 		    BBR_LOG_HPTSDIAG, 0,
2442 		    0, &log, false, &bbr->rc_tv);
2443 	}
2444 }
2445 
2446 static void
2447 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2448     uint32_t thresh, uint32_t to)
2449 {
2450 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2451 		union tcp_log_stackspecific log;
2452 
2453 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2454 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2455 		log.u_bbr.flex2 = time_since_sent;
2456 		log.u_bbr.flex3 = srtt;
2457 		log.u_bbr.flex4 = thresh;
2458 		log.u_bbr.flex5 = to;
2459 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2460 		log.u_bbr.flex8 = mode;
2461 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2462 		    &bbr->rc_inp->inp_socket->so_rcv,
2463 		    &bbr->rc_inp->inp_socket->so_snd,
2464 		    BBR_LOG_TIMERPREP, 0,
2465 		    0, &log, false, &bbr->rc_tv);
2466 	}
2467 }
2468 
2469 static void
2470 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2471     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2472 {
2473 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2474 		union tcp_log_stackspecific log;
2475 
2476 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2477 		log.u_bbr.flex1 = usecs;
2478 		log.u_bbr.flex2 = len;
2479 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2480 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2481 		if (override)
2482 			log.u_bbr.flex5 = (1 << 2);
2483 		else
2484 			log.u_bbr.flex5 = 0;
2485 		log.u_bbr.flex6 = override;
2486 		log.u_bbr.flex7 = gain;
2487 		log.u_bbr.flex8 = mod;
2488 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2489 		    &bbr->rc_inp->inp_socket->so_rcv,
2490 		    &bbr->rc_inp->inp_socket->so_snd,
2491 		    BBR_LOG_HPTSI_CALC, 0,
2492 		    len, &log, false, &bbr->rc_tv);
2493 	}
2494 }
2495 
2496 static void
2497 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2498 {
2499 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2500 		union tcp_log_stackspecific log;
2501 
2502 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2503 
2504 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2505 		log.u_bbr.flex2 = to;
2506 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2507 		log.u_bbr.flex4 = slot;
2508 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2509 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2510 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2511 		log.u_bbr.flex8 = which;
2512 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2513 		    &bbr->rc_inp->inp_socket->so_rcv,
2514 		    &bbr->rc_inp->inp_socket->so_snd,
2515 		    BBR_LOG_TIMERSTAR, 0,
2516 		    0, &log, false, &bbr->rc_tv);
2517 	}
2518 }
2519 
2520 static void
2521 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)
2522 {
2523 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2524 		union tcp_log_stackspecific log;
2525 
2526 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2527 		log.u_bbr.flex1 = thresh;
2528 		log.u_bbr.flex2 = lro;
2529 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2530 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2531 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2532 		log.u_bbr.flex6 = srtt;
2533 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2534 		log.u_bbr.flex8 = frm;
2535 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2536 		    &bbr->rc_inp->inp_socket->so_rcv,
2537 		    &bbr->rc_inp->inp_socket->so_snd,
2538 		    BBR_LOG_THRESH_CALC, 0,
2539 		    0, &log, false, &bbr->rc_tv);
2540 	}
2541 }
2542 
2543 static void
2544 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2545 {
2546 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2547 		union tcp_log_stackspecific log;
2548 
2549 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2550 		log.u_bbr.flex1 = line;
2551 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2552 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2553 		log.u_bbr.flex4 = bbr->rc_in_persist;
2554 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2555 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2556 		log.u_bbr.flex8 = hpts_removed;
2557 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2558 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2559 		    &bbr->rc_inp->inp_socket->so_rcv,
2560 		    &bbr->rc_inp->inp_socket->so_snd,
2561 		    BBR_LOG_TIMERCANC, 0,
2562 		    0, &log, false, &bbr->rc_tv);
2563 	}
2564 }
2565 
2566 static void
2567 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2568 {
2569 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2570 		union tcp_log_stackspecific log;
2571 
2572 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2573 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2574 		log.u_bbr.flex2 = (peer_delta >> 32);
2575 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2576 		log.u_bbr.flex4 = (delta >> 32);
2577 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2578 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2579 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2580 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2581 		    &bbr->rc_inp->inp_socket->so_rcv,
2582 		    &bbr->rc_inp->inp_socket->so_snd,
2583 		    BBR_LOG_TSTMP_VAL, 0,
2584 		    0, &log, false, &bbr->rc_tv);
2585 	}
2586 }
2587 
2588 static void
2589 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)
2590 {
2591 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2592 		union tcp_log_stackspecific log;
2593 
2594 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2595 		log.u_bbr.flex1 = tsosz;
2596 		log.u_bbr.flex2 = tls;
2597 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2598 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2599 		log.u_bbr.flex5 = old_val;
2600 		log.u_bbr.flex6 = maxseg;
2601 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2602 		log.u_bbr.flex7 <<= 1;
2603 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2604 		if (hdwr)
2605 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2606 		else
2607 			log.u_bbr.flex8 = bbr->rc_use_google;
2608 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2609 		    &bbr->rc_inp->inp_socket->so_rcv,
2610 		    &bbr->rc_inp->inp_socket->so_snd,
2611 		    BBR_LOG_BBRTSO, 0,
2612 		    0, &log, false, &bbr->rc_tv);
2613 	}
2614 }
2615 
2616 static void
2617 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2618 		      uint32_t flags, uint32_t line)
2619 {
2620 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2621 		union tcp_log_stackspecific log;
2622 
2623 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2624 		log.u_bbr.flex1 = line;
2625 		log.u_bbr.flex2 = rsm->r_start;
2626 		log.u_bbr.flex3 = rsm->r_end;
2627 		log.u_bbr.flex4 = rsm->r_delivered;
2628 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2629 		log.u_bbr.flex6 = rsm->r_dupack;
2630 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2631 		log.u_bbr.flex8 = rsm->r_flags;
2632 		/* Hijack the pkts_out fids */
2633 		log.u_bbr.applimited = flags;
2634 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2635 		    &bbr->rc_inp->inp_socket->so_rcv,
2636 		    &bbr->rc_inp->inp_socket->so_snd,
2637 		    BBR_RSM_CLEARED, 0,
2638 		    0, &log, false, &bbr->rc_tv);
2639 	}
2640 }
2641 
2642 static void
2643 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2644     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2645     uint32_t flex6, uint32_t pkts_out, int flex7,
2646     uint32_t flex4, uint32_t flex1)
2647 {
2648 
2649 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2650 		union tcp_log_stackspecific log;
2651 
2652 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2653 		log.u_bbr.flex1 = flex1;
2654 		log.u_bbr.flex2 = flex2;
2655 		log.u_bbr.flex3 = flex3;
2656 		log.u_bbr.flex4 = flex4;
2657 		log.u_bbr.flex5 = flex5;
2658 		log.u_bbr.flex6 = flex6;
2659 		log.u_bbr.flex7 = flex7;
2660 		/* Hijack the pkts_out fids */
2661 		log.u_bbr.pkts_out = pkts_out;
2662 		log.u_bbr.flex8 = flex8;
2663 		if (bbr->rc_ack_was_delayed)
2664 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2665 		else
2666 			log.u_bbr.epoch = 0;
2667 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2668 		    &bbr->rc_inp->inp_socket->so_rcv,
2669 		    &bbr->rc_inp->inp_socket->so_snd,
2670 		    BBR_LOG_BBRUPD, 0,
2671 		    flex2, &log, false, &bbr->rc_tv);
2672 	}
2673 }
2674 
2675 static void
2676 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2677 	uint32_t newbw, uint32_t obw, uint32_t diff,
2678 	uint32_t tim)
2679 {
2680 	if (/*bbr_verbose_logging && */(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 = reason;
2685 		log.u_bbr.flex2 = newbw;
2686 		log.u_bbr.flex3 = obw;
2687 		log.u_bbr.flex4 = diff;
2688 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2689 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2690 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2691 		log.u_bbr.pkts_out = tim;
2692 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2693 		if (bbr->rc_lt_use_bw == 0)
2694 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2695 		else
2696 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2697 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2698 		    &bbr->rc_inp->inp_socket->so_rcv,
2699 		    &bbr->rc_inp->inp_socket->so_snd,
2700 		    BBR_LOG_BWSAMP, 0,
2701 		    0, &log, false, &bbr->rc_tv);
2702 	}
2703 }
2704 
2705 static inline void
2706 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2707 {
2708 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2709 		union tcp_log_stackspecific log;
2710 
2711 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2712 		log.u_bbr.flex1 = line;
2713 		log.u_bbr.flex2 = tick;
2714 		log.u_bbr.flex3 = tp->t_maxunacktime;
2715 		log.u_bbr.flex4 = tp->t_acktime;
2716 		log.u_bbr.flex8 = event;
2717 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2718 		    &bbr->rc_inp->inp_socket->so_rcv,
2719 		    &bbr->rc_inp->inp_socket->so_snd,
2720 		    BBR_LOG_PROGRESS, 0,
2721 		    0, &log, false, &bbr->rc_tv);
2722 	}
2723 }
2724 
2725 static void
2726 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2727 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2728 			 int error)
2729 {
2730 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2731 		union tcp_log_stackspecific log;
2732 
2733 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2734 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2735 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2736 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2737 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2738 		log.u_bbr.bw_inuse = rate;
2739 		log.u_bbr.flex5 = line;
2740 		log.u_bbr.flex6 = error;
2741 		log.u_bbr.flex8 = bbr->skip_gain;
2742 		log.u_bbr.flex8 <<= 1;
2743 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2744 		log.u_bbr.flex8 <<= 1;
2745 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2746 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2747 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2748 		    &bbr->rc_inp->inp_socket->so_rcv,
2749 		    &bbr->rc_inp->inp_socket->so_snd,
2750 		    BBR_LOG_HDWR_PACE, 0,
2751 		    0, &log, false, &bbr->rc_tv);
2752 	}
2753 }
2754 
2755 static void
2756 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)
2757 {
2758 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2759 		union tcp_log_stackspecific log;
2760 
2761 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2762 		log.u_bbr.flex1 = slot;
2763 		log.u_bbr.flex2 = del_by;
2764 		log.u_bbr.flex3 = prev_delay;
2765 		log.u_bbr.flex4 = line;
2766 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2767 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2768 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2769 		log.u_bbr.flex8 = bbr->rc_in_persist;
2770 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2771 		    &bbr->rc_inp->inp_socket->so_rcv,
2772 		    &bbr->rc_inp->inp_socket->so_snd,
2773 		    BBR_LOG_BBRSND, 0,
2774 		    len, &log, false, &bbr->rc_tv);
2775 	}
2776 }
2777 
2778 static void
2779 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)
2780 {
2781 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2782 		union tcp_log_stackspecific log;
2783 
2784 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2785 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2786 		log.u_bbr.flex2 = 0;
2787 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2788 		log.u_bbr.flex4 = end;
2789 		log.u_bbr.flex5 = seq;
2790 		log.u_bbr.flex6 = t;
2791 		log.u_bbr.flex7 = match;
2792 		log.u_bbr.flex8 = flags;
2793 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2794 		    &bbr->rc_inp->inp_socket->so_rcv,
2795 		    &bbr->rc_inp->inp_socket->so_snd,
2796 		    BBR_LOG_BBRRTT, 0,
2797 		    0, &log, false, &bbr->rc_tv);
2798 	}
2799 }
2800 
2801 static void
2802 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2803 {
2804 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2805 		union tcp_log_stackspecific log;
2806 
2807 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2808 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2809 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2810 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2811 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2812 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2813 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2814 		log.u_bbr.flex7 = 0;
2815 		log.u_bbr.flex8 = entry_method;
2816 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2817 		    &bbr->rc_inp->inp_socket->so_rcv,
2818 		    &bbr->rc_inp->inp_socket->so_snd,
2819 		    BBR_LOG_EXIT_GAIN, 0,
2820 		    0, &log, false, &bbr->rc_tv);
2821 	}
2822 }
2823 
2824 static void
2825 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2826 {
2827 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2828 		union tcp_log_stackspecific log;
2829 
2830 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2831 		/* R-HU */
2832 		log.u_bbr.flex1 = 0;
2833 		log.u_bbr.flex2 = 0;
2834 		log.u_bbr.flex3 = 0;
2835 		log.u_bbr.flex4 = 0;
2836 		log.u_bbr.flex7 = 0;
2837 		log.u_bbr.flex8 = settings_desired;
2838 
2839 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2840 		    &bbr->rc_inp->inp_socket->so_rcv,
2841 		    &bbr->rc_inp->inp_socket->so_snd,
2842 		    BBR_LOG_SETTINGS_CHG, 0,
2843 		    0, &log, false, &bbr->rc_tv);
2844 	}
2845 }
2846 
2847 /*
2848  * Returns the bw from the our filter.
2849  */
2850 static inline uint64_t
2851 bbr_get_full_bw(struct tcp_bbr *bbr)
2852 {
2853 	uint64_t bw;
2854 
2855 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2856 
2857 	return (bw);
2858 }
2859 
2860 static inline void
2861 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2862 {
2863 	uint64_t calclr;
2864 	uint32_t lost, del;
2865 
2866 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2867 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2868 	else
2869 		lost = 0;
2870 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2871 	if (lost == 0)  {
2872 		calclr = 0;
2873 	} else if (del) {
2874 		calclr = lost;
2875 		calclr *= (uint64_t)1000;
2876 		calclr /= (uint64_t)del;
2877 	} else {
2878 		/* Nothing delivered? 100.0% loss */
2879 		calclr = 1000;
2880 	}
2881 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2882 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2883 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2884 	bbr->r_ctl.rc_pkt_epoch++;
2885 	if (bbr->rc_no_pacing &&
2886 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2887 		bbr->rc_no_pacing = 0;
2888 		tcp_bbr_tso_size_check(bbr, cts);
2889 	}
2890 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2891 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2892 	/* What was our loss rate */
2893 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2894 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2895 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2896 }
2897 
2898 static inline void
2899 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2900 {
2901 	uint32_t epoch_time;
2902 
2903 	/* Tick the RTT clock */
2904 	bbr->r_ctl.rc_rtt_epoch++;
2905 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2906 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2907 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2908 }
2909 
2910 static inline void
2911 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2912 {
2913 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2914 		bbr->rc_is_pkt_epoch_now = 1;
2915 	}
2916 }
2917 
2918 /*
2919  * Returns the bw from either the b/w filter
2920  * or from the lt_bw (if the connection is being
2921  * policed).
2922  */
2923 static inline uint64_t
2924 __bbr_get_bw(struct tcp_bbr *bbr)
2925 {
2926 	uint64_t bw, min_bw;
2927 	uint64_t rtt;
2928 	int gm_measure_cnt = 1;
2929 
2930 	/*
2931 	 * For startup we make, like google, a
2932 	 * minimum b/w. This is generated from the
2933 	 * IW and the rttProp. We do fall back to srtt
2934 	 * if for some reason (initial handshake) we don't
2935 	 * have a rttProp. We, in the worst case, fall back
2936 	 * to the configured min_bw (rc_initial_hptsi_bw).
2937 	 */
2938 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2939 		/* Attempt first to use rttProp */
2940 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2941 		if (rtt && (rtt < 0xffffffff)) {
2942 measure:
2943 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2944 				((uint64_t)1000000);
2945 			min_bw /= rtt;
2946 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2947 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2948 			}
2949 
2950 		} else if (bbr->rc_tp->t_srtt != 0) {
2951 			/* No rttProp, use srtt? */
2952 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2953 			goto measure;
2954 		} else {
2955 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2956 		}
2957 	} else
2958 		min_bw = 0;
2959 
2960 	if ((bbr->rc_past_init_win == 0) &&
2961 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2962 		bbr->rc_past_init_win = 1;
2963 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2964 		gm_measure_cnt = 0;
2965 	if (gm_measure_cnt &&
2966 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2967 	     (bbr->rc_past_init_win == 0))) {
2968 		/* For google we use our guess rate until we get 1 measurement */
2969 
2970 use_initial_window:
2971 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2972 		if (rtt && (rtt < 0xffffffff)) {
2973 			/*
2974 			 * We have an RTT measurement. Use that in
2975 			 * combination with our initial window to calculate
2976 			 * a b/w.
2977 			 */
2978 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2979 				((uint64_t)1000000);
2980 			bw /= rtt;
2981 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2982 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2983 			}
2984 		} else {
2985 			/* Drop back to the 40 and punt to a default */
2986 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2987 		}
2988 		if (bw < 1)
2989 			/* Probably should panic */
2990 			bw = 1;
2991 		if (bw > min_bw)
2992 			return (bw);
2993 		else
2994 			return (min_bw);
2995 	}
2996 	if (bbr->rc_lt_use_bw)
2997 		bw = bbr->r_ctl.rc_lt_bw;
2998 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2999 		bw = bbr->r_ctl.red_bw;
3000 	else
3001 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3002 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3003 		/*
3004 		 * Enforce user set rate limit, keep in mind that
3005 		 * t_peakrate_thr is in B/s already
3006 		 */
3007 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3008 	}
3009 	if (bw == 0) {
3010 		/* We should not be at 0, go to the initial window then  */
3011 		goto use_initial_window;
3012 	}
3013 	if (bw < 1)
3014 		/* Probably should panic */
3015 		bw = 1;
3016 	if (bw < min_bw)
3017 		bw = min_bw;
3018 	return (bw);
3019 }
3020 
3021 static inline uint64_t
3022 bbr_get_bw(struct tcp_bbr *bbr)
3023 {
3024 	uint64_t bw;
3025 
3026 	bw = __bbr_get_bw(bbr);
3027 	return (bw);
3028 }
3029 
3030 static inline void
3031 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3032 {
3033 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3034 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3035 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3036 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3037 }
3038 
3039 static inline void
3040 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3041 {
3042 	bbr->rc_lt_is_sampling = 0;
3043 	bbr->rc_lt_use_bw = 0;
3044 	bbr->r_ctl.rc_lt_bw = 0;
3045 	bbr_reset_lt_bw_interval(bbr, cts);
3046 }
3047 
3048 static inline void
3049 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3050 {
3051 	uint64_t diff;
3052 
3053 	/* Do we have a previous sample? */
3054 	if (bbr->r_ctl.rc_lt_bw) {
3055 		/* Get the diff in bytes per second */
3056 		if (bbr->r_ctl.rc_lt_bw > bw)
3057 			diff = bbr->r_ctl.rc_lt_bw - bw;
3058 		else
3059 			diff = bw - bbr->r_ctl.rc_lt_bw;
3060 		if ((diff <= bbr_lt_bw_diff) ||
3061 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3062 			/* Consider us policed */
3063 			uint32_t saved_bw;
3064 
3065 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3066 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3067 			bbr->rc_lt_use_bw = 1;
3068 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3069 			/*
3070 			 * Use pkt based epoch for measuring length of
3071 			 * policer up
3072 			 */
3073 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3074 			/*
3075 			 * reason 4 is we need to start consider being
3076 			 * policed
3077 			 */
3078 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3079 			return;
3080 		}
3081 	}
3082 	bbr->r_ctl.rc_lt_bw = bw;
3083 	bbr_reset_lt_bw_interval(bbr, cts);
3084 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3085 }
3086 
3087 static void
3088 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3089 {
3090 	uint32_t ran, deduct;
3091 
3092 	ran = arc4random_uniform(bbr_rand_ot);
3093 	if (ran) {
3094 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3095 		bbr->r_ctl.rc_level_state_extra -= deduct;
3096 	}
3097 }
3098 /*
3099  * Return randomly the starting state
3100  * to use in probebw.
3101  */
3102 static uint8_t
3103 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3104 {
3105 	uint32_t ran;
3106 	uint8_t ret_val;
3107 
3108 	/* Initialize the offset to 0 */
3109 	bbr->r_ctl.rc_exta_time_gd = 0;
3110 	bbr->rc_hit_state_1 = 0;
3111 	bbr->r_ctl.rc_level_state_extra = 0;
3112 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3113 	/*
3114 	 * The math works funny here :) the return value is used to set the
3115 	 * substate and then the state change is called which increments by
3116 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3117 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3118 	 * we return 1 - 7, so we dont return 0 and end up starting in
3119 	 * state 1 (DRAIN).
3120 	 */
3121 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3122 	/* Set an epoch */
3123 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3124 		bbr_set_epoch(bbr, cts, __LINE__);
3125 
3126 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3127 	return (ret_val);
3128 }
3129 
3130 static void
3131 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3132 {
3133 	uint32_t diff, d_time;
3134 	uint64_t del_time, bw, lost, delivered;
3135 
3136 	if (bbr->r_use_policer == 0)
3137 		return;
3138 	if (bbr->rc_lt_use_bw) {
3139 		/* We are using lt bw do we stop yet? */
3140 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3141 		if (diff > bbr_lt_bw_max_rtts) {
3142 			/* Reset it all */
3143 reset_all:
3144 			bbr_reset_lt_bw_sampling(bbr, cts);
3145 			if (bbr->rc_filled_pipe) {
3146 				bbr_set_epoch(bbr, cts, __LINE__);
3147 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3148 				bbr_substate_change(bbr, cts, __LINE__, 0);
3149 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3150 				bbr_log_type_statechange(bbr, cts, __LINE__);
3151 			} else {
3152 				/*
3153 				 * This should not happen really
3154 				 * unless we remove the startup/drain
3155 				 * restrictions above.
3156 				 */
3157 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3158 				bbr_set_epoch(bbr, cts, __LINE__);
3159 				bbr->r_ctl.rc_bbr_state_time = cts;
3160 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3161 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3162 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3163 				bbr_set_state_target(bbr, __LINE__);
3164 				bbr_log_type_statechange(bbr, cts, __LINE__);
3165 			}
3166 			/* reason 0 is to stop using lt-bw */
3167 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3168 			return;
3169 		}
3170 		if (bbr_lt_intvl_fp == 0) {
3171 			/* Not doing false-postive detection */
3172 			return;
3173 		}
3174 		/* False positive detection */
3175 		if (diff == bbr_lt_intvl_fp) {
3176 			/* At bbr_lt_intvl_fp we record the lost */
3177 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3178 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3179 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3180 			/* Now is our loss rate still high? */
3181 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3182 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3183 			if ((delivered == 0) ||
3184 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3185 				/* No still below our threshold */
3186 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3187 			} else {
3188 				/* Yikes its still high, it must be a false positive */
3189 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3190 				goto reset_all;
3191 			}
3192 		}
3193 		return;
3194 	}
3195 	/*
3196 	 * Wait for the first loss before sampling, to let the policer
3197 	 * exhaust its tokens and estimate the steady-state rate allowed by
3198 	 * the policer. Starting samples earlier includes bursts that
3199 	 * over-estimate the bw.
3200 	 */
3201 	if (bbr->rc_lt_is_sampling == 0) {
3202 		/* reason 1 is to begin doing the sampling  */
3203 		if (loss_detected == 0)
3204 			return;
3205 		bbr_reset_lt_bw_interval(bbr, cts);
3206 		bbr->rc_lt_is_sampling = 1;
3207 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3208 		return;
3209 	}
3210 	/* Now how long were we delivering long term last> */
3211 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3212 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3213 	else
3214 		d_time = 0;
3215 
3216 	/* To avoid underestimates, reset sampling if we run out of data. */
3217 	if (bbr->r_ctl.r_app_limited_until) {
3218 		/* Can not measure in app-limited state */
3219 		bbr_reset_lt_bw_sampling(bbr, cts);
3220 		/* reason 2 is to reset sampling due to app limits  */
3221 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3222 		return;
3223 	}
3224 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3225 	if (diff < bbr_lt_intvl_min_rtts) {
3226 		/*
3227 		 * need more samples (we don't
3228 		 * start on a round like linux so
3229 		 * we need 1 more).
3230 		 */
3231 		/* 6 is not_enough time or no-loss */
3232 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3233 		return;
3234 	}
3235 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3236 		/*
3237 		 * For now if we wait too long, reset all sampling. We need
3238 		 * to do some research here, its possible that we should
3239 		 * base this on how much loss as occurred.. something like
3240 		 * if its under 10% (or some thresh) reset all otherwise
3241 		 * don't.  Thats for phase II I guess.
3242 		 */
3243 		bbr_reset_lt_bw_sampling(bbr, cts);
3244  		/* reason 3 is to reset sampling due too long of sampling */
3245 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3246 		return;
3247 	}
3248 	/*
3249 	 * End sampling interval when a packet is lost, so we estimate the
3250 	 * policer tokens were exhausted. Stopping the sampling before the
3251 	 * tokens are exhausted under-estimates the policed rate.
3252 	 */
3253 	if (loss_detected == 0) {
3254 		/* 6 is not_enough time or no-loss */
3255 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3256 		return;
3257 	}
3258 	/* Calculate packets lost and delivered in sampling interval. */
3259 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3260 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3261 	if ((delivered == 0) ||
3262 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3263 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3264 		return;
3265 	}
3266 	if (d_time < 1000) {
3267 		/* Not enough time. wait */
3268 		/* 6 is not_enough time or no-loss */
3269 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3270 		return;
3271 	}
3272 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3273 		/* Too long */
3274 		bbr_reset_lt_bw_sampling(bbr, cts);
3275  		/* reason 3 is to reset sampling due too long of sampling */
3276 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3277 		return;
3278 	}
3279 	del_time = d_time;
3280 	bw = delivered;
3281 	bw *= (uint64_t)USECS_IN_SECOND;
3282 	bw /= del_time;
3283 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3284 }
3285 
3286 /*
3287  * Allocate a sendmap from our zone.
3288  */
3289 static struct bbr_sendmap *
3290 bbr_alloc(struct tcp_bbr *bbr)
3291 {
3292 	struct bbr_sendmap *rsm;
3293 
3294 	BBR_STAT_INC(bbr_to_alloc);
3295 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3296 	if (rsm) {
3297 		bbr->r_ctl.rc_num_maps_alloced++;
3298 		return (rsm);
3299 	}
3300 	if (bbr->r_ctl.rc_free_cnt) {
3301 		BBR_STAT_INC(bbr_to_alloc_emerg);
3302 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3303 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3304 		bbr->r_ctl.rc_free_cnt--;
3305 		return (rsm);
3306 	}
3307 	BBR_STAT_INC(bbr_to_alloc_failed);
3308 	return (NULL);
3309 }
3310 
3311 static struct bbr_sendmap *
3312 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3313 {
3314 	if ((V_tcp_map_entries_limit > 0) &&
3315 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3316 		BBR_STAT_INC(bbr_alloc_limited);
3317 		if (!bbr->alloc_limit_reported) {
3318 			bbr->alloc_limit_reported = 1;
3319 			BBR_STAT_INC(bbr_alloc_limited_conns);
3320 		}
3321 		return (NULL);
3322 	}
3323 	return (bbr_alloc(bbr));
3324 }
3325 
3326 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3327 static struct bbr_sendmap *
3328 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3329 {
3330 	struct bbr_sendmap *rsm;
3331 
3332 	if (limit_type) {
3333 		/* currently there is only one limit type */
3334 		if (V_tcp_map_split_limit > 0 &&
3335 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3336 			BBR_STAT_INC(bbr_split_limited);
3337 			if (!bbr->alloc_limit_reported) {
3338 				bbr->alloc_limit_reported = 1;
3339 				BBR_STAT_INC(bbr_alloc_limited_conns);
3340 			}
3341 			return (NULL);
3342 		}
3343 	}
3344 
3345 	/* allocate and mark in the limit type, if set */
3346 	rsm = bbr_alloc(bbr);
3347 	if (rsm != NULL && limit_type) {
3348 		rsm->r_limit_type = limit_type;
3349 		bbr->r_ctl.rc_num_split_allocs++;
3350 	}
3351 	return (rsm);
3352 }
3353 
3354 static void
3355 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3356 {
3357 	if (rsm->r_limit_type) {
3358 		/* currently there is only one limit type */
3359 		bbr->r_ctl.rc_num_split_allocs--;
3360 	}
3361 	if (rsm->r_is_smallmap)
3362 		bbr->r_ctl.rc_num_small_maps_alloced--;
3363 	if (bbr->r_ctl.rc_tlp_send == rsm)
3364 		bbr->r_ctl.rc_tlp_send = NULL;
3365 	if (bbr->r_ctl.rc_resend == rsm) {
3366 		bbr->r_ctl.rc_resend = NULL;
3367 	}
3368 	if (bbr->r_ctl.rc_next == rsm)
3369 		bbr->r_ctl.rc_next = NULL;
3370 	if (bbr->r_ctl.rc_sacklast == rsm)
3371 		bbr->r_ctl.rc_sacklast = NULL;
3372 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3373 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3374 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3375 		rsm->r_limit_type = 0;
3376 		bbr->r_ctl.rc_free_cnt++;
3377 		return;
3378 	}
3379 	bbr->r_ctl.rc_num_maps_alloced--;
3380 	uma_zfree(bbr_zone, rsm);
3381 }
3382 
3383 /*
3384  * Returns the BDP.
3385  */
3386 static uint64_t
3387 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3388 	/*
3389 	 * Calculate the bytes in flight needed given the bw (in bytes per
3390 	 * second) and the specifyed rtt in useconds. We need to put out the
3391 	 * returned value per RTT to match that rate. Gain will normally
3392 	 * raise it up from there.
3393 	 *
3394 	 * This should not overflow as long as the bandwidth is below 1
3395 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3396 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3397 	 */
3398 	uint64_t usec_per_sec;
3399 
3400 	usec_per_sec = USECS_IN_SECOND;
3401 	return ((rtt * bw) / usec_per_sec);
3402 }
3403 
3404 /*
3405  * Return the initial cwnd.
3406  */
3407 static uint32_t
3408 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3409 {
3410 	uint32_t i_cwnd;
3411 
3412 	if (bbr->rc_init_win) {
3413 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3414 	} else if (V_tcp_initcwnd_segments)
3415 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3416 		    max(2 * tp->t_maxseg, 14600));
3417 	else if (V_tcp_do_rfc3390)
3418 		i_cwnd = min(4 * tp->t_maxseg,
3419 		    max(2 * tp->t_maxseg, 4380));
3420 	else {
3421 		/* Per RFC5681 Section 3.1 */
3422 		if (tp->t_maxseg > 2190)
3423 			i_cwnd = 2 * tp->t_maxseg;
3424 		else if (tp->t_maxseg > 1095)
3425 			i_cwnd = 3 * tp->t_maxseg;
3426 		else
3427 			i_cwnd = 4 * tp->t_maxseg;
3428 	}
3429 	return (i_cwnd);
3430 }
3431 
3432 /*
3433  * Given a specified gain, return the target
3434  * cwnd based on that gain.
3435  */
3436 static uint32_t
3437 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3438 {
3439 	uint64_t bdp, rtt;
3440 	uint32_t cwnd;
3441 
3442 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3443 	    (bbr_get_full_bw(bbr) == 0)) {
3444 		/* No measurements yet */
3445 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3446 	}
3447 	/*
3448 	 * Get bytes per RTT needed (rttProp is normally in
3449 	 * bbr_cwndtarget_rtt_touse)
3450 	 */
3451 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3452 	/* Get the bdp from the two values */
3453 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3454 	/* Now apply the gain */
3455 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3456 
3457 	return (cwnd);
3458 }
3459 
3460 static uint32_t
3461 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3462 {
3463 	uint32_t cwnd, mss;
3464 
3465 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3466 	/* Get the base cwnd with gain rounded to a mss */
3467 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3468 	/*
3469 	 * Add in N (2 default since we do not have a
3470 	 * fq layer to trap packets in) quanta's per the I-D
3471 	 * section 4.2.3.2 quanta adjust.
3472 	 */
3473 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3474 	if (bbr->rc_use_google) {
3475 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3476 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3477 			/*
3478 			 * The linux implementation adds
3479 			 * an extra 2 x mss in gain cycle which
3480 			 * is documented no-where except in the code.
3481 			 * so we add more for Neal undocumented feature
3482 			 */
3483 			cwnd += 2 * mss;
3484 		}
3485  		if ((cwnd / mss) & 0x1) {
3486 			/* Round up for odd num mss */
3487 			cwnd += mss;
3488 		}
3489 	}
3490 	/* Are we below the min cwnd? */
3491 	if (cwnd < get_min_cwnd(bbr))
3492 		return (get_min_cwnd(bbr));
3493 	return (cwnd);
3494 }
3495 
3496 static uint16_t
3497 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3498 {
3499 	if (gain < 1)
3500 		gain = 1;
3501 	return (gain);
3502 }
3503 
3504 static uint32_t
3505 bbr_get_header_oh(struct tcp_bbr *bbr)
3506 {
3507 	int seg_oh;
3508 
3509 	seg_oh = 0;
3510 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3511 		/* Do we include TCP overhead? */
3512 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3513 	}
3514 	if (bbr->r_ctl.rc_inc_ip_oh) {
3515 		/* Do we include IP overhead? */
3516 #ifdef INET6
3517 		if (bbr->r_is_v6) {
3518 			seg_oh += sizeof(struct ip6_hdr);
3519 		} else
3520 #endif
3521 		{
3522 
3523 #ifdef INET
3524 			seg_oh += sizeof(struct ip);
3525 #endif
3526 		}
3527 	}
3528 	if (bbr->r_ctl.rc_inc_enet_oh) {
3529 		/* Do we include the ethernet overhead?  */
3530 		seg_oh += sizeof(struct ether_header);
3531 	}
3532 	return(seg_oh);
3533 }
3534 
3535 static uint32_t
3536 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3537 {
3538 	uint64_t divor, res, tim;
3539 
3540 	if (useconds_time == 0)
3541 		return (0);
3542 	gain = bbr_gain_adjust(bbr, gain);
3543 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3544 	tim = useconds_time;
3545 	res = (tim * bw * gain) / divor;
3546 	if (res == 0)
3547 		res = 1;
3548 	return ((uint32_t)res);
3549 }
3550 
3551 /*
3552  * Given a gain and a length return the delay in useconds that
3553  * should be used to evenly space out packets
3554  * on the connection (based on the gain factor).
3555  */
3556 static uint32_t
3557 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3558 {
3559 	uint64_t bw, lentim, res;
3560 	uint32_t usecs, srtt, over = 0;
3561 	uint32_t seg_oh, num_segs, maxseg;
3562 
3563 	if (len == 0)
3564 		return (0);
3565 
3566 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3567 	num_segs = (len + maxseg - 1) / maxseg;
3568 	if (bbr->rc_use_google == 0) {
3569 		seg_oh = bbr_get_header_oh(bbr);
3570 		len += (num_segs * seg_oh);
3571 	}
3572 	gain = bbr_gain_adjust(bbr, gain);
3573 	bw = bbr_get_bw(bbr);
3574 	if (bbr->rc_use_google) {
3575 		uint64_t cbw;
3576 
3577 		/*
3578 		 * Reduce the b/w by the google discount
3579 		 * factor 10 = 1%.
3580 		 */
3581 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3582 		cbw /= (uint64_t)1000;
3583 		/* We don't apply a discount if it results in 0 */
3584 		if (cbw > 0)
3585 			bw = cbw;
3586 	}
3587 	lentim = ((uint64_t)len *
3588 		  (uint64_t)USECS_IN_SECOND *
3589 		  (uint64_t)BBR_UNIT);
3590 	res = lentim / ((uint64_t)gain * bw);
3591 	if (res == 0)
3592 		res = 1;
3593 	usecs = (uint32_t)res;
3594 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3595 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3596 	    (bbr->rc_use_google == 0) &&
3597 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3598 		/*
3599 		 * We cannot let the delay be more than 1/2 the srtt time.
3600 		 * Otherwise we cannot pace out or send properly.
3601 		 */
3602 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3603 		BBR_STAT_INC(bbr_hpts_min_time);
3604 	}
3605 	if (!nolog)
3606 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3607 	return (usecs);
3608 }
3609 
3610 static void
3611 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3612 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3613 {
3614 	INP_WLOCK_ASSERT(tp->t_inpcb);
3615 	uint64_t bw;
3616 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3617 	int32_t meth;
3618 
3619 #ifdef STATS
3620 	if ((tp->t_flags & TF_GPUTINPROG) &&
3621 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3622 		/*
3623 		 * Strech acks and compressed acks will cause this to
3624 		 * oscillate but we are doing it the same way as the main
3625 		 * stack so it will be compariable (though possibly not
3626 		 * ideal).
3627 		 */
3628 		int32_t cgput;
3629 		int64_t gput, time_stamp;
3630 
3631 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3632 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3633 		cgput = gput / time_stamp;
3634 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3635 					 cgput);
3636 		if (tp->t_stats_gput_prev > 0)
3637 			stats_voi_update_abs_s32(tp->t_stats,
3638 						 VOI_TCP_GPUT_ND,
3639 						 ((gput - tp->t_stats_gput_prev) * 100) /
3640 						 tp->t_stats_gput_prev);
3641 		tp->t_flags &= ~TF_GPUTINPROG;
3642 		tp->t_stats_gput_prev = cgput;
3643 	}
3644 #endif
3645 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3646 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3647 		/* We don't change anything in probe-rtt */
3648 		return;
3649 	}
3650 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3651 	saved_bytes = bytes_this_ack;
3652 	bytes_this_ack += sack_changed;
3653 	if (bytes_this_ack > prev_acked) {
3654 		bytes_this_ack -= prev_acked;
3655 		/*
3656 		 * A byte ack'd gives us a full mss
3657 		 * to be like linux i.e. they count packets.
3658 		 */
3659 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3660 			bytes_this_ack = maxseg;
3661 	} else {
3662 		/* Unlikely */
3663 		bytes_this_ack = 0;
3664 	}
3665 	cwnd = tp->snd_cwnd;
3666 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3667 	if (bw)
3668 		target_cwnd = bbr_get_target_cwnd(bbr,
3669 						  bw,
3670 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3671 	else
3672 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3673 	if (IN_RECOVERY(tp->t_flags) &&
3674 	    (bbr->bbr_prev_in_rec == 0)) {
3675 		/*
3676 		 * We are entering recovery and
3677 		 * thus packet conservation.
3678 		 */
3679 		bbr->pkt_conservation = 1;
3680 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3681 		cwnd = ctf_flight_size(tp,
3682 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3683 			bytes_this_ack;
3684 	}
3685 	if (IN_RECOVERY(tp->t_flags)) {
3686 		uint32_t flight;
3687 
3688 		bbr->bbr_prev_in_rec = 1;
3689 		if (cwnd > losses) {
3690 			cwnd -= losses;
3691 			if (cwnd < maxseg)
3692 				cwnd = maxseg;
3693 		} else
3694 			cwnd = maxseg;
3695 		flight = ctf_flight_size(tp,
3696 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3697 		bbr_log_type_cwndupd(bbr, flight, 0,
3698 				     losses, 10, 0, 0, line);
3699 		if (bbr->pkt_conservation) {
3700 			uint32_t time_in;
3701 
3702 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3703 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3704 			else
3705 				time_in = 0;
3706 
3707 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3708 				/* Clear packet conservation after an rttProp */
3709 				bbr->pkt_conservation = 0;
3710 			} else {
3711 				if ((flight + bytes_this_ack) > cwnd)
3712 					cwnd = flight + bytes_this_ack;
3713 				if (cwnd < get_min_cwnd(bbr))
3714 					cwnd = get_min_cwnd(bbr);
3715 				tp->snd_cwnd = cwnd;
3716 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3717 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3718 				return;
3719 			}
3720 		}
3721 	} else
3722 		bbr->bbr_prev_in_rec = 0;
3723 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3724 		bbr->r_ctl.restrict_growth--;
3725 		if (bytes_this_ack > maxseg)
3726 			bytes_this_ack = maxseg;
3727 	}
3728 	if (bbr->rc_filled_pipe) {
3729 		/*
3730 		 * Here we have exited startup and filled the pipe. We will
3731 		 * thus allow the cwnd to shrink to the target. We hit here
3732 		 * mostly.
3733 		 */
3734 		uint32_t s_cwnd;
3735 
3736 		meth = 2;
3737 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3738 		if (s_cwnd > cwnd)
3739 			cwnd = s_cwnd;
3740 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3741 			cwnd = s_cwnd;
3742 	} else {
3743 		/*
3744 		 * Here we are still in startup, we increase cwnd by what
3745 		 * has been acked.
3746 		 */
3747 		if ((cwnd < target_cwnd) ||
3748 		    (bbr->rc_past_init_win == 0)) {
3749 			meth = 3;
3750 			cwnd += bytes_this_ack;
3751 		} else {
3752 			/*
3753 			 * Method 4 means we are at target so no gain in
3754 			 * startup and past the initial window.
3755 			 */
3756 			meth = 4;
3757 		}
3758 	}
3759 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3760 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3761 }
3762 
3763 static void
3764 tcp_bbr_partialack(struct tcpcb *tp)
3765 {
3766 	struct tcp_bbr *bbr;
3767 
3768 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3769 	INP_WLOCK_ASSERT(tp->t_inpcb);
3770 	if (ctf_flight_size(tp,
3771 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3772 	    tp->snd_cwnd) {
3773 		bbr->r_wanted_output = 1;
3774 	}
3775 }
3776 
3777 static void
3778 bbr_post_recovery(struct tcpcb *tp)
3779 {
3780 	struct tcp_bbr *bbr;
3781 	uint32_t  flight;
3782 
3783 	INP_WLOCK_ASSERT(tp->t_inpcb);
3784 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3785 	/*
3786 	 * Here we just exit recovery.
3787 	 */
3788 	EXIT_RECOVERY(tp->t_flags);
3789 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3790 	bbr->r_recovery_bw = 0;
3791 	tp->snd_recover = tp->snd_una;
3792 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3793 	bbr->pkt_conservation = 0;
3794 	if (bbr->rc_use_google == 0) {
3795 		/*
3796 		 * For non-google mode lets
3797 		 * go ahead and make sure we clear
3798 		 * the recovery state so if we
3799 		 * bounce back in to recovery we
3800 		 * will do PC.
3801 		 */
3802 		bbr->bbr_prev_in_rec = 0;
3803 	}
3804 	bbr_log_type_exit_rec(bbr);
3805 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3806 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3807 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3808 	} else {
3809 		/* For probe-rtt case lets fix up its saved_cwnd */
3810 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3811 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3812 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3813 		}
3814 	}
3815 	flight = ctf_flight_size(tp,
3816 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3817 	if ((bbr->rc_use_google == 0) &&
3818 	    bbr_do_red) {
3819 		uint64_t val, lr2use;
3820 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3821 		uint32_t *cwnd_p;
3822 
3823 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3824 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3825 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3826 			ratio = (uint32_t)val;
3827 		} else
3828 			ratio = 1000;
3829 
3830 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3831 				     bbr->r_ctl.recovery_lr, 21,
3832 				     ratio,
3833 				     bbr->r_ctl.rc_red_cwnd_pe,
3834 				     __LINE__);
3835 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3836 			goto done;
3837 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3838 		     bbr_prtt_slam_cwnd) ||
3839 		    (bbr_sub_drain_slam_cwnd &&
3840 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3841 		     bbr->rc_hit_state_1 &&
3842 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3843 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3844 		     bbr_slam_cwnd_in_main_drain)) {
3845 			/*
3846 			 * Here we must poke at the saved cwnd
3847 			 * as well as the cwnd.
3848 			 */
3849 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3850 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3851 		} else {
3852  			cwnd = tp->snd_cwnd;
3853 			cwnd_p = &tp->snd_cwnd;
3854 		}
3855 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3856 		/* Add the overall lr with the recovery lr */
3857 		if (bbr->r_ctl.rc_lost == 0)
3858 			lr2use = 0;
3859 		else if (bbr->r_ctl.rc_delivered == 0)
3860 			lr2use = 1000;
3861 		else {
3862 			lr2use = bbr->r_ctl.rc_lost * 1000;
3863 			lr2use /= bbr->r_ctl.rc_delivered;
3864 		}
3865 		lr2use += bbr->r_ctl.recovery_lr;
3866 		acks_inflight = (flight / (maxseg * 2));
3867 		if (bbr_red_scale) {
3868 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3869 			lr2use /= bbr_red_scale;
3870 			if ((bbr_red_growth_restrict) &&
3871 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3872 			    bbr->r_ctl.restrict_growth += acks_inflight;
3873 		}
3874 		if (lr2use) {
3875 			val = (uint64_t)cwnd * lr2use;
3876 			val /= 1000;
3877 			if (cwnd > val)
3878 				newcwnd = roundup((cwnd - val), maxseg);
3879 			else
3880 				newcwnd = maxseg;
3881 		} else {
3882 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3883 			val /= (uint64_t)bbr_red_div;
3884 			newcwnd = roundup((uint32_t)val, maxseg);
3885 		}
3886 		/* with standard delayed acks how many acks can I expect? */
3887 		if (bbr_drop_limit == 0) {
3888 			/*
3889 			 * Anticpate how much we will
3890 			 * raise the cwnd based on the acks.
3891 			 */
3892 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3893 				/* We do enforce the min (with the acks) */
3894 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3895 			}
3896 		} else {
3897 			/*
3898 			 * A strict drop limit of N is is inplace
3899 			 */
3900 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3901 				newcwnd = bbr_drop_limit * maxseg;
3902 			}
3903 		}
3904 		/* For the next N acks do we restrict the growth */
3905 		*cwnd_p = newcwnd;
3906 		if (tp->snd_cwnd > newcwnd)
3907 			tp->snd_cwnd = newcwnd;
3908 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3909 				     (uint32_t)lr2use,
3910 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3911 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3912 	}
3913 done:
3914 	bbr->r_ctl.recovery_lr = 0;
3915 	if (flight <= tp->snd_cwnd) {
3916 		bbr->r_wanted_output = 1;
3917 	}
3918 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3919 }
3920 
3921 static void
3922 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3923 {
3924 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3925 	/* Limit the drop in b/w to 1/2 our current filter. */
3926 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3927 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3928 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3929 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3930 	tcp_bbr_tso_size_check(bbr, cts);
3931 }
3932 
3933 static void
3934 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3935 {
3936 	struct tcp_bbr *bbr;
3937 
3938 	INP_WLOCK_ASSERT(tp->t_inpcb);
3939 #ifdef STATS
3940 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3941 #endif
3942 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3943 	switch (type) {
3944 	case CC_NDUPACK:
3945 		if (!IN_RECOVERY(tp->t_flags)) {
3946 			tp->snd_recover = tp->snd_max;
3947 			/* Start a new epoch */
3948 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3949 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3950 				/*
3951 				 * Move forward the lt epoch
3952 				 * so it won't count the truncated
3953 				 * epoch.
3954 				 */
3955 				bbr->r_ctl.rc_lt_epoch++;
3956 			}
3957 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3958 				/*
3959 				 * Just like the policer detection code
3960 				 * if we are in startup we must push
3961 				 * forward the last startup epoch
3962 				 * to hide the truncated PE.
3963 				 */
3964 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3965 			}
3966 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3967 			ENTER_RECOVERY(tp->t_flags);
3968 			bbr->rc_tlp_rtx_out = 0;
3969 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3970 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3971 			if (tcp_in_hpts(bbr->rc_inp) &&
3972 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3973 				/*
3974 				 * When we enter recovery, we need to restart
3975 				 * any timers. This may mean we gain an agg
3976 				 * early, which will be made up for at the last
3977 				 * rxt out.
3978 				 */
3979 				bbr->rc_timer_first = 1;
3980 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3981 			}
3982 			/*
3983 			 * Calculate a new cwnd based on to the current
3984 			 * delivery rate with no gain. We get the bdp
3985 			 * without gaining it up like we normally would and
3986 			 * we use the last cur_del_rate.
3987 			 */
3988 			if ((bbr->rc_use_google == 0) &&
3989 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3990 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3991 				tp->snd_cwnd = ctf_flight_size(tp,
3992 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3993 					(tp->t_maxseg - bbr->rc_last_options);
3994 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3995 					/* We always gate to min cwnd */
3996 					tp->snd_cwnd = get_min_cwnd(bbr);
3997 				}
3998 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3999 			}
4000 			bbr_log_type_enter_rec(bbr, rsm->r_start);
4001 		}
4002 		break;
4003 	case CC_RTO_ERR:
4004 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4005 		/* RTO was unnecessary, so reset everything. */
4006 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4007 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4008 			tp->snd_cwnd = tp->snd_cwnd_prev;
4009 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4010 			tp->snd_recover = tp->snd_recover_prev;
4011 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4012 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4013 		}
4014 		tp->t_badrxtwin = 0;
4015 		break;
4016 	}
4017 }
4018 
4019 /*
4020  * Indicate whether this ack should be delayed.  We can delay the ack if
4021  * following conditions are met:
4022  *	- There is no delayed ack timer in progress.
4023  *	- Our last ack wasn't a 0-sized window. We never want to delay
4024  *	  the ack that opens up a 0-sized window.
4025  *	- LRO wasn't used for this segment. We make sure by checking that the
4026  *	  segment size is not larger than the MSS.
4027  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4028  *	  connection.
4029  *	- The data being acked is less than a full segment (a stretch ack
4030  *        of more than a segment we should ack.
4031  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4032  */
4033 #define DELAY_ACK(tp, bbr, nsegs)				\
4034 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4035 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4036 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4037 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4038 
4039 /*
4040  * Return the lowest RSM in the map of
4041  * packets still in flight that is not acked.
4042  * This should normally find on the first one
4043  * since we remove packets from the send
4044  * map after they are marked ACKED.
4045  */
4046 static struct bbr_sendmap *
4047 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4048 {
4049 	struct bbr_sendmap *rsm;
4050 
4051 	/*
4052 	 * Walk the time-order transmitted list looking for an rsm that is
4053 	 * not acked. This will be the one that was sent the longest time
4054 	 * ago that is still outstanding.
4055 	 */
4056 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4057 		if (rsm->r_flags & BBR_ACKED) {
4058 			continue;
4059 		}
4060 		goto finish;
4061 	}
4062 finish:
4063 	return (rsm);
4064 }
4065 
4066 static struct bbr_sendmap *
4067 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4068 {
4069 	struct bbr_sendmap *prsm;
4070 
4071 	/*
4072 	 * Walk the sequence order list backward until we hit and arrive at
4073 	 * the highest seq not acked. In theory when this is called it
4074 	 * should be the last segment (which it was not).
4075 	 */
4076 	prsm = rsm;
4077 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4078 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4079 			continue;
4080 		}
4081 		return (prsm);
4082 	}
4083 	return (NULL);
4084 }
4085 
4086 /*
4087  * Returns to the caller the number of microseconds that
4088  * the packet can be outstanding before we think we
4089  * should have had an ack returned.
4090  */
4091 static uint32_t
4092 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4093 {
4094 	/*
4095 	 * lro is the flag we use to determine if we have seen reordering.
4096 	 * If it gets set we have seen reordering. The reorder logic either
4097 	 * works in one of two ways:
4098 	 *
4099 	 * If reorder-fade is configured, then we track the last time we saw
4100 	 * re-ordering occur. If we reach the point where enough time as
4101 	 * passed we no longer consider reordering has occuring.
4102 	 *
4103 	 * Or if reorder-face is 0, then once we see reordering we consider
4104 	 * the connection to alway be subject to reordering and just set lro
4105 	 * to 1.
4106 	 *
4107 	 * In the end if lro is non-zero we add the extra time for
4108 	 * reordering in.
4109 	 */
4110 	int32_t lro;
4111 	uint32_t thresh, t_rxtcur;
4112 
4113 	if (srtt == 0)
4114 		srtt = 1;
4115 	if (bbr->r_ctl.rc_reorder_ts) {
4116 		if (bbr->r_ctl.rc_reorder_fade) {
4117 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4118 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4119 				if (lro == 0) {
4120 					/*
4121 					 * No time as passed since the last
4122 					 * reorder, mark it as reordering.
4123 					 */
4124 					lro = 1;
4125 				}
4126 			} else {
4127 				/* Negative time? */
4128 				lro = 0;
4129 			}
4130 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4131 				/* Turn off reordering seen too */
4132 				bbr->r_ctl.rc_reorder_ts = 0;
4133 				lro = 0;
4134 			}
4135 		} else {
4136 			/* Reodering does not fade */
4137 			lro = 1;
4138 		}
4139 	} else {
4140 		lro = 0;
4141 	}
4142 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4143 	if (lro) {
4144 		/* It must be set, if not you get 1/4 rtt */
4145 		if (bbr->r_ctl.rc_reorder_shift)
4146 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4147 		else
4148 			thresh += (srtt >> 2);
4149 	} else {
4150 		thresh += 1000;
4151 	}
4152 	/* We don't let the rack timeout be above a RTO */
4153 	if ((bbr->rc_tp)->t_srtt == 0)
4154 		t_rxtcur = BBR_INITIAL_RTO;
4155 	else
4156 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4157 	if (thresh > t_rxtcur) {
4158 		thresh = t_rxtcur;
4159 	}
4160 	/* And we don't want it above the RTO max either */
4161 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4162 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4163 	}
4164 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4165 	return (thresh);
4166 }
4167 
4168 /*
4169  * Return to the caller the amount of time in mico-seconds
4170  * that should be used for the TLP timer from the last
4171  * send time of this packet.
4172  */
4173 static uint32_t
4174 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4175     struct bbr_sendmap *rsm, uint32_t srtt,
4176     uint32_t cts)
4177 {
4178 	uint32_t thresh, len, maxseg, t_rxtcur;
4179 	struct bbr_sendmap *prsm;
4180 
4181 	if (srtt == 0)
4182 		srtt = 1;
4183 	if (bbr->rc_tlp_threshold)
4184 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4185 	else
4186 		thresh = (srtt * 2);
4187 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4188 	/* Get the previous sent packet, if any  */
4189 	len = rsm->r_end - rsm->r_start;
4190 
4191 	/* 2.1 behavior */
4192 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4193 	if (prsm && (len <= maxseg)) {
4194 		/*
4195 		 * Two packets outstanding, thresh should be (2*srtt) +
4196 		 * possible inter-packet delay (if any).
4197 		 */
4198 		uint32_t inter_gap = 0;
4199 		int idx, nidx;
4200 
4201 		idx = rsm->r_rtr_cnt - 1;
4202 		nidx = prsm->r_rtr_cnt - 1;
4203 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4204 			/* Yes it was sent later (or at the same time) */
4205 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4206 		}
4207 		thresh += inter_gap;
4208 	} else if (len <= maxseg) {
4209 		/*
4210 		 * Possibly compensate for delayed-ack.
4211 		 */
4212 		uint32_t alt_thresh;
4213 
4214 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4215 		if (alt_thresh > thresh)
4216 			thresh = alt_thresh;
4217 	}
4218 	/* Not above the current  RTO */
4219 	if (tp->t_srtt == 0)
4220 		t_rxtcur = BBR_INITIAL_RTO;
4221 	else
4222 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4223 
4224 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4225 	/* Not above an RTO */
4226 	if (thresh > t_rxtcur) {
4227 		thresh = t_rxtcur;
4228 	}
4229 	/* Not above a RTO max */
4230 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4231 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4232 	}
4233 	/* And now apply the user TLP min */
4234 	if (thresh < bbr_tlp_min) {
4235 		thresh = bbr_tlp_min;
4236 	}
4237 	return (thresh);
4238 }
4239 
4240 /*
4241  * Return one of three RTTs to use (in microseconds).
4242  */
4243 static __inline uint32_t
4244 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4245 {
4246 	uint32_t f_rtt;
4247 	uint32_t srtt;
4248 
4249 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4250 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4251 		/* We have no rtt at all */
4252 		if (bbr->rc_tp->t_srtt == 0)
4253 			f_rtt = BBR_INITIAL_RTO;
4254 		else
4255 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4256 		/*
4257 		 * Since we don't know how good the rtt is apply a
4258 		 * delayed-ack min
4259 		 */
4260 		if (f_rtt < bbr_delayed_ack_time) {
4261 			f_rtt = bbr_delayed_ack_time;
4262 		}
4263 	}
4264 	/* Take the filter version or last measured pkt-rtt */
4265 	if (rtt_type == BBR_RTT_PROP) {
4266 		srtt = f_rtt;
4267 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4268 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4269 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4270 		} else {
4271 			/* No pkt rtt yet */
4272 			srtt = f_rtt;
4273 		}
4274 	} else if (rtt_type == BBR_RTT_RACK) {
4275 		srtt = bbr->r_ctl.rc_last_rtt;
4276 		/* We need to add in any internal delay for our timer */
4277 		if (bbr->rc_ack_was_delayed)
4278 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4279 	} else if (rtt_type == BBR_SRTT) {
4280 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4281 	} else {
4282 		/* TSNH */
4283 		srtt = f_rtt;
4284 #ifdef BBR_INVARIANTS
4285 		panic("Unknown rtt request type %d", rtt_type);
4286 #endif
4287 	}
4288 	return (srtt);
4289 }
4290 
4291 static int
4292 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4293 {
4294 	uint32_t thresh;
4295 
4296 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4297 				      cts, rsm);
4298 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4299 		/* It is lost (past time) */
4300 		return (1);
4301 	}
4302 	return (0);
4303 }
4304 
4305 /*
4306  * Return a sendmap if we need to retransmit something.
4307  */
4308 static struct bbr_sendmap *
4309 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4310 {
4311 	/*
4312 	 * Check to see that we don't need to fall into recovery. We will
4313 	 * need to do so if our oldest transmit is past the time we should
4314 	 * have had an ack.
4315 	 */
4316 
4317 	struct bbr_sendmap *rsm;
4318 	int32_t idx;
4319 
4320 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4321 		/* Nothing outstanding that we know of */
4322 		return (NULL);
4323 	}
4324 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4325 	if (rsm == NULL) {
4326 		/* Nothing in the transmit map */
4327 		return (NULL);
4328 	}
4329 	if (tp->t_flags & TF_SENTFIN) {
4330 		/* Fin restricted, don't find anything once a fin is sent */
4331 		return (NULL);
4332 	}
4333 	if (rsm->r_flags & BBR_ACKED) {
4334 		/*
4335 		 * Ok the first one is acked (this really should not happen
4336 		 * since we remove the from the tmap once they are acked)
4337 		 */
4338 		rsm = bbr_find_lowest_rsm(bbr);
4339 		if (rsm == NULL)
4340 			return (NULL);
4341 	}
4342 	idx = rsm->r_rtr_cnt - 1;
4343 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4344 		/* Send timestamp is the same or less? can't be ready */
4345 		return (NULL);
4346 	}
4347 	/* Get our RTT time */
4348 	if (bbr_is_lost(bbr, rsm, cts) &&
4349 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4350 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4351 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4352 			rsm->r_flags |= BBR_MARKED_LOST;
4353 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4354 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4355 		}
4356 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4357 #ifdef BBR_INVARIANTS
4358 		if ((rsm->r_end - rsm->r_start) == 0)
4359 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4360 #endif
4361 		return (rsm);
4362 	}
4363 	return (NULL);
4364 }
4365 
4366 /*
4367  * RACK Timer, here we simply do logging and house keeping.
4368  * the normal bbr_output_wtime() function will call the
4369  * appropriate thing to check if we need to do a RACK retransmit.
4370  * We return 1, saying don't proceed with bbr_output_wtime only
4371  * when all timers have been stopped (destroyed PCB?).
4372  */
4373 static int
4374 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4375 {
4376 	/*
4377 	 * This timer simply provides an internal trigger to send out data.
4378 	 * The check_recovery_mode call will see if there are needed
4379 	 * retransmissions, if so we will enter fast-recovery. The output
4380 	 * call may or may not do the same thing depending on sysctl
4381 	 * settings.
4382 	 */
4383 	uint32_t lost;
4384 
4385 	if (bbr->rc_all_timers_stopped) {
4386 		return (1);
4387 	}
4388 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4389 		/* Its not time yet */
4390 		return (0);
4391 	}
4392 	BBR_STAT_INC(bbr_to_tot);
4393 	lost = bbr->r_ctl.rc_lost;
4394 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4395 		bbr_set_state(tp, bbr, 0);
4396 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4397 	if (bbr->r_ctl.rc_resend == NULL) {
4398 		/* Lets do the check here */
4399 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4400 	}
4401 	if (bbr_policer_call_from_rack_to)
4402 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4403 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4404 	return (0);
4405 }
4406 
4407 static __inline void
4408 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4409 {
4410 	int idx;
4411 
4412 	nrsm->r_start = start;
4413 	nrsm->r_end = rsm->r_end;
4414 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4415 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4416 	nrsm->r_flags = rsm->r_flags;
4417 	/* We don't transfer forward the SYN flag */
4418 	nrsm->r_flags &= ~BBR_HAS_SYN;
4419 	/* We move forward the FIN flag, not that this should happen */
4420 	rsm->r_flags &= ~BBR_HAS_FIN;
4421 	nrsm->r_dupack = rsm->r_dupack;
4422 	nrsm->r_rtr_bytes = 0;
4423 	nrsm->r_is_gain = rsm->r_is_gain;
4424 	nrsm->r_is_drain = rsm->r_is_drain;
4425 	nrsm->r_delivered = rsm->r_delivered;
4426 	nrsm->r_ts_valid = rsm->r_ts_valid;
4427 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4428 	nrsm->r_del_time = rsm->r_del_time;
4429 	nrsm->r_app_limited = rsm->r_app_limited;
4430 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4431 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4432 	/* We split a piece the lower section looses any just_ret flag. */
4433 	nrsm->r_bbr_state = rsm->r_bbr_state;
4434 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4435 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4436 	}
4437 	rsm->r_end = nrsm->r_start;
4438 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4439 	idx /= 8;
4440 	/* Check if we got too small */
4441 	if ((rsm->r_is_smallmap == 0) &&
4442 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4443 		bbr->r_ctl.rc_num_small_maps_alloced++;
4444 		rsm->r_is_smallmap = 1;
4445 	}
4446 	/* Check the new one as well */
4447 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4448 		bbr->r_ctl.rc_num_small_maps_alloced++;
4449 		nrsm->r_is_smallmap = 1;
4450 	}
4451 }
4452 
4453 static int
4454 bbr_sack_mergable(struct bbr_sendmap *at,
4455 		  uint32_t start, uint32_t end)
4456 {
4457 	/*
4458 	 * Given a sack block defined by
4459 	 * start and end, and a current postion
4460 	 * at. Return 1 if either side of at
4461 	 * would show that the block is mergable
4462 	 * to that side. A block to be mergable
4463 	 * must have overlap with the start/end
4464 	 * and be in the SACK'd state.
4465 	 */
4466 	struct bbr_sendmap *l_rsm;
4467 	struct bbr_sendmap *r_rsm;
4468 
4469 	/* first get the either side blocks */
4470 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4471 	r_rsm = TAILQ_NEXT(at, r_next);
4472 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4473 		/* Potentially mergeable */
4474 		if ((l_rsm->r_end == start) ||
4475 		    (SEQ_LT(start, l_rsm->r_end) &&
4476 		     SEQ_GT(end, l_rsm->r_end))) {
4477 			    /*
4478 			     * map blk   |------|
4479 			     * sack blk         |------|
4480 			     * <or>
4481 			     * map blk   |------|
4482 			     * sack blk      |------|
4483 			     */
4484 			    return (1);
4485 		    }
4486 	}
4487 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4488 		/* Potentially mergeable */
4489 		if ((r_rsm->r_start == end) ||
4490 		    (SEQ_LT(start, r_rsm->r_start) &&
4491 		     SEQ_GT(end, r_rsm->r_start))) {
4492 			/*
4493 			 * map blk          |---------|
4494 			 * sack blk    |----|
4495 			 * <or>
4496 			 * map blk          |---------|
4497 			 * sack blk    |-------|
4498 			 */
4499 			return (1);
4500 		}
4501 	}
4502 	return (0);
4503 }
4504 
4505 static struct bbr_sendmap *
4506 bbr_merge_rsm(struct tcp_bbr *bbr,
4507 	      struct bbr_sendmap *l_rsm,
4508 	      struct bbr_sendmap *r_rsm)
4509 {
4510 	/*
4511 	 * We are merging two ack'd RSM's,
4512 	 * the l_rsm is on the left (lower seq
4513 	 * values) and the r_rsm is on the right
4514 	 * (higher seq value). The simplest way
4515 	 * to merge these is to move the right
4516 	 * one into the left. I don't think there
4517 	 * is any reason we need to try to find
4518 	 * the oldest (or last oldest retransmitted).
4519 	 */
4520 	l_rsm->r_end = r_rsm->r_end;
4521 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4522 		l_rsm->r_dupack = r_rsm->r_dupack;
4523 	if (r_rsm->r_rtr_bytes)
4524 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4525 	if (r_rsm->r_in_tmap) {
4526 		/* This really should not happen */
4527 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4528 	}
4529 	if (r_rsm->r_app_limited)
4530 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4531 	/* Now the flags */
4532 	if (r_rsm->r_flags & BBR_HAS_FIN)
4533 		l_rsm->r_flags |= BBR_HAS_FIN;
4534 	if (r_rsm->r_flags & BBR_TLP)
4535 		l_rsm->r_flags |= BBR_TLP;
4536 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4537 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4538 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4539 		/* This really should not happen */
4540 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4541 	}
4542 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4543 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4544 		/* Transfer the split limit to the map we free */
4545 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4546 		l_rsm->r_limit_type = 0;
4547 	}
4548 	bbr_free(bbr, r_rsm);
4549 	return(l_rsm);
4550 }
4551 
4552 /*
4553  * TLP Timer, here we simply setup what segment we want to
4554  * have the TLP expire on, the normal bbr_output_wtime() will then
4555  * send it out.
4556  *
4557  * We return 1, saying don't proceed with bbr_output_wtime only
4558  * when all timers have been stopped (destroyed PCB?).
4559  */
4560 static int
4561 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4562 {
4563 	/*
4564 	 * Tail Loss Probe.
4565 	 */
4566 	struct bbr_sendmap *rsm = NULL;
4567 	struct socket *so;
4568 	uint32_t amm;
4569 	uint32_t out, avail;
4570 	uint32_t maxseg;
4571 	int collapsed_win = 0;
4572 
4573 	if (bbr->rc_all_timers_stopped) {
4574 		return (1);
4575 	}
4576 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4577 		/* Its not time yet */
4578 		return (0);
4579 	}
4580 	if (ctf_progress_timeout_check(tp, true)) {
4581 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4582 		return (-ETIMEDOUT);	/* tcp_drop() */
4583 	}
4584 	/* Did we somehow get into persists? */
4585 	if (bbr->rc_in_persist) {
4586 		return (0);
4587 	}
4588 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4589 		bbr_set_state(tp, bbr, 0);
4590 	BBR_STAT_INC(bbr_tlp_tot);
4591 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4592 	/*
4593 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4594 	 * need to figure out how to force a full MSS segment out.
4595 	 */
4596 	so = tp->t_inpcb->inp_socket;
4597 	avail = sbavail(&so->so_snd);
4598 	out = ctf_outstanding(tp);
4599 	if (out > tp->snd_wnd) {
4600 		/* special case, we need a retransmission */
4601 		collapsed_win = 1;
4602 		goto need_retran;
4603 	}
4604 	if (avail > out) {
4605 		/* New data is available */
4606 		amm = avail - out;
4607 		if (amm > maxseg) {
4608 			amm = maxseg;
4609 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4610 			/* not enough to fill a MTU and no-delay is off */
4611 			goto need_retran;
4612 		}
4613 		/* Set the send-new override */
4614 		if ((out + amm) <= tp->snd_wnd) {
4615 			bbr->rc_tlp_new_data = 1;
4616 		} else {
4617 			goto need_retran;
4618 		}
4619 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4620 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4621 		bbr->r_ctl.rc_tlp_send = NULL;
4622 		/* cap any slots */
4623 		BBR_STAT_INC(bbr_tlp_newdata);
4624 		goto send;
4625 	}
4626 need_retran:
4627 	/*
4628 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4629 	 * optionally the first un-acked segment.
4630 	 */
4631 	if (collapsed_win == 0) {
4632 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4633 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4634 			rsm = bbr_find_high_nonack(bbr, rsm);
4635 		}
4636 		if (rsm == NULL) {
4637 			goto restore;
4638 		}
4639 	} else {
4640 		/*
4641 		 * We must find the last segment
4642 		 * that was acceptable by the client.
4643 		 */
4644 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4645 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4646 				/* Found one */
4647 				break;
4648 			}
4649 		}
4650 		if (rsm == NULL) {
4651 			/* None? if so send the first */
4652 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4653 			if (rsm == NULL)
4654 				goto restore;
4655 		}
4656 	}
4657 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4658 		/*
4659 		 * We need to split this the last segment in two.
4660 		 */
4661 		struct bbr_sendmap *nrsm;
4662 
4663 		nrsm = bbr_alloc_full_limit(bbr);
4664 		if (nrsm == NULL) {
4665 			/*
4666 			 * We can't get memory to split, we can either just
4667 			 * not split it. Or retransmit the whole piece, lets
4668 			 * do the large send (BTLP :-) ).
4669 			 */
4670 			goto go_for_it;
4671 		}
4672 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4673 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4674 		if (rsm->r_in_tmap) {
4675 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4676 			nrsm->r_in_tmap = 1;
4677 		}
4678 		rsm->r_flags &= (~BBR_HAS_FIN);
4679 		rsm = nrsm;
4680 	}
4681 go_for_it:
4682 	bbr->r_ctl.rc_tlp_send = rsm;
4683 	bbr->rc_tlp_rtx_out = 1;
4684 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4685 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4686 		tp->t_rxtshift++;
4687 	} else {
4688 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4689 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4690 	}
4691 send:
4692 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4693 		/*
4694 		 * Can't [re]/transmit a segment we have retranmitted the
4695 		 * max times. We need the retransmit timer to take over.
4696 		 */
4697 restore:
4698 		bbr->rc_tlp_new_data = 0;
4699 		bbr->r_ctl.rc_tlp_send = NULL;
4700 		if (rsm)
4701 			rsm->r_flags &= ~BBR_TLP;
4702 		BBR_STAT_INC(bbr_tlp_retran_fail);
4703 		return (0);
4704 	} else if (rsm) {
4705 		rsm->r_flags |= BBR_TLP;
4706 	}
4707 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4708 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4709 		/*
4710 		 * We have retransmitted to many times for TLP. Switch to
4711 		 * the regular RTO timer
4712 		 */
4713 		goto restore;
4714 	}
4715 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4716 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4717 	return (0);
4718 }
4719 
4720 /*
4721  * Delayed ack Timer, here we simply need to setup the
4722  * ACK_NOW flag and remove the DELACK flag. From there
4723  * the output routine will send the ack out.
4724  *
4725  * We only return 1, saying don't proceed, if all timers
4726  * are stopped (destroyed PCB?).
4727  */
4728 static int
4729 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4730 {
4731 	if (bbr->rc_all_timers_stopped) {
4732 		return (1);
4733 	}
4734 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4735 	tp->t_flags &= ~TF_DELACK;
4736 	tp->t_flags |= TF_ACKNOW;
4737 	KMOD_TCPSTAT_INC(tcps_delack);
4738 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4739 	return (0);
4740 }
4741 
4742 /*
4743  * Here we send a KEEP-ALIVE like probe to the
4744  * peer, we do not send data.
4745  *
4746  * We only return 1, saying don't proceed, if all timers
4747  * are stopped (destroyed PCB?).
4748  */
4749 static int
4750 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4751 {
4752 	struct tcptemp *t_template;
4753 	int32_t retval = 1;
4754 
4755 	if (bbr->rc_all_timers_stopped) {
4756 		return (1);
4757 	}
4758 	if (bbr->rc_in_persist == 0)
4759 		return (0);
4760 	KASSERT(tp->t_inpcb != NULL,
4761 	    ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4762 	/*
4763 	 * Persistence timer into zero window. Force a byte to be output, if
4764 	 * possible.
4765 	 */
4766 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4767 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4768 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4769 	/*
4770 	 * Have we exceeded the user specified progress time?
4771 	 */
4772 	if (ctf_progress_timeout_check(tp, true)) {
4773 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4774 		return (-ETIMEDOUT);	/* tcp_drop() */
4775 	}
4776 	/*
4777 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4778 	 * window is closed.  After a full backoff, drop the connection if
4779 	 * the idle time (no responses to probes) reaches the maximum
4780 	 * backoff that we would use if retransmitting.
4781 	 */
4782 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4783 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4784 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4785 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4786 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4787 		return (-ETIMEDOUT);	/* tcp_drop() */
4788 	}
4789 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4790 	    tp->snd_una == tp->snd_max) {
4791 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4792 		retval = 0;
4793 		goto out;
4794 	}
4795 	/*
4796 	 * If the user has closed the socket then drop a persisting
4797 	 * connection after a much reduced timeout.
4798 	 */
4799 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4800 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4801 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4802 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4803 		return (-ETIMEDOUT);	/* tcp_drop() */
4804 	}
4805 	t_template = tcpip_maketemplate(bbr->rc_inp);
4806 	if (t_template) {
4807 		tcp_respond(tp, t_template->tt_ipgen,
4808 			    &t_template->tt_t, (struct mbuf *)NULL,
4809 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4810 		/* This sends an ack */
4811 		if (tp->t_flags & TF_DELACK)
4812 			tp->t_flags &= ~TF_DELACK;
4813 		free(t_template, M_TEMP);
4814 	}
4815 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4816 		tp->t_rxtshift++;
4817 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4818 out:
4819 	return (retval);
4820 }
4821 
4822 /*
4823  * If a keepalive goes off, we had no other timers
4824  * happening. We always return 1 here since this
4825  * routine either drops the connection or sends
4826  * out a segment with respond.
4827  */
4828 static int
4829 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4830 {
4831 	struct tcptemp *t_template;
4832 	struct inpcb *inp;
4833 
4834 	if (bbr->rc_all_timers_stopped) {
4835 		return (1);
4836 	}
4837 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4838 	inp = tp->t_inpcb;
4839 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4840 	/*
4841 	 * Keep-alive timer went off; send something or drop connection if
4842 	 * idle for too long.
4843 	 */
4844 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4845 	if (tp->t_state < TCPS_ESTABLISHED)
4846 		goto dropit;
4847 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4848 	    tp->t_state <= TCPS_CLOSING) {
4849 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4850 			goto dropit;
4851 		/*
4852 		 * Send a packet designed to force a response if the peer is
4853 		 * up and reachable: either an ACK if the connection is
4854 		 * still alive, or an RST if the peer has closed the
4855 		 * connection due to timeout or reboot. Using sequence
4856 		 * number tp->snd_una-1 causes the transmitted zero-length
4857 		 * segment to lie outside the receive window; by the
4858 		 * protocol spec, this requires the correspondent TCP to
4859 		 * respond.
4860 		 */
4861 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4862 		t_template = tcpip_maketemplate(inp);
4863 		if (t_template) {
4864 			tcp_respond(tp, t_template->tt_ipgen,
4865 			    &t_template->tt_t, (struct mbuf *)NULL,
4866 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4867 			free(t_template, M_TEMP);
4868 		}
4869 	}
4870 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4871 	return (1);
4872 dropit:
4873 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4874 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4875 	return (-ETIMEDOUT);	/* tcp_drop() */
4876 }
4877 
4878 /*
4879  * Retransmit helper function, clear up all the ack
4880  * flags and take care of important book keeping.
4881  */
4882 static void
4883 bbr_remxt_tmr(struct tcpcb *tp)
4884 {
4885 	/*
4886 	 * The retransmit timer went off, all sack'd blocks must be
4887 	 * un-acked.
4888 	 */
4889 	struct bbr_sendmap *rsm, *trsm = NULL;
4890 	struct tcp_bbr *bbr;
4891 	uint32_t cts, lost;
4892 
4893 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4894 	cts = tcp_get_usecs(&bbr->rc_tv);
4895 	lost = bbr->r_ctl.rc_lost;
4896 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4897 		bbr_set_state(tp, bbr, 0);
4898 
4899 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4900 		if (rsm->r_flags & BBR_ACKED) {
4901 			uint32_t old_flags;
4902 
4903 			rsm->r_dupack = 0;
4904 			if (rsm->r_in_tmap == 0) {
4905 				/* We must re-add it back to the tlist */
4906 				if (trsm == NULL) {
4907 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4908 				} else {
4909 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4910 				}
4911 				rsm->r_in_tmap = 1;
4912 			}
4913 			old_flags = rsm->r_flags;
4914 			rsm->r_flags |= BBR_RXT_CLEARED;
4915 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4916 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4917 		} else {
4918 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4919 			    (rsm->r_start == tp->snd_una)) {
4920 				/*
4921 				 * Special case for TCP FO. Where
4922 				 * we sent more data beyond the snd_max.
4923 				 * We don't mark that as lost and stop here.
4924 				 */
4925 				break;
4926 			}
4927 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4928 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4929 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4930 			}
4931 			if (bbr_marks_rxt_sack_passed) {
4932 				/*
4933 				 * With this option, we will rack out
4934 				 * in 1ms increments the rest of the packets.
4935 				 */
4936 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4937 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4938 			} else {
4939 				/*
4940 				 * With this option we only mark them lost
4941 				 * and remove all sack'd markings. We will run
4942 				 * another RXT or a TLP. This will cause
4943 				 * us to eventually send more based on what
4944 				 * ack's come in.
4945 				 */
4946 				rsm->r_flags |= BBR_MARKED_LOST;
4947 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4948 				rsm->r_flags &= ~BBR_SACK_PASSED;
4949 			}
4950 		}
4951 		trsm = rsm;
4952 	}
4953 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4954 	/* Clear the count (we just un-acked them) */
4955 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4956 	bbr->rc_tlp_new_data = 0;
4957 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4958 	/* zap the behindness on a rxt */
4959 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4960 	bbr->r_agg_early_set = 0;
4961 	bbr->r_ctl.rc_agg_early = 0;
4962 	bbr->rc_tlp_rtx_out = 0;
4963 	bbr->r_ctl.rc_sacked = 0;
4964 	bbr->r_ctl.rc_sacklast = NULL;
4965 	bbr->r_timer_override = 1;
4966 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4967 }
4968 
4969 /*
4970  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4971  * we will setup to retransmit the lowest seq number outstanding.
4972  */
4973 static int
4974 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4975 {
4976 	int32_t rexmt;
4977 	int32_t retval = 0;
4978 	bool isipv6;
4979 
4980 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4981 	if (bbr->rc_all_timers_stopped) {
4982 		return (1);
4983 	}
4984 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4985 	    (tp->snd_una == tp->snd_max)) {
4986 		/* Nothing outstanding .. nothing to do */
4987 		return (0);
4988 	}
4989 	/*
4990 	 * Retransmission timer went off.  Message has not been acked within
4991 	 * retransmit interval.  Back off to a longer retransmit interval
4992 	 * and retransmit one segment.
4993 	 */
4994 	if (ctf_progress_timeout_check(tp, true)) {
4995 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4996 		return (-ETIMEDOUT);	/* tcp_drop() */
4997 	}
4998 	bbr_remxt_tmr(tp);
4999 	if ((bbr->r_ctl.rc_resend == NULL) ||
5000 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
5001 		/*
5002 		 * If the rwnd collapsed on
5003 		 * the one we are retransmitting
5004 		 * it does not count against the
5005 		 * rxt count.
5006 		 */
5007 		tp->t_rxtshift++;
5008 	}
5009 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5010 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5011 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5012 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5013 		/* XXXGL: previously t_softerror was casted to uint16_t */
5014 		MPASS(tp->t_softerror >= 0);
5015 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
5016 		return (retval);	/* tcp_drop() */
5017 	}
5018 	if (tp->t_state == TCPS_SYN_SENT) {
5019 		/*
5020 		 * If the SYN was retransmitted, indicate CWND to be limited
5021 		 * to 1 segment in cc_conn_init().
5022 		 */
5023 		tp->snd_cwnd = 1;
5024 	} else if (tp->t_rxtshift == 1) {
5025 		/*
5026 		 * first retransmit; record ssthresh and cwnd so they can be
5027 		 * recovered if this turns out to be a "bad" retransmit. A
5028 		 * retransmit is considered "bad" if an ACK for this segment
5029 		 * is received within RTT/2 interval; the assumption here is
5030 		 * that the ACK was already in flight.  See "On Estimating
5031 		 * End-to-End Network Path Properties" by Allman and Paxson
5032 		 * for more details.
5033 		 */
5034 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5035 		if (!IN_RECOVERY(tp->t_flags)) {
5036 			tp->snd_cwnd_prev = tp->snd_cwnd;
5037 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5038 			tp->snd_recover_prev = tp->snd_recover;
5039 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5040 			tp->t_flags |= TF_PREVVALID;
5041 		} else {
5042 			tp->t_flags &= ~TF_PREVVALID;
5043 		}
5044 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5045 	} else {
5046 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5047 		tp->t_flags &= ~TF_PREVVALID;
5048 	}
5049 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5050 	if ((tp->t_state == TCPS_SYN_SENT) ||
5051 	    (tp->t_state == TCPS_SYN_RECEIVED))
5052 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5053 	else
5054 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5055 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5056 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5057 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5058 	/*
5059 	 * We enter the path for PLMTUD if connection is established or, if
5060 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5061 	 * amount of data we send is very small, we could send it in couple
5062 	 * of packets and process straight to FIN. In that case we won't
5063 	 * catch ESTABLISHED state.
5064 	 */
5065 #ifdef INET6
5066 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
5067 #else
5068 	isipv6 = false;
5069 #endif
5070 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5071 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5072 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5073 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5074 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5075 		/*
5076 		 * Idea here is that at each stage of mtu probe (usually,
5077 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5078 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5079 		 * should take care of that.
5080 		 */
5081 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5082 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5083 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5084 		    tp->t_rxtshift % 2 == 0)) {
5085 			/*
5086 			 * Enter Path MTU Black-hole Detection mechanism: -
5087 			 * Disable Path MTU Discovery (IP "DF" bit). -
5088 			 * Reduce MTU to lower value than what we negotiated
5089 			 * with peer.
5090 			 */
5091 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5092 				/*
5093 				 * Record that we may have found a black
5094 				 * hole.
5095 				 */
5096 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5097 				/* Keep track of previous MSS. */
5098 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5099 			}
5100 			/*
5101 			 * Reduce the MSS to blackhole value or to the
5102 			 * default in an attempt to retransmit.
5103 			 */
5104 #ifdef INET6
5105 			isipv6 = bbr->r_is_v6;
5106 			if (isipv6 &&
5107 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5108 				/* Use the sysctl tuneable blackhole MSS. */
5109 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5110 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5111 			} else if (isipv6) {
5112 				/* Use the default MSS. */
5113 				tp->t_maxseg = V_tcp_v6mssdflt;
5114 				/*
5115 				 * Disable Path MTU Discovery when we switch
5116 				 * to minmss.
5117 				 */
5118 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5119 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5120 			}
5121 #endif
5122 #if defined(INET6) && defined(INET)
5123 			else
5124 #endif
5125 #ifdef INET
5126 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5127 				/* Use the sysctl tuneable blackhole MSS. */
5128 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5129 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5130 			} else {
5131 				/* Use the default MSS. */
5132 				tp->t_maxseg = V_tcp_mssdflt;
5133 				/*
5134 				 * Disable Path MTU Discovery when we switch
5135 				 * to minmss.
5136 				 */
5137 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5138 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5139 			}
5140 #endif
5141 		} else {
5142 			/*
5143 			 * If further retransmissions are still unsuccessful
5144 			 * with a lowered MTU, maybe this isn't a blackhole
5145 			 * and we restore the previous MSS and blackhole
5146 			 * detection flags. The limit '6' is determined by
5147 			 * giving each probe stage (1448, 1188, 524) 2
5148 			 * chances to recover.
5149 			 */
5150 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5151 			    (tp->t_rxtshift >= 6)) {
5152 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5153 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5154 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5155 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5156 			}
5157 		}
5158 	}
5159 	/*
5160 	 * Disable RFC1323 and SACK if we haven't got any response to our
5161 	 * third SYN to work-around some broken terminal servers (most of
5162 	 * which have hopefully been retired) that have bad VJ header
5163 	 * compression code which trashes TCP segments containing
5164 	 * unknown-to-them TCP options.
5165 	 */
5166 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5167 	    (tp->t_rxtshift == 3))
5168 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5169 	/*
5170 	 * If we backed off this far, our srtt estimate is probably bogus.
5171 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5172 	 * move the current srtt into rttvar to keep the current retransmit
5173 	 * times until then.
5174 	 */
5175 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5176 #ifdef INET6
5177 		if (bbr->r_is_v6)
5178 			in6_losing(tp->t_inpcb);
5179 		else
5180 #endif
5181 			in_losing(tp->t_inpcb);
5182 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5183 		tp->t_srtt = 0;
5184 	}
5185 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5186 	tp->snd_recover = tp->snd_max;
5187 	tp->t_flags |= TF_ACKNOW;
5188 	tp->t_rtttime = 0;
5189 
5190 	return (retval);
5191 }
5192 
5193 static int
5194 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5195 {
5196 	int32_t ret = 0;
5197 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5198 
5199 	if (timers == 0) {
5200 		return (0);
5201 	}
5202 	if (tp->t_state == TCPS_LISTEN) {
5203 		/* no timers on listen sockets */
5204 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5205 			return (0);
5206 		return (1);
5207 	}
5208 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5209 		uint32_t left;
5210 
5211 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5212 			ret = -1;
5213 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5214 			return (0);
5215 		}
5216 		if (hpts_calling == 0) {
5217 			ret = -2;
5218 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5219 			return (0);
5220 		}
5221 		/*
5222 		 * Ok our timer went off early and we are not paced false
5223 		 * alarm, go back to sleep.
5224 		 */
5225 		left = bbr->r_ctl.rc_timer_exp - cts;
5226 		ret = -3;
5227 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5228 		tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5229 		return (1);
5230 	}
5231 	bbr->rc_tmr_stopped = 0;
5232 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5233 	if (timers & PACE_TMR_DELACK) {
5234 		ret = bbr_timeout_delack(tp, bbr, cts);
5235 	} else if (timers & PACE_TMR_PERSIT) {
5236 		ret = bbr_timeout_persist(tp, bbr, cts);
5237 	} else if (timers & PACE_TMR_RACK) {
5238 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5239 		ret = bbr_timeout_rack(tp, bbr, cts);
5240 	} else if (timers & PACE_TMR_TLP) {
5241 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5242 		ret = bbr_timeout_tlp(tp, bbr, cts);
5243 	} else if (timers & PACE_TMR_RXT) {
5244 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5245 		ret = bbr_timeout_rxt(tp, bbr, cts);
5246 	} else if (timers & PACE_TMR_KEEP) {
5247 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5248 	}
5249 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5250 	return (ret);
5251 }
5252 
5253 static void
5254 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5255 {
5256 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5257 		uint8_t hpts_removed = 0;
5258 
5259 		if (tcp_in_hpts(bbr->rc_inp) &&
5260 		    (bbr->rc_timer_first == 1)) {
5261 			/*
5262 			 * If we are canceling timer's when we have the
5263 			 * timer ahead of the output being paced. We also
5264 			 * must remove ourselves from the hpts.
5265 			 */
5266 			hpts_removed = 1;
5267 			tcp_hpts_remove(bbr->rc_inp);
5268 			if (bbr->r_ctl.rc_last_delay_val) {
5269 				/* Update the last hptsi delay too */
5270 				uint32_t time_since_send;
5271 
5272 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5273 					time_since_send = cts - bbr->rc_pacer_started;
5274 				else
5275 					time_since_send = 0;
5276 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5277 					/* Cut down our slot time */
5278 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5279 				} else {
5280 					bbr->r_ctl.rc_last_delay_val = 0;
5281 				}
5282 				bbr->rc_pacer_started = cts;
5283 			}
5284 		}
5285 		bbr->rc_timer_first = 0;
5286 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5287 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5288 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5289 	}
5290 }
5291 
5292 static void
5293 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5294 {
5295 	struct tcp_bbr *bbr;
5296 
5297 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5298 	bbr->rc_all_timers_stopped = 1;
5299 	return;
5300 }
5301 
5302 /*
5303  * stop all timers always returning 0.
5304  */
5305 static int
5306 bbr_stopall(struct tcpcb *tp)
5307 {
5308 	return (0);
5309 }
5310 
5311 static void
5312 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5313 {
5314 	return;
5315 }
5316 
5317 /*
5318  * return true if a bbr timer (rack or tlp) is active.
5319  */
5320 static int
5321 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5322 {
5323 	return (0);
5324 }
5325 
5326 static uint32_t
5327 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5328 {
5329 	struct bbr_sendmap *rsm;
5330 
5331 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5332 	if ((rsm == NULL) || (u_rsm == rsm))
5333 		return (cts);
5334 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5335 }
5336 
5337 static void
5338 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5339      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5340 {
5341 	int32_t idx;
5342 
5343 	rsm->r_rtr_cnt++;
5344 	rsm->r_dupack = 0;
5345 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5346 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5347 		rsm->r_flags |= BBR_OVERMAX;
5348 	}
5349 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5350 		/* Take off the collapsed flag at rxt */
5351 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5352 	}
5353 	if (rsm->r_flags & BBR_MARKED_LOST) {
5354 		/* We have retransmitted, its no longer lost */
5355 		rsm->r_flags &= ~BBR_MARKED_LOST;
5356 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5357 	}
5358 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5359 		/*
5360 		 * We hit a RXT timer on it and
5361 		 * we cleared the "acked" flag.
5362 		 * We now have it going back into
5363 		 * flight, we can remove the cleared
5364 		 * flag and possibly do accounting on
5365 		 * this piece.
5366 		 */
5367 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5368 	}
5369 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5370 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5371 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5372 	}
5373 	idx = rsm->r_rtr_cnt - 1;
5374 	rsm->r_tim_lastsent[idx] = cts;
5375 	rsm->r_pacing_delay = pacing_time;
5376 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5377 	rsm->r_ts_valid = bbr->rc_ts_valid;
5378 	if (bbr->rc_ts_valid)
5379 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5380 	if (bbr->r_ctl.r_app_limited_until)
5381 		rsm->r_app_limited = 1;
5382 	else
5383 		rsm->r_app_limited = 0;
5384 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5385 		rsm->r_bbr_state = bbr_state_val(bbr);
5386 	else
5387 		rsm->r_bbr_state = 8;
5388 	if (rsm->r_flags & BBR_ACKED) {
5389 		/* Problably MTU discovery messing with us */
5390 		uint32_t old_flags;
5391 
5392 		old_flags = rsm->r_flags;
5393 		rsm->r_flags &= ~BBR_ACKED;
5394 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5395 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5396 		if (bbr->r_ctl.rc_sacked == 0)
5397 			bbr->r_ctl.rc_sacklast = NULL;
5398 	}
5399 	if (rsm->r_in_tmap) {
5400 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5401 	}
5402 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5403 	rsm->r_in_tmap = 1;
5404 	if (rsm->r_flags & BBR_SACK_PASSED) {
5405 		/* We have retransmitted due to the SACK pass */
5406 		rsm->r_flags &= ~BBR_SACK_PASSED;
5407 		rsm->r_flags |= BBR_WAS_SACKPASS;
5408 	}
5409 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5410 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5411 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5412 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5413 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5414 		rsm->r_is_gain = 1;
5415 		rsm->r_is_drain = 0;
5416 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5417 		rsm->r_is_drain = 1;
5418 		rsm->r_is_gain = 0;
5419 	} else {
5420 		rsm->r_is_drain = 0;
5421 		rsm->r_is_gain = 0;
5422 	}
5423 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5424 }
5425 
5426 /*
5427  * Returns 0, or the sequence where we stopped
5428  * updating. We also update the lenp to be the amount
5429  * of data left.
5430  */
5431 
5432 static uint32_t
5433 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5434     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5435 {
5436 	/*
5437 	 * We (re-)transmitted starting at rsm->r_start for some length
5438 	 * (possibly less than r_end.
5439 	 */
5440 	struct bbr_sendmap *nrsm;
5441 	uint32_t c_end;
5442 	int32_t len;
5443 
5444 	len = *lenp;
5445 	c_end = rsm->r_start + len;
5446 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5447 		/*
5448 		 * We retransmitted the whole piece or more than the whole
5449 		 * slopping into the next rsm.
5450 		 */
5451 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5452 		if (c_end == rsm->r_end) {
5453 			*lenp = 0;
5454 			return (0);
5455 		} else {
5456 			int32_t act_len;
5457 
5458 			/* Hangs over the end return whats left */
5459 			act_len = rsm->r_end - rsm->r_start;
5460 			*lenp = (len - act_len);
5461 			return (rsm->r_end);
5462 		}
5463 		/* We don't get out of this block. */
5464 	}
5465 	/*
5466 	 * Here we retransmitted less than the whole thing which means we
5467 	 * have to split this into what was transmitted and what was not.
5468 	 */
5469 	nrsm = bbr_alloc_full_limit(bbr);
5470 	if (nrsm == NULL) {
5471 		*lenp = 0;
5472 		return (0);
5473 	}
5474 	/*
5475 	 * So here we are going to take the original rsm and make it what we
5476 	 * retransmitted. nrsm will be the tail portion we did not
5477 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5478 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5479 	 * 1, 6 and the new piece will be 6, 11.
5480 	 */
5481 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5482 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5483 	nrsm->r_dupack = 0;
5484 	if (rsm->r_in_tmap) {
5485 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5486 		nrsm->r_in_tmap = 1;
5487 	}
5488 	rsm->r_flags &= (~BBR_HAS_FIN);
5489 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5490 	*lenp = 0;
5491 	return (0);
5492 }
5493 
5494 static uint64_t
5495 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5496 {
5497 	uint64_t bw;
5498 
5499 	bw = bbr_get_bw(bbr);
5500 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5501 	bw /= (uint64_t)BBR_UNIT;
5502 	return(bw);
5503 }
5504 
5505 static void
5506 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5507 		       uint64_t act_rate, uint64_t rate_wanted)
5508 {
5509 	/*
5510 	 * We could not get a full gains worth
5511 	 * of rate.
5512 	 */
5513 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5514 		/* we can't even get the real rate */
5515 		uint64_t red;
5516 
5517 		bbr->skip_gain = 1;
5518 		bbr->gain_is_limited = 0;
5519 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5520 		if (red)
5521 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5522 	} else {
5523 		/* We can use a lower gain */
5524 		bbr->skip_gain = 0;
5525 		bbr->gain_is_limited = 1;
5526 	}
5527 }
5528 
5529 static void
5530 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5531 {
5532 	const struct tcp_hwrate_limit_table *nrte;
5533 	int error, rate = -1;
5534 
5535 	if (bbr->r_ctl.crte == NULL)
5536 		return;
5537 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5538 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5539 		/* Lost our routes? */
5540 		/* Clear the way for a re-attempt */
5541 		bbr->bbr_attempt_hdwr_pace = 0;
5542 lost_rate:
5543 		bbr->gain_is_limited = 0;
5544 		bbr->skip_gain = 0;
5545 		bbr->bbr_hdrw_pacing = 0;
5546 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5547 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5548 		tcp_bbr_tso_size_check(bbr, cts);
5549 		return;
5550 	}
5551 	rate = bbr_get_hardware_rate(bbr);
5552 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5553 				   bbr->rc_tp,
5554 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5555 				   rate,
5556 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5557 				   &error, NULL);
5558 	if (nrte == NULL) {
5559 		goto lost_rate;
5560 	}
5561 	if (nrte != bbr->r_ctl.crte) {
5562 		bbr->r_ctl.crte = nrte;
5563 		if (error == 0)  {
5564 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5565 			if (bbr->r_ctl.crte->rate < rate) {
5566 				/* We have a problem */
5567 				bbr_setup_less_of_rate(bbr, cts,
5568 						       bbr->r_ctl.crte->rate, rate);
5569 			} else {
5570 				/* We are good */
5571 				bbr->gain_is_limited = 0;
5572 				bbr->skip_gain = 0;
5573 			}
5574 		} else {
5575 			/* A failure should release the tag */
5576 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5577 			bbr->gain_is_limited = 0;
5578 			bbr->skip_gain = 0;
5579 			bbr->bbr_hdrw_pacing = 0;
5580 		}
5581 		bbr_type_log_hdwr_pacing(bbr,
5582 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5583 					 rate,
5584 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5585 					 __LINE__,
5586 					 cts,
5587 					 error);
5588 	}
5589 }
5590 
5591 static void
5592 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5593 {
5594 	/*
5595 	 * If we have hardware pacing support
5596 	 * we need to factor that in for our
5597 	 * TSO size.
5598 	 */
5599 	const struct tcp_hwrate_limit_table *rlp;
5600 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5601 
5602 	if ((bbr->bbr_hdrw_pacing == 0) ||
5603 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5604 	    (bbr->r_ctl.crte == NULL))
5605 		return;
5606 	if (bbr->hw_pacing_set == 0) {
5607 		/* Not yet by the hdwr pacing count delay */
5608 		return;
5609 	}
5610 	if (bbr_hdwr_pace_adjust == 0) {
5611 		/* No adjustment */
5612 		return;
5613 	}
5614 	rlp = bbr->r_ctl.crte;
5615 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5616 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5617 	else
5618 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5619 	/*
5620 	 * So lets first get the
5621 	 * time we will take between
5622 	 * TSO sized sends currently without
5623 	 * hardware help.
5624 	 */
5625 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5626 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5627 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5628 	hdwr_delay *= rlp->time_between;
5629 	if (cur_delay > hdwr_delay)
5630 		delta = cur_delay - hdwr_delay;
5631 	else
5632 		delta = 0;
5633 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5634 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5635 			     1);
5636 	if (delta &&
5637 	    (delta < (max(rlp->time_between,
5638 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5639 		/*
5640 		 * Now lets divide by the pacing
5641 		 * time between each segment the
5642 		 * hardware sends rounding up and
5643 		 * derive a bytes from that. We multiply
5644 		 * that by bbr_hdwr_pace_adjust to get
5645 		 * more bang for our buck.
5646 		 *
5647 		 * The goal is to have the software pacer
5648 		 * waiting no more than an additional
5649 		 * pacing delay if we can (without the
5650 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5651 		 */
5652 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5653 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5654 		seg_sz *= bbr_hdwr_pace_adjust;
5655 		if (bbr_hdwr_pace_floor &&
5656 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5657 			/* Currently hardware paces
5658 			 * out rs_min_seg segments at a time.
5659 			 * We need to make sure we always send at least
5660 			 * a full burst of bbr_hdwr_pace_floor down.
5661 			 */
5662 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5663 		}
5664 		seg_sz *= maxseg;
5665 	} else if (delta == 0) {
5666 		/*
5667 		 * The highest pacing rate is
5668 		 * above our b/w gained. This means
5669 		 * we probably are going quite fast at
5670 		 * the hardware highest rate. Lets just multiply
5671 		 * the calculated TSO size by the
5672 		 * multiplier factor (its probably
5673 		 * 4 segments in the default config for
5674 		 * mlx).
5675 		 */
5676 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5677 		if (bbr_hdwr_pace_floor &&
5678 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5679 			/* Currently hardware paces
5680 			 * out rs_min_seg segments at a time.
5681 			 * We need to make sure we always send at least
5682 			 * a full burst of bbr_hdwr_pace_floor down.
5683 			 */
5684 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5685 		}
5686 	} else {
5687 		/*
5688 		 * The pacing time difference is so
5689 		 * big that the hardware will
5690 		 * pace out more rapidly then we
5691 		 * really want and then we
5692 		 * will have a long delay. Lets just keep
5693 		 * the same TSO size so its as if
5694 		 * we were not using hdwr pacing (we
5695 		 * just gain a bit of spacing from the
5696 		 * hardware if seg_sz > 1).
5697 		 */
5698 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5699 	}
5700 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5701 		new_tso = seg_sz;
5702 	else
5703 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5704 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5705 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5706 
5707 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5708 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5709 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5710 	}
5711 }
5712 
5713 static void
5714 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5715 {
5716 	uint64_t bw;
5717 	uint32_t old_tso = 0, new_tso;
5718 	uint32_t maxseg, bytes;
5719 	uint32_t tls_seg=0;
5720 	/*
5721 	 * Google/linux uses the following algorithm to determine
5722 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5723 	 *
5724 	 *  bytes = bw_in_bytes_per_second / 1000
5725 	 *  bytes = min(bytes, 64k)
5726 	 *  tso_segs = bytes / MSS
5727 	 *  if (bw < 1.2Mbs)
5728 	 *      min_tso_segs = 1
5729 	 *  else
5730 	 *	min_tso_segs = 2
5731 	 * tso_segs = max(tso_segs, min_tso_segs)
5732 	 *
5733 	 * * Note apply a device specific limit (we apply this in the
5734 	 *   tcp_m_copym).
5735 	 * Note that before the initial measurement is made google bursts out
5736 	 * a full iwnd just like new-reno/cubic.
5737 	 *
5738 	 * We do not use this algorithm. Instead we
5739 	 * use a two phased approach:
5740 	 *
5741 	 *  if ( bw <= per-tcb-cross-over)
5742 	 *     goal_tso =  calculate how much with this bw we
5743 	 *                 can send in goal-time seconds.
5744 	 *     if (goal_tso > mss)
5745 	 *         seg = goal_tso / mss
5746 	 *         tso = seg * mss
5747 	 *     else
5748 	 *         tso = mss
5749 	 *     if (tso > per-tcb-max)
5750 	 *         tso = per-tcb-max
5751 	 *  else if ( bw > 512Mbps)
5752 	 *     tso = max-tso (64k/mss)
5753 	 *  else
5754 	 *     goal_tso = bw / per-tcb-divsor
5755 	 *     seg = (goal_tso + mss-1)/mss
5756 	 *     tso = seg * mss
5757 	 *
5758 	 * if (tso < per-tcb-floor)
5759 	 *    tso = per-tcb-floor
5760 	 * if (tso > per-tcb-utter_max)
5761 	 *    tso = per-tcb-utter_max
5762 	 *
5763 	 * Note the default per-tcb-divisor is 1000 (same as google).
5764 	 * the goal cross over is 30Mbps however. To recreate googles
5765 	 * algorithm you need to set:
5766 	 *
5767 	 * cross-over = 23,168,000 bps
5768 	 * goal-time = 18000
5769 	 * per-tcb-max = 2
5770 	 * per-tcb-divisor = 1000
5771 	 * per-tcb-floor = 1
5772 	 *
5773 	 * This will get you "google bbr" behavior with respect to tso size.
5774 	 *
5775 	 * Note we do set anything TSO size until we are past the initial
5776 	 * window. Before that we gnerally use either a single MSS
5777 	 * or we use the full IW size (so we burst a IW at a time)
5778 	 */
5779 
5780 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5781 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5782 	} else {
5783 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5784 	}
5785 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5786 	if (bbr->rc_past_init_win == 0) {
5787 		/*
5788 		 * Not enough data has been acknowledged to make a
5789 		 * judgement. Set up the initial TSO based on if we
5790 		 * are sending a full IW at once or not.
5791 		 */
5792 		if (bbr->rc_use_google)
5793 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5794 		else if (bbr->bbr_init_win_cheat)
5795 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5796 		else
5797 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5798 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5799 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5800 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5801 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5802 		}
5803 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5804 			bbr_adjust_for_hw_pacing(bbr, cts);
5805 		return;
5806 	}
5807 	/**
5808 	 * Now lets set the TSO goal based on our delivery rate in
5809 	 * bytes per second. Note we only do this if
5810 	 * we have acked at least the initial cwnd worth of data.
5811 	 */
5812 	bw = bbr_get_bw(bbr);
5813 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5814 	     (bbr->rc_use_google == 0)) {
5815 		/* We clamp to one MSS in recovery */
5816 		new_tso = maxseg;
5817 	} else if (bbr->rc_use_google) {
5818 		int min_tso_segs;
5819 
5820 		/* Google considers the gain too */
5821 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5822 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5823 			bw /= BBR_UNIT;
5824 		}
5825 		bytes = bw / 1024;
5826 		if (bytes > (64 * 1024))
5827 			bytes = 64 * 1024;
5828 		new_tso = bytes / maxseg;
5829 		if (bw < ONE_POINT_TWO_MEG)
5830 			min_tso_segs = 1;
5831 		else
5832 			min_tso_segs = 2;
5833 		if (new_tso < min_tso_segs)
5834 			new_tso = min_tso_segs;
5835 		new_tso *= maxseg;
5836 	} else if (bbr->rc_no_pacing) {
5837 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5838 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5839 		/*
5840 		 * Calculate the worse case b/w TSO if we are inserting no
5841 		 * more than a delay_target number of TSO's.
5842 		 */
5843 		uint32_t tso_len, min_tso;
5844 
5845 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5846 		if (tso_len > maxseg) {
5847 			new_tso = tso_len / maxseg;
5848 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5849 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5850 			new_tso *= maxseg;
5851 		} else {
5852 			/*
5853 			 * less than a full sized frame yikes.. long rtt or
5854 			 * low bw?
5855 			 */
5856 			min_tso = bbr_minseg(bbr);
5857 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5858 				new_tso = rounddown(tso_len, min_tso);
5859 			else
5860 				new_tso = min_tso;
5861 		}
5862 	} else if (bw > FIVETWELVE_MBPS) {
5863 		/*
5864 		 * This guy is so fast b/w wise that we can TSO as large as
5865 		 * possible of segments that the NIC will allow.
5866 		 */
5867 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5868 	} else {
5869 		/*
5870 		 * This formula is based on attempting to send a segment or
5871 		 * more every bbr_hptsi_per_second. The default is 1000
5872 		 * which means you are targeting what you can send every 1ms
5873 		 * based on the peers bw.
5874 		 *
5875 		 * If the number drops to say 500, then you are looking more
5876 		 * at 2ms and you will raise how much we send in a single
5877 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5878 		 * trade off of course is you will send more at once and
5879 		 * thus tend to clump up the sends into larger "bursts"
5880 		 * building a queue.
5881 		 */
5882 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5883 		new_tso = roundup(bw, (uint64_t)maxseg);
5884 		/*
5885 		 * Gate the floor to match what our lower than 48Mbps
5886 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5887 		 * becomes the floor for this calculation.
5888 		 */
5889 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5890 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5891 	}
5892 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5893 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5894 	if (new_tso > PACE_MAX_IP_BYTES)
5895 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5896 	/* Enforce an utter maximum. */
5897 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5898 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5899 	}
5900 	if (old_tso != new_tso) {
5901 		/* Only log changes */
5902 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5903 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5904 	}
5905 	/* We have hardware pacing! */
5906 	bbr_adjust_for_hw_pacing(bbr, cts);
5907 }
5908 
5909 static void
5910 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5911     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t cts,
5912     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5913     struct sockbuf *sb)
5914 {
5915 
5916 	struct bbr_sendmap *rsm, *nrsm;
5917 	register uint32_t snd_max, snd_una;
5918 	uint32_t pacing_time;
5919 	/*
5920 	 * Add to the RACK log of packets in flight or retransmitted. If
5921 	 * there is a TS option we will use the TS echoed, if not we will
5922 	 * grab a TS.
5923 	 *
5924 	 * Retransmissions will increment the count and move the ts to its
5925 	 * proper place. Note that if options do not include TS's then we
5926 	 * won't be able to effectively use the ACK for an RTT on a retran.
5927 	 *
5928 	 * Notes about r_start and r_end. Lets consider a send starting at
5929 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5930 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5931 	 * This means that r_end is actually the first sequence for the next
5932 	 * slot (11).
5933 	 *
5934 	 */
5935 	INP_WLOCK_ASSERT(tp->t_inpcb);
5936 	if (err) {
5937 		/*
5938 		 * We don't log errors -- we could but snd_max does not
5939 		 * advance in this case either.
5940 		 */
5941 		return;
5942 	}
5943 	if (th_flags & TH_RST) {
5944 		/*
5945 		 * We don't log resets and we return immediately from
5946 		 * sending
5947 		 */
5948 		*abandon = 1;
5949 		return;
5950 	}
5951 	snd_una = tp->snd_una;
5952 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5953 		/*
5954 		 * The call to bbr_log_output is made before bumping
5955 		 * snd_max. This means we can record one extra byte on a SYN
5956 		 * or FIN if seq_out is adding more on and a FIN is present
5957 		 * (and we are not resending).
5958 		 */
5959 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5960 			len++;
5961 		if (th_flags & TH_FIN)
5962 			len++;
5963 	}
5964 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5965 		/* Are sending an old segment to induce an ack (keep-alive)? */
5966 		return;
5967 	}
5968 	if (SEQ_LT(seq_out, snd_una)) {
5969 		/* huh? should we panic? */
5970 		uint32_t end;
5971 
5972 		end = seq_out + len;
5973 		seq_out = snd_una;
5974 		len = end - seq_out;
5975 	}
5976 	snd_max = tp->snd_max;
5977 	if (len == 0) {
5978 		/* We don't log zero window probes */
5979 		return;
5980 	}
5981 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5982 	/* First question is it a retransmission? */
5983 	if (seq_out == snd_max) {
5984 again:
5985 		rsm = bbr_alloc(bbr);
5986 		if (rsm == NULL) {
5987 			return;
5988 		}
5989 		rsm->r_flags = 0;
5990 		if (th_flags & TH_SYN)
5991 			rsm->r_flags |= BBR_HAS_SYN;
5992 		if (th_flags & TH_FIN)
5993 			rsm->r_flags |= BBR_HAS_FIN;
5994 		rsm->r_tim_lastsent[0] = cts;
5995 		rsm->r_rtr_cnt = 1;
5996 		rsm->r_rtr_bytes = 0;
5997 		rsm->r_start = seq_out;
5998 		rsm->r_end = rsm->r_start + len;
5999 		rsm->r_dupack = 0;
6000 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
6001 		rsm->r_pacing_delay = pacing_time;
6002 		rsm->r_ts_valid = bbr->rc_ts_valid;
6003 		if (bbr->rc_ts_valid)
6004 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6005 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
6006 		if (bbr->r_ctl.r_app_limited_until)
6007 			rsm->r_app_limited = 1;
6008 		else
6009 			rsm->r_app_limited = 0;
6010 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6011 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6012 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6013 		/*
6014 		 * Here we must also add in this rsm since snd_max
6015 		 * is updated after we return from a new send.
6016 		 */
6017 		rsm->r_flight_at_send += len;
6018 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6019 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6020 		rsm->r_in_tmap = 1;
6021 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6022 			rsm->r_bbr_state = bbr_state_val(bbr);
6023 		else
6024 			rsm->r_bbr_state = 8;
6025 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6026 			rsm->r_is_gain = 1;
6027 			rsm->r_is_drain = 0;
6028 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6029 			rsm->r_is_drain = 1;
6030 			rsm->r_is_gain = 0;
6031 		} else {
6032 			rsm->r_is_drain = 0;
6033 			rsm->r_is_gain = 0;
6034 		}
6035 		return;
6036 	}
6037 	/*
6038 	 * If we reach here its a retransmission and we need to find it.
6039 	 */
6040 more:
6041 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6042 		rsm = hintrsm;
6043 		hintrsm = NULL;
6044 	} else if (bbr->r_ctl.rc_next) {
6045 		/* We have a hint from a previous run */
6046 		rsm = bbr->r_ctl.rc_next;
6047 	} else {
6048 		/* No hints sorry */
6049 		rsm = NULL;
6050 	}
6051 	if ((rsm) && (rsm->r_start == seq_out)) {
6052 		/*
6053 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6054 		 * likely case.
6055 		 */
6056 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6057 		if (len == 0) {
6058 			return;
6059 		} else {
6060 			goto more;
6061 		}
6062 	}
6063 	/* Ok it was not the last pointer go through it the hard way. */
6064 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6065 		if (rsm->r_start == seq_out) {
6066 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6067 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6068 			if (len == 0) {
6069 				return;
6070 			} else {
6071 				continue;
6072 			}
6073 		}
6074 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6075 			/* Transmitted within this piece */
6076 			/*
6077 			 * Ok we must split off the front and then let the
6078 			 * update do the rest
6079 			 */
6080 			nrsm = bbr_alloc_full_limit(bbr);
6081 			if (nrsm == NULL) {
6082 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6083 				return;
6084 			}
6085 			/*
6086 			 * copy rsm to nrsm and then trim the front of rsm
6087 			 * to not include this part.
6088 			 */
6089 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6090 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6091 			if (rsm->r_in_tmap) {
6092 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6093 				nrsm->r_in_tmap = 1;
6094 			}
6095 			rsm->r_flags &= (~BBR_HAS_FIN);
6096 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6097 			if (len == 0) {
6098 				return;
6099 			}
6100 		}
6101 	}
6102 	/*
6103 	 * Hmm not found in map did they retransmit both old and on into the
6104 	 * new?
6105 	 */
6106 	if (seq_out == tp->snd_max) {
6107 		goto again;
6108 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6109 #ifdef BBR_INVARIANTS
6110 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6111 		    seq_out, len, tp->snd_una, tp->snd_max);
6112 		printf("Starting Dump of all rack entries\n");
6113 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6114 			printf("rsm:%p start:%u end:%u\n",
6115 			    rsm, rsm->r_start, rsm->r_end);
6116 		}
6117 		printf("Dump complete\n");
6118 		panic("seq_out not found rack:%p tp:%p",
6119 		    bbr, tp);
6120 #endif
6121 	} else {
6122 #ifdef BBR_INVARIANTS
6123 		/*
6124 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6125 		 * flag)
6126 		 */
6127 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6128 		    seq_out, len, tp->snd_max, tp);
6129 #endif
6130 	}
6131 }
6132 
6133 static void
6134 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6135 {
6136 	/*
6137 	 * Collapse timeout back the cum-ack moved.
6138 	 */
6139 	tp->t_rxtshift = 0;
6140 	tp->t_softerror = 0;
6141 }
6142 
6143 static void
6144 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6145 {
6146 	bbr->rtt_valid = 1;
6147 	bbr->r_ctl.cur_rtt = rtt_usecs;
6148 	bbr->r_ctl.ts_in = tsin;
6149 	if (rsm_send_time)
6150 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6151 }
6152 
6153 static void
6154 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6155 {
6156 	/**
6157 	 * We have in our bbr control:
6158 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6159 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6160 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6161 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6162 	 *
6163 	 * Now we can calculate the time between the sends by doing:
6164 	 *
6165 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6166 	 *
6167 	 * And the peer's time between receiving them by doing:
6168 	 *
6169 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6170 	 *
6171 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6172 	 * We also may find that we can't use the timestamps if say we see
6173 	 * that the peer_delta indicates that though we may have taken 10ms to
6174 	 * pace out the data, it only saw 1ms between the two packets. This would
6175 	 * indicate that somewhere on the path is a batching entity that is giving
6176 	 * out time-slices of the actual b/w. This would mean we could not use
6177 	 * reliably the peers timestamps.
6178 	 *
6179 	 * We expect delta > peer_delta initially. Until we figure out the
6180 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6181 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6182 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6183 	 * put a 1 there. If the value is faster then ours, we will disable the
6184 	 * use of timestamps (though we could revist this later if we find it to be not
6185 	 * just an isolated one or two flows)).
6186 	 *
6187 	 * To detect the batching middle boxes we will come up with our compensation and
6188 	 * if with it in place, we find the peer is drastically off (by some margin) in
6189 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6190 	 *
6191 	 */
6192 	uint64_t delta, peer_delta, delta_up;
6193 
6194 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6195 	if (delta < bbr_min_usec_delta) {
6196 		/*
6197 		 * Have not seen a min amount of time
6198 		 * between our send times so we can
6199 		 * make a determination of the timestamp
6200 		 * yet.
6201 		 */
6202 		return;
6203 	}
6204 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6205 	if (peer_delta < bbr_min_peer_delta) {
6206 		/*
6207 		 * We may have enough in the form of
6208 		 * our delta but the peers number
6209 		 * has not changed that much. It could
6210 		 * be its clock ratio is such that
6211 		 * we need more data (10ms tick) or
6212 		 * there may be other compression scenarios
6213 		 * going on. In any event we need the
6214 		 * spread to be larger.
6215 		 */
6216 		return;
6217 	}
6218 	/* Ok lets first see which way our delta is going */
6219 	if (peer_delta > delta) {
6220 		/* Very unlikely, the peer without
6221 		 * compensation shows that it saw
6222 		 * the two sends arrive further apart
6223 		 * then we saw then in micro-seconds.
6224 		 */
6225 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6226 			/* well it looks like the peer is a micro-second clock. */
6227 			bbr->rc_ts_clock_set = 1;
6228 			bbr->r_ctl.bbr_peer_tsratio = 1;
6229 		} else {
6230 			bbr->rc_ts_cant_be_used = 1;
6231 			bbr->rc_ts_clock_set = 1;
6232 		}
6233 		return;
6234 	}
6235 	/* Ok we know that the peer_delta is smaller than our send distance */
6236 	bbr->rc_ts_clock_set = 1;
6237 	/* First question is it within the percentage that they are using usec time? */
6238 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6239 	if ((peer_delta + delta_up) >= delta) {
6240 		/* Its a usec clock */
6241 		bbr->r_ctl.bbr_peer_tsratio = 1;
6242 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6243 		return;
6244 	}
6245 	/* Ok if not usec, what about 10usec (though unlikely)? */
6246 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6247 	if (((peer_delta * 10) + delta_up) >= delta) {
6248 		bbr->r_ctl.bbr_peer_tsratio = 10;
6249 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6250 		return;
6251 	}
6252 	/* And what about 100usec (though again unlikely)? */
6253 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6254 	if (((peer_delta * 100) + delta_up) >= delta) {
6255 		bbr->r_ctl.bbr_peer_tsratio = 100;
6256 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6257 		return;
6258 	}
6259 	/* And how about 1 msec (the most likely one)? */
6260 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6261 	if (((peer_delta * 1000) + delta_up) >= delta) {
6262 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6263 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6264 		return;
6265 	}
6266 	/* Ok if not msec could it be 10 msec? */
6267 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6268 	if (((peer_delta * 10000) + delta_up) >= delta) {
6269 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6270 		return;
6271 	}
6272 	/* If we fall down here the clock tick so slowly we can't use it */
6273 	bbr->rc_ts_cant_be_used = 1;
6274 	bbr->r_ctl.bbr_peer_tsratio = 0;
6275 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6276 }
6277 
6278 /*
6279  * Collect new round-trip time estimate
6280  * and update averages and current timeout.
6281  */
6282 static void
6283 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6284 {
6285 	int32_t delta;
6286 	uint32_t rtt, tsin;
6287 	int32_t rtt_ticks;
6288 
6289 	if (bbr->rtt_valid == 0)
6290 		/* No valid sample */
6291 		return;
6292 
6293 	rtt = bbr->r_ctl.cur_rtt;
6294 	tsin = bbr->r_ctl.ts_in;
6295 	if (bbr->rc_prtt_set_ts) {
6296 		/*
6297 		 * We are to force feed the rttProp filter due
6298 		 * to an entry into PROBE_RTT. This assures
6299 		 * that the times are sync'd between when we
6300 		 * go into PROBE_RTT and the filter expiration.
6301 		 *
6302 		 * Google does not use a true filter, so they do
6303 		 * this implicitly since they only keep one value
6304 		 * and when they enter probe-rtt they update the
6305 		 * value to the newest rtt.
6306 		 */
6307 		uint32_t rtt_prop;
6308 
6309 		bbr->rc_prtt_set_ts = 0;
6310 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6311 		if (rtt > rtt_prop)
6312 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6313 		else
6314 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6315 	}
6316 	if (bbr->rc_ack_was_delayed)
6317 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6318 
6319 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6320 		bbr->r_ctl.rc_lowest_rtt = rtt;
6321 	bbr_log_rtt_sample(bbr, rtt, tsin);
6322 	if (bbr->r_init_rtt) {
6323 		/*
6324 		 * The initial rtt is not-trusted, nuke it and lets get
6325 		 * our first valid measurement in.
6326 		 */
6327 		bbr->r_init_rtt = 0;
6328 		tp->t_srtt = 0;
6329 	}
6330 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6331 		/*
6332 		 * So we have not yet figured out
6333 		 * what the peers TSTMP value is
6334 		 * in (most likely ms). We need a
6335 		 * series of cum-ack's to determine
6336 		 * this reliably.
6337 		 */
6338 		if (bbr->rc_ack_is_cumack) {
6339 			if (bbr->rc_ts_data_set) {
6340 				/* Lets attempt to determine the timestamp granularity. */
6341 				bbr_make_timestamp_determination(bbr);
6342 			} else {
6343 				bbr->rc_ts_data_set = 1;
6344 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6345 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6346 			}
6347 		} else {
6348 			/*
6349 			 * We have to have consecutive acks
6350 			 * reset any "filled" state to none.
6351 			 */
6352 			bbr->rc_ts_data_set = 0;
6353 		}
6354 	}
6355 	/* Round it up */
6356 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6357 	if (rtt_ticks == 0)
6358 		rtt_ticks = 1;
6359 	if (tp->t_srtt != 0) {
6360 		/*
6361 		 * srtt is stored as fixed point with 5 bits after the
6362 		 * binary point (i.e., scaled by 8).  The following magic is
6363 		 * equivalent to the smoothing algorithm in rfc793 with an
6364 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6365 		 * Adjust rtt to origin 0.
6366 		 */
6367 
6368 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6369 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6370 
6371 		tp->t_srtt += delta;
6372 		if (tp->t_srtt <= 0)
6373 			tp->t_srtt = 1;
6374 
6375 		/*
6376 		 * We accumulate a smoothed rtt variance (actually, a
6377 		 * smoothed mean difference), then set the retransmit timer
6378 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6379 		 * is stored as fixed point with 4 bits after the binary
6380 		 * point (scaled by 16).  The following is equivalent to
6381 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6382 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6383 		 * wired-in beta.
6384 		 */
6385 		if (delta < 0)
6386 			delta = -delta;
6387 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6388 		tp->t_rttvar += delta;
6389 		if (tp->t_rttvar <= 0)
6390 			tp->t_rttvar = 1;
6391 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6392 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6393 	} else {
6394 		/*
6395 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6396 		 * variance to half the rtt (so our first retransmit happens
6397 		 * at 3*rtt).
6398 		 */
6399 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6400 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6401 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6402 	}
6403 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6404 	tp->t_rttupdated++;
6405 #ifdef STATS
6406 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6407 #endif
6408 	/*
6409 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6410 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6411 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6412 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6413 	 * uncertainty in the firing of the timer.  The bias will give us
6414 	 * exactly the 1.5 tick we need.  But, because the bias is
6415 	 * statistical, we have to test that we don't drop below the minimum
6416 	 * feasible timer (which is 2 ticks).
6417 	 */
6418 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6419 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6420 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6421 
6422 	/*
6423 	 * We received an ack for a packet that wasn't retransmitted; it is
6424 	 * probably safe to discard any error indications we've received
6425 	 * recently.  This isn't quite right, but close enough for now (a
6426 	 * route might have failed after we sent a segment, and the return
6427 	 * path might not be symmetrical).
6428 	 */
6429 	tp->t_softerror = 0;
6430 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6431 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6432 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6433 }
6434 
6435 static void
6436 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6437 {
6438 	bbr->r_ctl.rc_rtt_shrinks = cts;
6439 	if (bbr_can_force_probertt &&
6440 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6441 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6442 		/*
6443 		 * We should enter probe-rtt its been too long
6444 		 * since we have been there.
6445 		 */
6446 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6447 	} else
6448 		bbr_check_probe_rtt_limits(bbr, cts);
6449 }
6450 
6451 static void
6452 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6453 {
6454 	uint64_t orig_bw;
6455 
6456 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6457 		/* We never apply a zero measurment */
6458 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6459 				    0, 0, 0, 0, 0, 0);
6460 		return;
6461 	}
6462 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6463 		bbr->r_ctl.r_measurement_count++;
6464 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6465 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6466 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6467 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6468 			    0, 0, 0, 0, 0, 0);
6469 	if (orig_bw &&
6470 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6471 		if (bbr->bbr_hdrw_pacing) {
6472 			/*
6473 			 * Apply a new rate to the hardware
6474 			 * possibly.
6475 			 */
6476 			bbr_update_hardware_pacing_rate(bbr, cts);
6477 		}
6478 		bbr_set_state_target(bbr, __LINE__);
6479 		tcp_bbr_tso_size_check(bbr, cts);
6480 		if (bbr->r_recovery_bw)  {
6481 			bbr_setup_red_bw(bbr, cts);
6482 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6483 		}
6484 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6485 		tcp_bbr_tso_size_check(bbr, cts);
6486 }
6487 
6488 static void
6489 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6490 {
6491 	if (bbr->rc_in_persist == 0) {
6492 		/* We log only when not in persist */
6493 		/* Translate to a Bytes Per Second */
6494 		uint64_t tim, bw, ts_diff, ts_bw;
6495 		uint32_t delivered;
6496 
6497 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6498 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6499 		else
6500 			tim = 1;
6501 		/*
6502 		 * Now that we have processed the tim (skipping the sample
6503 		 * or possibly updating the time, go ahead and
6504 		 * calculate the cdr.
6505 		 */
6506 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6507 		bw = (uint64_t)delivered;
6508 		bw *= (uint64_t)USECS_IN_SECOND;
6509 		bw /= tim;
6510 		if (bw == 0) {
6511 			/* We must have a calculatable amount */
6512 			return;
6513 		}
6514 		/*
6515 		 * If we are using this b/w shove it in now so we
6516 		 * can see in the trace viewer if it gets over-ridden.
6517 		 */
6518 		if (rsm->r_ts_valid &&
6519 		    bbr->rc_ts_valid &&
6520 		    bbr->rc_ts_clock_set &&
6521 		    (bbr->rc_ts_cant_be_used == 0) &&
6522 		    bbr->rc_use_ts_limit) {
6523 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6524 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6525 			if ((delivered == 0) ||
6526 			    (rtt < 1000)) {
6527 				/* Can't use the ts */
6528 				bbr_log_type_bbrupd(bbr, 61, cts,
6529 						    ts_diff,
6530 						    bbr->r_ctl.last_inbound_ts,
6531 						    rsm->r_del_ack_ts, 0,
6532 						    0, 0, 0, delivered);
6533 			} else {
6534 				ts_bw = (uint64_t)delivered;
6535 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6536 				ts_bw /= ts_diff;
6537 				bbr_log_type_bbrupd(bbr, 62, cts,
6538 						    (ts_bw >> 32),
6539 						    (ts_bw & 0xffffffff), 0, 0,
6540 						    0, 0, ts_diff, delivered);
6541 				if ((bbr->ts_can_raise) &&
6542 				    (ts_bw > bw)) {
6543 					bbr_log_type_bbrupd(bbr, 8, cts,
6544 							    delivered,
6545 							    ts_diff,
6546 							    (bw >> 32),
6547 							    (bw & 0x00000000ffffffff),
6548 							    0, 0, 0, 0);
6549 					bw = ts_bw;
6550 				} else if (ts_bw && (ts_bw < bw)) {
6551 					bbr_log_type_bbrupd(bbr, 7, cts,
6552 							    delivered,
6553 							    ts_diff,
6554 							    (bw >> 32),
6555 							    (bw & 0x00000000ffffffff),
6556 							    0, 0, 0, 0);
6557 					bw = ts_bw;
6558 				}
6559 			}
6560 		}
6561 		if (rsm->r_first_sent_time &&
6562 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6563 			uint64_t sbw, sti;
6564 			/*
6565 			 * We use what was in flight at the time of our
6566 			 * send  and the size of this send to figure
6567 			 * out what we have been sending at (amount).
6568 			 * For the time we take from the time of
6569 			 * the send of the first send outstanding
6570 			 * until this send plus this sends pacing
6571 			 * time. This gives us a good calculation
6572 			 * as to the rate we have been sending at.
6573 			 */
6574 
6575 			sbw = (uint64_t)(rsm->r_flight_at_send);
6576 			sbw *= (uint64_t)USECS_IN_SECOND;
6577 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6578 			sti += rsm->r_pacing_delay;
6579 			sbw /= sti;
6580 			if (sbw < bw) {
6581 				bbr_log_type_bbrupd(bbr, 6, cts,
6582 						    delivered,
6583 						    (uint32_t)sti,
6584 						    (bw >> 32),
6585 						    (uint32_t)bw,
6586 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6587 						    (uint32_t)sbw);
6588 				bw = sbw;
6589 			}
6590 		}
6591 		/* Use the google algorithm for b/w measurements */
6592 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6593 		if ((rsm->r_app_limited == 0) ||
6594 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6595 			tcp_bbr_commit_bw(bbr, cts);
6596 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6597 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6598 		}
6599 	}
6600 }
6601 
6602 static void
6603 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6604 {
6605 	if (bbr->rc_in_persist == 0) {
6606 		/* We log only when not in persist */
6607 		/* Translate to a Bytes Per Second */
6608 		uint64_t tim, bw;
6609 		uint32_t delivered;
6610 		int no_apply = 0;
6611 
6612 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6613 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6614 		else
6615 			tim = 1;
6616 		/*
6617 		 * Now that we have processed the tim (skipping the sample
6618 		 * or possibly updating the time, go ahead and
6619 		 * calculate the cdr.
6620 		 */
6621 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6622 		bw = (uint64_t)delivered;
6623 		bw *= (uint64_t)USECS_IN_SECOND;
6624 		bw /= tim;
6625 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6626 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6627 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6628 
6629 			no_apply = 1;
6630 		}
6631 		/*
6632 		 * If we are using this b/w shove it in now so we
6633 		 * can see in the trace viewer if it gets over-ridden.
6634 		 */
6635 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6636 		/* Gate by the sending rate */
6637 		if (rsm->r_first_sent_time &&
6638 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6639 			uint64_t sbw, sti;
6640 			/*
6641 			 * We use what was in flight at the time of our
6642 			 * send  and the size of this send to figure
6643 			 * out what we have been sending at (amount).
6644 			 * For the time we take from the time of
6645 			 * the send of the first send outstanding
6646 			 * until this send plus this sends pacing
6647 			 * time. This gives us a good calculation
6648 			 * as to the rate we have been sending at.
6649 			 */
6650 
6651 			sbw = (uint64_t)(rsm->r_flight_at_send);
6652 			sbw *= (uint64_t)USECS_IN_SECOND;
6653 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6654 			sti += rsm->r_pacing_delay;
6655 			sbw /= sti;
6656 			if (sbw < bw) {
6657 				bbr_log_type_bbrupd(bbr, 6, cts,
6658 						    delivered,
6659 						    (uint32_t)sti,
6660 						    (bw >> 32),
6661 						    (uint32_t)bw,
6662 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6663 						    (uint32_t)sbw);
6664 				bw = sbw;
6665 			}
6666 			if ((sti > tim) &&
6667 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6668 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6669 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6670 				no_apply = 1;
6671 			} else
6672 				no_apply = 0;
6673 		}
6674 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6675 		if ((no_apply == 0) &&
6676 		    ((rsm->r_app_limited == 0) ||
6677 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6678 			tcp_bbr_commit_bw(bbr, cts);
6679 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6680 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6681 		}
6682 	}
6683 }
6684 
6685 static void
6686 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6687     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6688 {
6689 	uint64_t old_rttprop;
6690 
6691 	/* Update our delivery time and amount */
6692 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6693 	bbr->r_ctl.rc_del_time = cts;
6694 	if (rtt == 0) {
6695 		/*
6696 		 * 0 means its a retransmit, for now we don't use these for
6697 		 * the rest of BBR.
6698 		 */
6699 		return;
6700 	}
6701 	if ((bbr->rc_use_google == 0) &&
6702 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6703 	    (match != BBR_RTT_BY_TIMESTAMP)){
6704 		/*
6705 		 * We get a lot of rtt updates, lets not pay attention to
6706 		 * any that are not an exact match. That way we don't have
6707 		 * to worry about timestamps and the whole nonsense of
6708 		 * unsure if its a retransmission etc (if we ever had the
6709 		 * timestamp fixed to always have the last thing sent this
6710 		 * would not be a issue).
6711 		 */
6712 		return;
6713 	}
6714 	if ((bbr_no_retran && bbr->rc_use_google) &&
6715 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6716 	    (match != BBR_RTT_BY_TIMESTAMP)){
6717 		/*
6718 		 * We only do measurements in google mode
6719 		 * with bbr_no_retran on for sure things.
6720 		 */
6721 		return;
6722 	}
6723 	/* Only update srtt if we know by exact match */
6724 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6725 	if (ack_type == BBR_CUM_ACKED)
6726 		bbr->rc_ack_is_cumack = 1;
6727 	else
6728 		bbr->rc_ack_is_cumack = 0;
6729 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6730 	/*
6731 	 * Note the following code differs to the original
6732 	 * BBR spec. It calls for <= not <. However after a
6733 	 * long discussion in email with Neal, he acknowledged
6734 	 * that it should be < than so that we will have flows
6735 	 * going into probe-rtt (we were seeing cases where that
6736 	 * did not happen and caused ugly things to occur). We
6737 	 * have added this agreed upon fix to our code base.
6738 	 */
6739 	if (rtt < old_rttprop) {
6740 		/* Update when we last saw a rtt drop */
6741 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6742 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6743 	}
6744 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6745 	    match, rsm->r_start, rsm->r_flags);
6746 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6747 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6748 		/*
6749 		 * The RTT-prop moved, reset the target (may be a
6750 		 * nop for some states).
6751 		 */
6752 		bbr_set_state_target(bbr, __LINE__);
6753 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6754 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6755 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6756 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6757 			/* It went up */
6758 			bbr_check_probe_rtt_limits(bbr, cts);
6759 	}
6760 	if ((bbr->rc_use_google == 0) &&
6761 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6762 		/*
6763 		 * We don't do b/w update with
6764 		 * these since they are not really
6765 		 * reliable.
6766 		 */
6767 		return;
6768 	}
6769 	if (bbr->r_ctl.r_app_limited_until &&
6770 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6771 		/* We are no longer app-limited */
6772 		bbr->r_ctl.r_app_limited_until = 0;
6773 	}
6774 	if (bbr->rc_use_google) {
6775 		bbr_google_measurement(bbr, rsm, rtt, cts);
6776 	} else {
6777 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6778 	}
6779 }
6780 
6781 /*
6782  * Convert a timestamp that the main stack
6783  * uses (milliseconds) into one that bbr uses
6784  * (microseconds). Return that converted timestamp.
6785  */
6786 static uint32_t
6787 bbr_ts_convert(uint32_t cts) {
6788 	uint32_t sec, msec;
6789 
6790 	sec = cts / MS_IN_USEC;
6791 	msec = cts - (MS_IN_USEC * sec);
6792 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6793 }
6794 
6795 /*
6796  * Return 0 if we did not update the RTT time, return
6797  * 1 if we did.
6798  */
6799 static int
6800 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6801     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6802 {
6803 	int32_t i;
6804 	uint32_t t, uts = 0;
6805 
6806 	if ((rsm->r_flags & BBR_ACKED) ||
6807 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6808 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6809 		/* Already done */
6810 		return (0);
6811 	}
6812 	if (rsm->r_rtt_not_allowed) {
6813 		/* Not allowed */
6814 		return (0);
6815 	}
6816 	if (rsm->r_rtr_cnt == 1) {
6817 		/*
6818 		 * Only one transmit. Hopefully the normal case.
6819 		 */
6820 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6821 			t = cts - rsm->r_tim_lastsent[0];
6822 		else
6823 			t = 1;
6824 		if ((int)t <= 0)
6825 			t = 1;
6826 		bbr->r_ctl.rc_last_rtt = t;
6827 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6828 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6829 		return (1);
6830 	}
6831 	/* Convert to usecs */
6832 	if ((bbr_can_use_ts_for_rtt == 1) &&
6833 	    (bbr->rc_use_google == 1) &&
6834 	    (ack_type == BBR_CUM_ACKED) &&
6835 	    (to->to_flags & TOF_TS) &&
6836 	    (to->to_tsecr != 0)) {
6837 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6838 		if (t < 1)
6839 			t = 1;
6840 		t *= MS_IN_USEC;
6841 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6842 				    BBR_RTT_BY_TIMESTAMP,
6843 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6844 				    ack_type, to);
6845 		return (1);
6846 	}
6847 	uts = bbr_ts_convert(to->to_tsecr);
6848 	if ((to->to_flags & TOF_TS) &&
6849 	    (to->to_tsecr != 0) &&
6850 	    (ack_type == BBR_CUM_ACKED) &&
6851 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6852 		/*
6853 		 * Now which timestamp does it match? In this block the ACK
6854 		 * may be coming from a previous transmission.
6855 		 */
6856 		uint32_t fudge;
6857 
6858 		fudge = BBR_TIMER_FUDGE;
6859 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6860 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6861 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6862 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6863 					t = cts - rsm->r_tim_lastsent[i];
6864 				else
6865 					t = 1;
6866 				if ((int)t <= 0)
6867 					t = 1;
6868 				bbr->r_ctl.rc_last_rtt = t;
6869 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6870 						    rsm->r_tim_lastsent[i], ack_type, to);
6871 				if ((i + 1) < rsm->r_rtr_cnt) {
6872 					/* Likely */
6873 					return (0);
6874 				} else if (rsm->r_flags & BBR_TLP) {
6875 					bbr->rc_tlp_rtx_out = 0;
6876 				}
6877 				return (1);
6878 			}
6879 		}
6880 		/* Fall through if we can't find a matching timestamp */
6881 	}
6882 	/*
6883 	 * Ok its a SACK block that we retransmitted. or a windows
6884 	 * machine without timestamps. We can tell nothing from the
6885 	 * time-stamp since its not there or the time the peer last
6886 	 * recieved a segment that moved forward its cum-ack point.
6887 	 *
6888 	 * Lets look at the last retransmit and see what we can tell
6889 	 * (with BBR for space we only keep 2 note we have to keep
6890 	 * at least 2 so the map can not be condensed more).
6891 	 */
6892 	i = rsm->r_rtr_cnt - 1;
6893 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6894 		t = cts - rsm->r_tim_lastsent[i];
6895 	else
6896 		goto not_sure;
6897 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6898 		/*
6899 		 * We retransmitted and the ack came back in less
6900 		 * than the smallest rtt we have observed in the
6901 		 * windowed rtt. We most likey did an improper
6902 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6903 		 * the rack-draft.
6904 		 *
6905 		 * Use the prior transmission to update all the
6906 		 * information as long as there is only one prior
6907 		 * transmission.
6908 		 */
6909 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6910 #ifdef BBR_INVARIANTS
6911 			if (rsm->r_rtr_cnt == 1)
6912 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6913 #endif
6914 			i = rsm->r_rtr_cnt - 2;
6915 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6916 				t = cts - rsm->r_tim_lastsent[i];
6917 			else
6918 				t = 1;
6919 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6920 					    rsm->r_tim_lastsent[i], ack_type, to);
6921 			return (0);
6922 		} else {
6923 			/*
6924 			 * Too many prior transmissions, just
6925 			 * updated BBR delivered
6926 			 */
6927 not_sure:
6928 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6929 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6930 		}
6931 	} else {
6932 		/*
6933 		 * We retransmitted it and the retransmit did the
6934 		 * job.
6935 		 */
6936 		if (rsm->r_flags & BBR_TLP)
6937 			bbr->rc_tlp_rtx_out = 0;
6938 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6939 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6940 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6941 		else
6942 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6943 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6944 		return (1);
6945 	}
6946 	return (0);
6947 }
6948 
6949 /*
6950  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6951  */
6952 static void
6953 bbr_log_sack_passed(struct tcpcb *tp,
6954     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6955 {
6956 	struct bbr_sendmap *nrsm;
6957 
6958 	nrsm = rsm;
6959 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6960 	    bbr_head, r_tnext) {
6961 		if (nrsm == rsm) {
6962 			/* Skip orginal segment he is acked */
6963 			continue;
6964 		}
6965 		if (nrsm->r_flags & BBR_ACKED) {
6966 			/* Skip ack'd segments */
6967 			continue;
6968 		}
6969 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6970 			/*
6971 			 * We found one that is already marked
6972 			 * passed, we have been here before and
6973 			 * so all others below this are marked.
6974 			 */
6975 			break;
6976 		}
6977 		BBR_STAT_INC(bbr_sack_passed);
6978 		nrsm->r_flags |= BBR_SACK_PASSED;
6979 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6980 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6981 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6982 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6983 			nrsm->r_flags |= BBR_MARKED_LOST;
6984 		}
6985 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6986 	}
6987 }
6988 
6989 /*
6990  * Returns the number of bytes that were
6991  * newly ack'd by sack blocks.
6992  */
6993 static uint32_t
6994 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6995     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6996 {
6997 	int32_t times = 0;
6998 	uint32_t start, end, changed = 0;
6999 	struct bbr_sendmap *rsm, *nrsm;
7000 	int32_t used_ref = 1;
7001 	uint8_t went_back = 0, went_fwd = 0;
7002 
7003 	start = sack->start;
7004 	end = sack->end;
7005 	rsm = *prsm;
7006 	if (rsm == NULL)
7007 		used_ref = 0;
7008 
7009 	/* Do we locate the block behind where we last were? */
7010 	if (rsm && SEQ_LT(start, rsm->r_start)) {
7011 		went_back = 1;
7012 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7013 			if (SEQ_GEQ(start, rsm->r_start) &&
7014 			    SEQ_LT(start, rsm->r_end)) {
7015 				goto do_rest_ofb;
7016 			}
7017 		}
7018 	}
7019 start_at_beginning:
7020 	went_fwd = 1;
7021 	/*
7022 	 * Ok lets locate the block where this guy is fwd from rsm (if its
7023 	 * set)
7024 	 */
7025 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7026 		if (SEQ_GEQ(start, rsm->r_start) &&
7027 		    SEQ_LT(start, rsm->r_end)) {
7028 			break;
7029 		}
7030 	}
7031 do_rest_ofb:
7032 	if (rsm == NULL) {
7033 		/*
7034 		 * This happens when we get duplicate sack blocks with the
7035 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7036 		 * will not change there location so we would just start at
7037 		 * the end of the first one and get lost.
7038 		 */
7039 		if (tp->t_flags & TF_SENTFIN) {
7040 			/*
7041 			 * Check to see if we have not logged the FIN that
7042 			 * went out.
7043 			 */
7044 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7045 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7046 				/*
7047 				 * Ok we did not get the FIN logged.
7048 				 */
7049 				nrsm->r_end++;
7050 				rsm = nrsm;
7051 				goto do_rest_ofb;
7052 			}
7053 		}
7054 		if (times == 1) {
7055 #ifdef BBR_INVARIANTS
7056 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7057 			    tp, bbr, sack, to, prsm);
7058 #else
7059 			goto out;
7060 #endif
7061 		}
7062 		times++;
7063 		BBR_STAT_INC(bbr_sack_proc_restart);
7064 		rsm = NULL;
7065 		goto start_at_beginning;
7066 	}
7067 	/* Ok we have an ACK for some piece of rsm */
7068 	if (rsm->r_start != start) {
7069 		/*
7070 		 * Need to split this in two pieces the before and after.
7071 		 */
7072 		if (bbr_sack_mergable(rsm, start, end))
7073 			nrsm = bbr_alloc_full_limit(bbr);
7074 		else
7075 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7076 		if (nrsm == NULL) {
7077 			/* We could not allocate ignore the sack */
7078 			struct sackblk blk;
7079 
7080 			blk.start = start;
7081 			blk.end = end;
7082 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7083 			goto out;
7084 		}
7085 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7086 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7087 		if (rsm->r_in_tmap) {
7088 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7089 			nrsm->r_in_tmap = 1;
7090 		}
7091 		rsm->r_flags &= (~BBR_HAS_FIN);
7092 		rsm = nrsm;
7093 	}
7094 	if (SEQ_GEQ(end, rsm->r_end)) {
7095 		/*
7096 		 * The end of this block is either beyond this guy or right
7097 		 * at this guy.
7098 		 */
7099 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7100 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7101 			changed += (rsm->r_end - rsm->r_start);
7102 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7103 			bbr_log_sack_passed(tp, bbr, rsm);
7104 			if (rsm->r_flags & BBR_MARKED_LOST) {
7105 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7106 			}
7107 			/* Is Reordering occuring? */
7108 			if (rsm->r_flags & BBR_SACK_PASSED) {
7109 				BBR_STAT_INC(bbr_reorder_seen);
7110 				bbr->r_ctl.rc_reorder_ts = cts;
7111 				if (rsm->r_flags & BBR_MARKED_LOST) {
7112 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7113 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7114 						/* LT sampling also needs adjustment */
7115 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7116 				}
7117 			}
7118 			rsm->r_flags |= BBR_ACKED;
7119 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7120 			if (rsm->r_in_tmap) {
7121 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7122 				rsm->r_in_tmap = 0;
7123 			}
7124 		}
7125 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7126 		if (end == rsm->r_end) {
7127 			/* This block only - done */
7128 			goto out;
7129 		}
7130 		/* There is more not coverend by this rsm move on */
7131 		start = rsm->r_end;
7132 		nrsm = TAILQ_NEXT(rsm, r_next);
7133 		rsm = nrsm;
7134 		times = 0;
7135 		goto do_rest_ofb;
7136 	}
7137 	if (rsm->r_flags & BBR_ACKED) {
7138 		/* Been here done that */
7139 		goto out;
7140 	}
7141 	/* Ok we need to split off this one at the tail */
7142 	if (bbr_sack_mergable(rsm, start, end))
7143 		nrsm = bbr_alloc_full_limit(bbr);
7144 	else
7145 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7146 	if (nrsm == NULL) {
7147 		/* failed XXXrrs what can we do but loose the sack info? */
7148 		struct sackblk blk;
7149 
7150 		blk.start = start;
7151 		blk.end = end;
7152 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7153 		goto out;
7154 	}
7155 	/* Clone it */
7156 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7157 	/* The sack block does not cover this guy fully */
7158 	rsm->r_flags &= (~BBR_HAS_FIN);
7159 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7160 	if (rsm->r_in_tmap) {
7161 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7162 		nrsm->r_in_tmap = 1;
7163 	}
7164 	nrsm->r_dupack = 0;
7165 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7166 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7167 	changed += (rsm->r_end - rsm->r_start);
7168 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7169 	bbr_log_sack_passed(tp, bbr, rsm);
7170 	/* Is Reordering occuring? */
7171 	if (rsm->r_flags & BBR_MARKED_LOST) {
7172 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7173 	}
7174 	if (rsm->r_flags & BBR_SACK_PASSED) {
7175 		BBR_STAT_INC(bbr_reorder_seen);
7176 		bbr->r_ctl.rc_reorder_ts = cts;
7177 		if (rsm->r_flags & BBR_MARKED_LOST) {
7178 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7179 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7180 				/* LT sampling also needs adjustment */
7181 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7182 		}
7183 	}
7184 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7185 	rsm->r_flags |= BBR_ACKED;
7186 	if (rsm->r_in_tmap) {
7187 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7188 		rsm->r_in_tmap = 0;
7189 	}
7190 out:
7191 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7192 		/*
7193 		 * Now can we merge this newly acked
7194 		 * block with either the previous or
7195 		 * next block?
7196 		 */
7197 		nrsm = TAILQ_NEXT(rsm, r_next);
7198 		if (nrsm &&
7199 		    (nrsm->r_flags & BBR_ACKED)) {
7200 			/* yep this and next can be merged */
7201 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7202 		}
7203 		/* Now what about the previous? */
7204 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7205 		if (nrsm &&
7206 		    (nrsm->r_flags & BBR_ACKED)) {
7207 			/* yep the previous and this can be merged */
7208 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7209 		}
7210 	}
7211 	if (used_ref == 0) {
7212 		BBR_STAT_INC(bbr_sack_proc_all);
7213 	} else {
7214 		BBR_STAT_INC(bbr_sack_proc_short);
7215 	}
7216 	if (went_fwd && went_back) {
7217 		BBR_STAT_INC(bbr_sack_search_both);
7218 	} else if (went_fwd) {
7219 		BBR_STAT_INC(bbr_sack_search_fwd);
7220 	} else if (went_back) {
7221 		BBR_STAT_INC(bbr_sack_search_back);
7222 	}
7223 	/* Save off where the next seq is */
7224 	if (rsm)
7225 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7226 	else
7227 		bbr->r_ctl.rc_sacklast = NULL;
7228 	*prsm = rsm;
7229 	return (changed);
7230 }
7231 
7232 static void inline
7233 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7234 {
7235 	struct bbr_sendmap *tmap;
7236 
7237 	BBR_STAT_INC(bbr_reneges_seen);
7238 	tmap = NULL;
7239 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7240 		/* Its no longer sacked, mark it so */
7241 		uint32_t oflags;
7242 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7243 #ifdef BBR_INVARIANTS
7244 		if (rsm->r_in_tmap) {
7245 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7246 			    bbr, rsm, rsm->r_flags);
7247 		}
7248 #endif
7249 		oflags = rsm->r_flags;
7250 		if (rsm->r_flags & BBR_MARKED_LOST) {
7251 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7252 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7253 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7254 				/* LT sampling also needs adjustment */
7255 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7256 		}
7257 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7258 		rsm->r_flags |= BBR_WAS_RENEGED;
7259 		rsm->r_flags |= BBR_RXT_CLEARED;
7260 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7261 		/* Rebuild it into our tmap */
7262 		if (tmap == NULL) {
7263 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7264 			tmap = rsm;
7265 		} else {
7266 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7267 			tmap = rsm;
7268 		}
7269 		tmap->r_in_tmap = 1;
7270 		/*
7271 		 * XXXrrs Delivered? Should we do anything here?
7272 		 *
7273 		 * Of course we don't on a rxt timeout so maybe its ok that
7274 		 * we don't?
7275 		 *
7276 		 * For now lets not.
7277 		 */
7278 		rsm = TAILQ_NEXT(rsm, r_next);
7279 	}
7280 	/*
7281 	 * Now lets possibly clear the sack filter so we start recognizing
7282 	 * sacks that cover this area.
7283 	 */
7284 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7285 }
7286 
7287 static void
7288 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7289 {
7290 	struct tcp_bbr *bbr;
7291 	struct bbr_sendmap *rsm;
7292 	uint32_t cts;
7293 
7294 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7295 	cts = bbr->r_ctl.rc_rcvtime;
7296 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7297 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7298 		if ((rsm->r_end - rsm->r_start) <= 1) {
7299 			/* Log out the SYN completely */
7300 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7301 			rsm->r_rtr_bytes = 0;
7302 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7303 			if (rsm->r_in_tmap) {
7304 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7305 				rsm->r_in_tmap = 0;
7306 			}
7307 			if (bbr->r_ctl.rc_next == rsm) {
7308 				/* scoot along the marker */
7309 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7310 			}
7311 			if (to != NULL)
7312 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7313 			bbr_free(bbr, rsm);
7314 		} else {
7315 			/* There is more (Fast open)? strip out SYN. */
7316 			rsm->r_flags &= ~BBR_HAS_SYN;
7317 			rsm->r_start++;
7318 		}
7319 	}
7320 }
7321 
7322 /*
7323  * Returns the number of bytes that were
7324  * acknowledged by SACK blocks.
7325  */
7326 
7327 static uint32_t
7328 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7329     uint32_t *prev_acked)
7330 {
7331 	uint32_t changed, last_seq, entered_recovery = 0;
7332 	struct tcp_bbr *bbr;
7333 	struct bbr_sendmap *rsm;
7334 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7335 	register uint32_t th_ack;
7336 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7337 	uint32_t cts, acked, ack_point, sack_changed = 0;
7338 	uint32_t p_maxseg, maxseg, p_acked = 0;
7339 
7340 	INP_WLOCK_ASSERT(tp->t_inpcb);
7341 	if (th->th_flags & TH_RST) {
7342 		/* We don't log resets */
7343 		return (0);
7344 	}
7345 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7346 	cts = bbr->r_ctl.rc_rcvtime;
7347 
7348 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7349 	changed = 0;
7350 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7351 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7352 	th_ack = th->th_ack;
7353 	if (SEQ_GT(th_ack, tp->snd_una)) {
7354 		acked = th_ack - tp->snd_una;
7355 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7356 		bbr->rc_tp->t_acktime = ticks;
7357 	} else
7358 		acked = 0;
7359 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7360 		/* Only sent here for sack processing */
7361 		goto proc_sack;
7362 	}
7363 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7364 		changed = th_ack - rsm->r_start;
7365 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7366 		/*
7367 		 * For the SYN incoming case we will not have called
7368 		 * tcp_output for the sending of the SYN, so there will be
7369 		 * no map. All other cases should probably be a panic.
7370 		 */
7371 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7372 			/*
7373 			 * We have a timestamp that can be used to generate
7374 			 * an initial RTT.
7375 			 */
7376 			uint32_t ts, now, rtt;
7377 
7378 			ts = bbr_ts_convert(to->to_tsecr);
7379 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7380 			rtt = now - ts;
7381 			if (rtt < 1)
7382 				rtt = 1;
7383 			bbr_log_type_bbrrttprop(bbr, rtt,
7384 						tp->iss, 0, cts,
7385 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7386 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7387 			changed = 1;
7388 			bbr->r_wanted_output = 1;
7389 			goto out;
7390 		}
7391 		goto proc_sack;
7392 	} else if (rsm == NULL) {
7393 		goto out;
7394 	}
7395 	if (changed) {
7396 		/*
7397 		 * The ACK point is advancing to th_ack, we must drop off
7398 		 * the packets in the rack log and calculate any eligble
7399 		 * RTT's.
7400 		 */
7401 		bbr->r_wanted_output = 1;
7402 more:
7403 		if (rsm == NULL) {
7404 			if (tp->t_flags & TF_SENTFIN) {
7405 				/* if we send a FIN we will not hav a map */
7406 				goto proc_sack;
7407 			}
7408 #ifdef BBR_INVARIANTS
7409 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7410 			    tp,
7411 			    th, tp->t_state, bbr,
7412 			    tp->snd_una, tp->snd_max, changed);
7413 #endif
7414 			goto proc_sack;
7415 		}
7416 	}
7417 	if (SEQ_LT(th_ack, rsm->r_start)) {
7418 		/* Huh map is missing this */
7419 #ifdef BBR_INVARIANTS
7420 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7421 		    rsm->r_start,
7422 		    th_ack, tp->t_state,
7423 		    bbr->r_state, bbr);
7424 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7425 #endif
7426 		goto proc_sack;
7427 	} else if (th_ack == rsm->r_start) {
7428 		/* None here to ack */
7429 		goto proc_sack;
7430 	}
7431 	/*
7432 	 * Clear the dup ack counter, it will
7433 	 * either be freed or if there is some
7434 	 * remaining we need to start it at zero.
7435 	 */
7436 	rsm->r_dupack = 0;
7437 	/* Now do we consume the whole thing? */
7438 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7439 		/* Its all consumed. */
7440 		uint32_t left;
7441 
7442 		if (rsm->r_flags & BBR_ACKED) {
7443 			/*
7444 			 * It was acked on the scoreboard -- remove it from
7445 			 * total
7446 			 */
7447 			p_acked += (rsm->r_end - rsm->r_start);
7448 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7449 			if (bbr->r_ctl.rc_sacked == 0)
7450 				bbr->r_ctl.rc_sacklast = NULL;
7451 		} else {
7452 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7453 			if (rsm->r_flags & BBR_MARKED_LOST) {
7454 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7455 			}
7456 			if (rsm->r_flags & BBR_SACK_PASSED) {
7457 				/*
7458 				 * There are acked segments ACKED on the
7459 				 * scoreboard further up. We are seeing
7460 				 * reordering.
7461 				 */
7462 				BBR_STAT_INC(bbr_reorder_seen);
7463 				bbr->r_ctl.rc_reorder_ts = cts;
7464 				if (rsm->r_flags & BBR_MARKED_LOST) {
7465 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7466 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7467 						/* LT sampling also needs adjustment */
7468 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7469 				}
7470 			}
7471 			rsm->r_flags &= ~BBR_MARKED_LOST;
7472 		}
7473 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7474 		rsm->r_rtr_bytes = 0;
7475 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7476 		if (rsm->r_in_tmap) {
7477 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7478 			rsm->r_in_tmap = 0;
7479 		}
7480 		if (bbr->r_ctl.rc_next == rsm) {
7481 			/* scoot along the marker */
7482 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7483 		}
7484 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7485 		/* Adjust the packet counts */
7486 		left = th_ack - rsm->r_end;
7487 		/* Free back to zone */
7488 		bbr_free(bbr, rsm);
7489 		if (left) {
7490 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7491 			goto more;
7492 		}
7493 		goto proc_sack;
7494 	}
7495 	if (rsm->r_flags & BBR_ACKED) {
7496 		/*
7497 		 * It was acked on the scoreboard -- remove it from total
7498 		 * for the part being cum-acked.
7499 		 */
7500 		p_acked += (rsm->r_end - rsm->r_start);
7501 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7502 		if (bbr->r_ctl.rc_sacked == 0)
7503 			bbr->r_ctl.rc_sacklast = NULL;
7504 	} else {
7505 		/*
7506 		 * It was acked up to th_ack point for the first time
7507 		 */
7508 		struct bbr_sendmap lrsm;
7509 
7510 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7511 		lrsm.r_end = th_ack;
7512 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7513 	}
7514 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7515 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7516 		/*
7517 		 * It was marked lost and partly ack'd now
7518 		 * for the first time. We lower the rc_lost_bytes
7519 		 * and still leave it MARKED.
7520 		 */
7521 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7522 	}
7523 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7524 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7525 	rsm->r_rtr_bytes = 0;
7526 	/* adjust packet count */
7527 	rsm->r_start = th_ack;
7528 proc_sack:
7529 	/* Check for reneging */
7530 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7531 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7532 		/*
7533 		 * The peer has moved snd_una up to the edge of this send,
7534 		 * i.e. one that it had previously acked. The only way that
7535 		 * can be true if the peer threw away data (space issues)
7536 		 * that it had previously sacked (else it would have given
7537 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7538 		 * markings here.
7539 		 *
7540 		 * Note we have to look to make sure th_ack is our
7541 		 * rsm->r_start in case we get an old ack where th_ack is
7542 		 * behind snd_una.
7543 		 */
7544 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7545 	}
7546 	if ((to->to_flags & TOF_SACK) == 0) {
7547 		/* We are done nothing left to log */
7548 		goto out;
7549 	}
7550 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7551 	if (rsm) {
7552 		last_seq = rsm->r_end;
7553 	} else {
7554 		last_seq = tp->snd_max;
7555 	}
7556 	/* Sack block processing */
7557 	if (SEQ_GT(th_ack, tp->snd_una))
7558 		ack_point = th_ack;
7559 	else
7560 		ack_point = tp->snd_una;
7561 	for (i = 0; i < to->to_nsacks; i++) {
7562 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7563 		    &sack, sizeof(sack));
7564 		sack.start = ntohl(sack.start);
7565 		sack.end = ntohl(sack.end);
7566 		if (SEQ_GT(sack.end, sack.start) &&
7567 		    SEQ_GT(sack.start, ack_point) &&
7568 		    SEQ_LT(sack.start, tp->snd_max) &&
7569 		    SEQ_GT(sack.end, ack_point) &&
7570 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7571 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7572 			    (SEQ_LT(sack.end, last_seq)) &&
7573 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7574 				/*
7575 				 * Not the last piece and its smaller than
7576 				 * 1/8th of a p_maxseg. We ignore this.
7577 				 */
7578 				BBR_STAT_INC(bbr_runt_sacks);
7579 				continue;
7580 			}
7581 			sack_blocks[num_sack_blks] = sack;
7582 			num_sack_blks++;
7583 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7584 		    SEQ_LEQ(sack.end, th_ack)) {
7585 			/*
7586 			 * Its a D-SACK block.
7587 			 */
7588 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7589 		}
7590 	}
7591 	if (num_sack_blks == 0)
7592 		goto out;
7593 	/*
7594 	 * Sort the SACK blocks so we can update the rack scoreboard with
7595 	 * just one pass.
7596 	 */
7597 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7598 				  num_sack_blks, th->th_ack);
7599 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7600 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7601 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7602 	num_sack_blks = new_sb;
7603 	if (num_sack_blks < 2) {
7604 		goto do_sack_work;
7605 	}
7606 	/* Sort the sacks */
7607 	for (i = 0; i < num_sack_blks; i++) {
7608 		for (j = i + 1; j < num_sack_blks; j++) {
7609 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7610 				sack = sack_blocks[i];
7611 				sack_blocks[i] = sack_blocks[j];
7612 				sack_blocks[j] = sack;
7613 			}
7614 		}
7615 	}
7616 	/*
7617 	 * Now are any of the sack block ends the same (yes some
7618 	 * implememtations send these)?
7619 	 */
7620 again:
7621 	if (num_sack_blks > 1) {
7622 		for (i = 0; i < num_sack_blks; i++) {
7623 			for (j = i + 1; j < num_sack_blks; j++) {
7624 				if (sack_blocks[i].end == sack_blocks[j].end) {
7625 					/*
7626 					 * Ok these two have the same end we
7627 					 * want the smallest end and then
7628 					 * throw away the larger and start
7629 					 * again.
7630 					 */
7631 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7632 						/*
7633 						 * The second block covers
7634 						 * more area use that
7635 						 */
7636 						sack_blocks[i].start = sack_blocks[j].start;
7637 					}
7638 					/*
7639 					 * Now collapse out the dup-sack and
7640 					 * lower the count
7641 					 */
7642 					for (k = (j + 1); k < num_sack_blks; k++) {
7643 						sack_blocks[j].start = sack_blocks[k].start;
7644 						sack_blocks[j].end = sack_blocks[k].end;
7645 						j++;
7646 					}
7647 					num_sack_blks--;
7648 					goto again;
7649 				}
7650 			}
7651 		}
7652 	}
7653 do_sack_work:
7654 	rsm = bbr->r_ctl.rc_sacklast;
7655 	for (i = 0; i < num_sack_blks; i++) {
7656 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7657 		if (acked) {
7658 			bbr->r_wanted_output = 1;
7659 			changed += acked;
7660 			sack_changed += acked;
7661 		}
7662 	}
7663 out:
7664 	*prev_acked = p_acked;
7665 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7666 		/*
7667 		 * Ok we have a high probability that we need to go in to
7668 		 * recovery since we have data sack'd
7669 		 */
7670 		struct bbr_sendmap *rsm;
7671 
7672 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7673 		if (rsm) {
7674 			/* Enter recovery */
7675 			entered_recovery = 1;
7676 			bbr->r_wanted_output = 1;
7677 			/*
7678 			 * When we enter recovery we need to assure we send
7679 			 * one packet.
7680 			 */
7681 			if (bbr->r_ctl.rc_resend == NULL) {
7682 				bbr->r_ctl.rc_resend = rsm;
7683 			}
7684 		}
7685 	}
7686 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7687 		/*
7688 		 * See if we need to rack-retransmit anything if so set it
7689 		 * up as the thing to resend assuming something else is not
7690 		 * already in that position.
7691 		 */
7692 		if (bbr->r_ctl.rc_resend == NULL) {
7693 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7694 		}
7695 	}
7696 	/*
7697 	 * We return the amount that changed via sack, this is used by the
7698 	 * ack-received code to augment what was changed between th_ack <->
7699 	 * snd_una.
7700 	 */
7701 	return (sack_changed);
7702 }
7703 
7704 static void
7705 bbr_strike_dupack(struct tcp_bbr *bbr)
7706 {
7707 	struct bbr_sendmap *rsm;
7708 
7709 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7710 	if (rsm && (rsm->r_dupack < 0xff)) {
7711 		rsm->r_dupack++;
7712 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7713 			bbr->r_wanted_output = 1;
7714 	}
7715 }
7716 
7717 /*
7718  * Return value of 1, we do not need to call bbr_process_data().
7719  * return value of 0, bbr_process_data can be called.
7720  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7721  * its unlocked and probably unsafe to touch the TCB.
7722  */
7723 static int
7724 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7725     struct tcpcb *tp, struct tcpopt *to,
7726     uint32_t tiwin, int32_t tlen,
7727     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7728 {
7729 	int32_t ourfinisacked = 0;
7730 	int32_t acked_amount;
7731 	uint16_t nsegs;
7732 	int32_t acked;
7733 	uint32_t lost, sack_changed = 0;
7734 	struct mbuf *mfree;
7735 	struct tcp_bbr *bbr;
7736 	uint32_t prev_acked = 0;
7737 
7738 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7739 	lost = bbr->r_ctl.rc_lost;
7740 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7741 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7742 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7743 		bbr->r_wanted_output = 1;
7744 		return (1);
7745 	}
7746 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7747 		/* Process the ack */
7748 		if (bbr->rc_in_persist)
7749 			tp->t_rxtshift = 0;
7750 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7751 		        bbr_strike_dupack(bbr);
7752 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7753 	}
7754 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7755 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7756 		/*
7757 		 * Old ack, behind the last one rcv'd or a duplicate ack
7758 		 * with SACK info.
7759 		 */
7760 		if (th->th_ack == tp->snd_una) {
7761 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7762 			if (bbr->r_state == TCPS_SYN_SENT) {
7763 				/*
7764 				 * Special case on where we sent SYN. When
7765 				 * the SYN-ACK is processed in syn_sent
7766 				 * state it bumps the snd_una. This causes
7767 				 * us to hit here even though we did ack 1
7768 				 * byte.
7769 				 *
7770 				 * Go through the nothing left case so we
7771 				 * send data.
7772 				 */
7773 				goto nothing_left;
7774 			}
7775 		}
7776 		return (0);
7777 	}
7778 	/*
7779 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7780 	 * something we sent.
7781 	 */
7782 	if (tp->t_flags & TF_NEEDSYN) {
7783 		/*
7784 		 * T/TCP: Connection was half-synchronized, and our SYN has
7785 		 * been ACK'd (so connection is now fully synchronized).  Go
7786 		 * to non-starred state, increment snd_una for ACK of SYN,
7787 		 * and check if we can do window scaling.
7788 		 */
7789 		tp->t_flags &= ~TF_NEEDSYN;
7790 		tp->snd_una++;
7791 		/* Do window scaling? */
7792 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7793 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7794 			tp->rcv_scale = tp->request_r_scale;
7795 			/* Send window already scaled. */
7796 		}
7797 	}
7798 	INP_WLOCK_ASSERT(tp->t_inpcb);
7799 
7800 	acked = BYTES_THIS_ACK(tp, th);
7801 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7802 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7803 
7804 	/*
7805 	 * If we just performed our first retransmit, and the ACK arrives
7806 	 * within our recovery window, then it was a mistake to do the
7807 	 * retransmit in the first place.  Recover our original cwnd and
7808 	 * ssthresh, and proceed to transmit where we left off.
7809 	 */
7810 	if (tp->t_flags & TF_PREVVALID) {
7811 		tp->t_flags &= ~TF_PREVVALID;
7812 		if (tp->t_rxtshift == 1 &&
7813 		    (int)(ticks - tp->t_badrxtwin) < 0)
7814 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7815 	}
7816 	SOCKBUF_LOCK(&so->so_snd);
7817 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7818 	tp->snd_wnd -= acked_amount;
7819 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7820 	/* NB: sowwakeup_locked() does an implicit unlock. */
7821 	sowwakeup_locked(so);
7822 	m_freem(mfree);
7823 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7824 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7825 	}
7826 	tp->snd_una = th->th_ack;
7827 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7828 	if (IN_RECOVERY(tp->t_flags)) {
7829 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7830 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7831 			tcp_bbr_partialack(tp);
7832 		} else {
7833 			bbr_post_recovery(tp);
7834 		}
7835 	}
7836 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7837 		tp->snd_recover = tp->snd_una;
7838 	}
7839 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7840 		tp->snd_nxt = tp->snd_max;
7841 	}
7842 	if (tp->snd_una == tp->snd_max) {
7843 		/* Nothing left outstanding */
7844 nothing_left:
7845 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7846 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
7847 			bbr->rc_tp->t_acktime = 0;
7848 		if ((sbused(&so->so_snd) == 0) &&
7849 		    (tp->t_flags & TF_SENTFIN)) {
7850 			ourfinisacked = 1;
7851 		}
7852 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7853 		if (bbr->rc_in_persist == 0) {
7854 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7855 		}
7856 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7857 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7858 		/*
7859 		 * We invalidate the last ack here since we
7860 		 * don't want to transfer forward the time
7861 		 * for our sum's calculations.
7862 		 */
7863 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7864 		    (sbavail(&so->so_snd) == 0) &&
7865 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7866 			/*
7867 			 * The socket was gone and the peer sent data, time
7868 			 * to reset him.
7869 			 */
7870 			*ret_val = 1;
7871 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7872 			/* tcp_close will kill the inp pre-log the Reset */
7873 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7874 			tp = tcp_close(tp);
7875 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7876 			BBR_STAT_INC(bbr_dropped_af_data);
7877 			return (1);
7878 		}
7879 		/* Set need output so persist might get set */
7880 		bbr->r_wanted_output = 1;
7881 	}
7882 	if (ofia)
7883 		*ofia = ourfinisacked;
7884 	return (0);
7885 }
7886 
7887 static void
7888 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7889 {
7890 	if (bbr->rc_in_persist == 0) {
7891 		bbr_timer_cancel(bbr, __LINE__, cts);
7892 		bbr->r_ctl.rc_last_delay_val = 0;
7893 		tp->t_rxtshift = 0;
7894 		bbr->rc_in_persist = 1;
7895 		bbr->r_ctl.rc_went_idle_time = cts;
7896 		/* We should be capped when rw went to 0 but just in case */
7897 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7898 		/* Time freezes for the state, so do the accounting now */
7899 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7900 			uint32_t time_in;
7901 
7902 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7903 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7904 				int32_t idx;
7905 
7906 				idx = bbr_state_val(bbr);
7907 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7908 			} else {
7909 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7910 			}
7911 		}
7912 		bbr->r_ctl.rc_bbr_state_time = cts;
7913 	}
7914 }
7915 
7916 static void
7917 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7918 {
7919 	/*
7920 	 * Note that if idle time does not exceed our
7921 	 * threshold, we do nothing continuing the state
7922 	 * transitions we were last walking through.
7923 	 */
7924 	if (idle_time >= bbr_idle_restart_threshold) {
7925 		if (bbr->rc_use_idle_restart) {
7926 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7927 			/*
7928 			 * Set our target using BBR_UNIT, so
7929 			 * we increase at a dramatic rate but
7930 			 * we stop when we get the pipe
7931 			 * full again for our current b/w estimate.
7932 			 */
7933 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7934 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7935 			bbr_set_state_target(bbr, __LINE__);
7936 			/* Now setup our gains to ramp up */
7937 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7938 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7939 			bbr_log_type_statechange(bbr, cts, __LINE__);
7940 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7941 			bbr_substate_change(bbr, cts, __LINE__, 1);
7942 		}
7943 	}
7944 }
7945 
7946 static void
7947 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7948 {
7949 	uint32_t idle_time;
7950 
7951 	if (bbr->rc_in_persist == 0)
7952 		return;
7953 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7954 	bbr->rc_in_persist = 0;
7955 	bbr->rc_hit_state_1 = 0;
7956 	bbr->r_ctl.rc_del_time = cts;
7957 	/*
7958 	 * We invalidate the last ack here since we
7959 	 * don't want to transfer forward the time
7960 	 * for our sum's calculations.
7961 	 */
7962 	if (tcp_in_hpts(bbr->rc_inp)) {
7963 		tcp_hpts_remove(bbr->rc_inp);
7964 		bbr->rc_timer_first = 0;
7965 		bbr->r_ctl.rc_hpts_flags = 0;
7966 		bbr->r_ctl.rc_last_delay_val = 0;
7967 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7968 		bbr->r_agg_early_set = 0;
7969 		bbr->r_ctl.rc_agg_early = 0;
7970 	}
7971 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7972 	if (idle_time >= bbr_rtt_probe_time) {
7973 		/*
7974 		 * This qualifies as a RTT_PROBE session since we drop the
7975 		 * data outstanding to nothing and waited more than
7976 		 * bbr_rtt_probe_time.
7977 		 */
7978 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7979 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7980 	}
7981 	tp->t_rxtshift = 0;
7982 	/*
7983 	 * If in probeBW and we have persisted more than an RTT lets do
7984 	 * special handling.
7985 	 */
7986 	/* Force a time based epoch */
7987 	bbr_set_epoch(bbr, cts, __LINE__);
7988 	/*
7989 	 * Setup the lost so we don't count anything against the guy
7990 	 * we have been stuck with during persists.
7991 	 */
7992 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7993 	/* Time un-freezes for the state */
7994 	bbr->r_ctl.rc_bbr_state_time = cts;
7995 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7996 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7997 		/*
7998 		 * If we are going back to probe-bw
7999 		 * or probe_rtt, we may need to possibly
8000 		 * do a fast restart.
8001 		 */
8002 		bbr_restart_after_idle(bbr, cts, idle_time);
8003 	}
8004 }
8005 
8006 static void
8007 bbr_collapsed_window(struct tcp_bbr *bbr)
8008 {
8009 	/*
8010 	 * Now we must walk the
8011 	 * send map and divide the
8012 	 * ones left stranded. These
8013 	 * guys can't cause us to abort
8014 	 * the connection and are really
8015 	 * "unsent". However if a buggy
8016 	 * client actually did keep some
8017 	 * of the data i.e. collapsed the win
8018 	 * and refused to ack and then opened
8019 	 * the win and acked that data. We would
8020 	 * get into an ack war, the simplier
8021 	 * method then of just pretending we
8022 	 * did not send those segments something
8023 	 * won't work.
8024 	 */
8025 	struct bbr_sendmap *rsm, *nrsm;
8026 	tcp_seq max_seq;
8027 	uint32_t maxseg;
8028 	int can_split = 0;
8029 	int fnd = 0;
8030 
8031 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8032 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8033 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8034 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8035 		/* Find the first seq past or at maxseq */
8036 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8037 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8038 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8039 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8040 			fnd = 1;
8041 			break;
8042 		}
8043 	}
8044 	bbr->rc_has_collapsed = 0;
8045 	if (!fnd) {
8046 		/* Nothing to do strange */
8047 		return;
8048 	}
8049 	/*
8050 	 * Now can we split?
8051 	 *
8052 	 * We don't want to split if splitting
8053 	 * would generate too many small segments
8054 	 * less we let an attacker fragment our
8055 	 * send_map and leave us out of memory.
8056 	 */
8057 	if ((max_seq != rsm->r_start) &&
8058 	    (max_seq != rsm->r_end)){
8059 		/* can we split? */
8060 		int res1, res2;
8061 
8062 		res1 = max_seq - rsm->r_start;
8063 		res2 = rsm->r_end - max_seq;
8064 		if ((res1 >= (maxseg/8)) &&
8065 		    (res2 >= (maxseg/8))) {
8066 			/* No small pieces here */
8067 			can_split = 1;
8068 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8069 			/* We are under the limit */
8070 			can_split = 1;
8071 		}
8072 	}
8073 	/* Ok do we need to split this rsm? */
8074 	if (max_seq == rsm->r_start) {
8075 		/* It's this guy no split required */
8076 		nrsm = rsm;
8077 	} else if (max_seq == rsm->r_end) {
8078 		/* It's the next one no split required. */
8079 		nrsm = TAILQ_NEXT(rsm, r_next);
8080 		if (nrsm == NULL) {
8081 			/* Huh? */
8082 			return;
8083 		}
8084 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8085 		/* yep we need to split it */
8086 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8087 		if (nrsm == NULL) {
8088 			/* failed XXXrrs what can we do mark the whole? */
8089 			nrsm = rsm;
8090 			goto no_split;
8091 		}
8092 		/* Clone it */
8093 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8094 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8095 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8096 		if (rsm->r_in_tmap) {
8097 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8098 			nrsm->r_in_tmap = 1;
8099 		}
8100 	} else {
8101 		/*
8102 		 * Split not allowed just start here just
8103 		 * use this guy.
8104 		 */
8105 		nrsm = rsm;
8106 	}
8107 no_split:
8108 	BBR_STAT_INC(bbr_collapsed_win);
8109 	/* reuse fnd as a count */
8110 	fnd = 0;
8111 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8112 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8113 		fnd++;
8114 		bbr->rc_has_collapsed = 1;
8115 	}
8116 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8117 }
8118 
8119 static void
8120 bbr_un_collapse_window(struct tcp_bbr *bbr)
8121 {
8122 	struct bbr_sendmap *rsm;
8123 	int cleared = 0;
8124 
8125 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8126 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8127 			/* Clear the flag */
8128 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8129 			cleared++;
8130 		} else
8131 			break;
8132 	}
8133 	bbr_log_type_rwnd_collapse(bbr,
8134 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8135 	bbr->rc_has_collapsed = 0;
8136 }
8137 
8138 /*
8139  * Return value of 1, the TCB is unlocked and most
8140  * likely gone, return value of 0, the TCB is still
8141  * locked.
8142  */
8143 static int
8144 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8145     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8146     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8147 {
8148 	/*
8149 	 * Update window information. Don't look at window if no ACK: TAC's
8150 	 * send garbage on first SYN.
8151 	 */
8152 	uint16_t nsegs;
8153 	int32_t tfo_syn;
8154 	struct tcp_bbr *bbr;
8155 
8156 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8157 	INP_WLOCK_ASSERT(tp->t_inpcb);
8158 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8159 	if ((thflags & TH_ACK) &&
8160 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8161 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8162 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8163 		/* keep track of pure window updates */
8164 		if (tlen == 0 &&
8165 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8166 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8167 		tp->snd_wnd = tiwin;
8168 		tp->snd_wl1 = th->th_seq;
8169 		tp->snd_wl2 = th->th_ack;
8170 		if (tp->snd_wnd > tp->max_sndwnd)
8171 			tp->max_sndwnd = tp->snd_wnd;
8172 		bbr->r_wanted_output = 1;
8173 	} else if (thflags & TH_ACK) {
8174 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8175 			tp->snd_wnd = tiwin;
8176 			tp->snd_wl1 = th->th_seq;
8177 			tp->snd_wl2 = th->th_ack;
8178 		}
8179 	}
8180 	if (tp->snd_wnd < ctf_outstanding(tp))
8181 		/* The peer collapsed its window on us */
8182 		bbr_collapsed_window(bbr);
8183  	else if (bbr->rc_has_collapsed)
8184 		bbr_un_collapse_window(bbr);
8185 	/* Was persist timer active and now we have window space? */
8186 	if ((bbr->rc_in_persist != 0) &&
8187 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8188 				bbr_minseg(bbr)))) {
8189 		/*
8190 		 * Make the rate persist at end of persist mode if idle long
8191 		 * enough
8192 		 */
8193 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8194 
8195 		/* Make sure we output to start the timer */
8196 		bbr->r_wanted_output = 1;
8197 	}
8198 	/* Do we need to enter persist? */
8199 	if ((bbr->rc_in_persist == 0) &&
8200 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8201 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8202 	    (tp->snd_max == tp->snd_una) &&
8203 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8204 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8205 		/* No send window.. we must enter persist */
8206 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8207 	}
8208 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8209 		m_freem(m);
8210 		return (0);
8211 	}
8212 	/*
8213 	 * We don't support urgent data but
8214 	 * drag along the up just to make sure
8215 	 * if there is a stack switch no one
8216 	 * is surprised.
8217 	 */
8218 	tp->rcv_up = tp->rcv_nxt;
8219 	INP_WLOCK_ASSERT(tp->t_inpcb);
8220 
8221 	/*
8222 	 * Process the segment text, merging it into the TCP sequencing
8223 	 * queue, and arranging for acknowledgment of receipt if necessary.
8224 	 * This process logically involves adjusting tp->rcv_wnd as data is
8225 	 * presented to the user (this happens in tcp_usrreq.c, case
8226 	 * PRU_RCVD).  If a FIN has already been received on this connection
8227 	 * then we just ignore the text.
8228 	 */
8229 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8230 		   IS_FASTOPEN(tp->t_flags));
8231 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8232 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8233 		tcp_seq save_start = th->th_seq;
8234 		tcp_seq save_rnxt  = tp->rcv_nxt;
8235 		int     save_tlen  = tlen;
8236 
8237 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8238 		/*
8239 		 * Insert segment which includes th into TCP reassembly
8240 		 * queue with control block tp.  Set thflags to whether
8241 		 * reassembly now includes a segment with FIN.  This handles
8242 		 * the common case inline (segment is the next to be
8243 		 * received on an established connection, and the queue is
8244 		 * empty), avoiding linkage into and removal from the queue
8245 		 * and repetition of various conversions. Set DELACK for
8246 		 * segments received in order, but ack immediately when
8247 		 * segments are out of order (so fast retransmit can work).
8248 		 */
8249 		if (th->th_seq == tp->rcv_nxt &&
8250 		    SEGQ_EMPTY(tp) &&
8251 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8252 		    tfo_syn)) {
8253 #ifdef NETFLIX_SB_LIMITS
8254 			u_int mcnt, appended;
8255 
8256 			if (so->so_rcv.sb_shlim) {
8257 				mcnt = m_memcnt(m);
8258 				appended = 0;
8259 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8260 				    CFO_NOSLEEP, NULL) == false) {
8261 					counter_u64_add(tcp_sb_shlim_fails, 1);
8262 					m_freem(m);
8263 					return (0);
8264 				}
8265 			}
8266 
8267 #endif
8268 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8269 				bbr->bbr_segs_rcvd += max(1, nsegs);
8270 				tp->t_flags |= TF_DELACK;
8271 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8272 			} else {
8273 				bbr->r_wanted_output = 1;
8274 				tp->t_flags |= TF_ACKNOW;
8275 			}
8276 			tp->rcv_nxt += tlen;
8277 			if (tlen &&
8278 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8279 			    (tp->t_fbyte_in == 0)) {
8280 				tp->t_fbyte_in = ticks;
8281 				if (tp->t_fbyte_in == 0)
8282 					tp->t_fbyte_in = 1;
8283 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8284 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8285 			}
8286 			thflags = th->th_flags & TH_FIN;
8287 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8288 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8289 			SOCKBUF_LOCK(&so->so_rcv);
8290 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8291 				m_freem(m);
8292 			else
8293 #ifdef NETFLIX_SB_LIMITS
8294 				appended =
8295 #endif
8296 					sbappendstream_locked(&so->so_rcv, m, 0);
8297 			/* NB: sorwakeup_locked() does an implicit unlock. */
8298 			sorwakeup_locked(so);
8299 #ifdef NETFLIX_SB_LIMITS
8300 			if (so->so_rcv.sb_shlim && appended != mcnt)
8301 				counter_fo_release(so->so_rcv.sb_shlim,
8302 				    mcnt - appended);
8303 #endif
8304 
8305 		} else {
8306 			/*
8307 			 * XXX: Due to the header drop above "th" is
8308 			 * theoretically invalid by now.  Fortunately
8309 			 * m_adj() doesn't actually frees any mbufs when
8310 			 * trimming from the head.
8311 			 */
8312 			tcp_seq temp = save_start;
8313 
8314 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8315 			tp->t_flags |= TF_ACKNOW;
8316 			if (tp->t_flags & TF_WAKESOR) {
8317 				tp->t_flags &= ~TF_WAKESOR;
8318 				/* NB: sorwakeup_locked() does an implicit unlock. */
8319 				sorwakeup_locked(so);
8320 			}
8321 		}
8322 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8323 		    (save_tlen > 0) &&
8324 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8325 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8326 				/*
8327 				 * DSACK actually handled in the fastpath
8328 				 * above.
8329 				 */
8330 				tcp_update_sack_list(tp, save_start,
8331 				    save_start + save_tlen);
8332 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8333 				if ((tp->rcv_numsacks >= 1) &&
8334 				    (tp->sackblks[0].end == save_start)) {
8335 					/*
8336 					 * Partial overlap, recorded at todrop
8337 					 * above.
8338 					 */
8339 					tcp_update_sack_list(tp,
8340 					    tp->sackblks[0].start,
8341 					    tp->sackblks[0].end);
8342 				} else {
8343 					tcp_update_dsack_list(tp, save_start,
8344 					    save_start + save_tlen);
8345 				}
8346 			} else if (tlen >= save_tlen) {
8347 				/* Update of sackblks. */
8348 				tcp_update_dsack_list(tp, save_start,
8349 				    save_start + save_tlen);
8350 			} else if (tlen > 0) {
8351 				tcp_update_dsack_list(tp, save_start,
8352 				    save_start + tlen);
8353 			}
8354 		}
8355 	} else {
8356 		m_freem(m);
8357 		thflags &= ~TH_FIN;
8358 	}
8359 
8360 	/*
8361 	 * If FIN is received ACK the FIN and let the user know that the
8362 	 * connection is closing.
8363 	 */
8364 	if (thflags & TH_FIN) {
8365 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8366 			/* The socket upcall is handled by socantrcvmore. */
8367 			socantrcvmore(so);
8368 			/*
8369 			 * If connection is half-synchronized (ie NEEDSYN
8370 			 * flag on) then delay ACK, so it may be piggybacked
8371 			 * when SYN is sent. Otherwise, since we received a
8372 			 * FIN then no more input can be expected, send ACK
8373 			 * now.
8374 			 */
8375 			if (tp->t_flags & TF_NEEDSYN) {
8376 				tp->t_flags |= TF_DELACK;
8377 				bbr_timer_cancel(bbr,
8378 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8379 			} else {
8380 				tp->t_flags |= TF_ACKNOW;
8381 			}
8382 			tp->rcv_nxt++;
8383 		}
8384 		switch (tp->t_state) {
8385 			/*
8386 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8387 			 * CLOSE_WAIT state.
8388 			 */
8389 		case TCPS_SYN_RECEIVED:
8390 			tp->t_starttime = ticks;
8391 			/* FALLTHROUGH */
8392 		case TCPS_ESTABLISHED:
8393 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8394 			break;
8395 
8396 			/*
8397 			 * If still in FIN_WAIT_1 STATE FIN has not been
8398 			 * acked so enter the CLOSING state.
8399 			 */
8400 		case TCPS_FIN_WAIT_1:
8401 			tcp_state_change(tp, TCPS_CLOSING);
8402 			break;
8403 
8404 			/*
8405 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8406 			 * starting the time-wait timer, turning off the
8407 			 * other standard timers.
8408 			 */
8409 		case TCPS_FIN_WAIT_2:
8410 			bbr->rc_timer_first = 1;
8411 			bbr_timer_cancel(bbr,
8412 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8413 			INP_WLOCK_ASSERT(tp->t_inpcb);
8414 			tcp_twstart(tp);
8415 			return (1);
8416 		}
8417 	}
8418 	/*
8419 	 * Return any desired output.
8420 	 */
8421 	if ((tp->t_flags & TF_ACKNOW) ||
8422 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8423 		bbr->r_wanted_output = 1;
8424 	}
8425 	INP_WLOCK_ASSERT(tp->t_inpcb);
8426 	return (0);
8427 }
8428 
8429 /*
8430  * Here nothing is really faster, its just that we
8431  * have broken out the fast-data path also just like
8432  * the fast-ack. Return 1 if we processed the packet
8433  * return 0 if you need to take the "slow-path".
8434  */
8435 static int
8436 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8437     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8438     uint32_t tiwin, int32_t nxt_pkt)
8439 {
8440 	uint16_t nsegs;
8441 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8442 	struct tcp_bbr *bbr;
8443 #ifdef NETFLIX_SB_LIMITS
8444 	u_int mcnt, appended;
8445 #endif
8446 #ifdef TCPDEBUG
8447 	/*
8448 	 * The size of tcp_saveipgen must be the size of the max ip header,
8449 	 * now IPv6.
8450 	 */
8451 	u_char tcp_saveipgen[IP6_HDR_LEN];
8452 	struct tcphdr tcp_savetcp;
8453 	short ostate = 0;
8454 
8455 #endif
8456 	/* On the hpts and we would have called output */
8457 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8458 
8459 	/*
8460 	 * If last ACK falls within this segment's sequence numbers, record
8461 	 * the timestamp. NOTE that the test is modified according to the
8462 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8463 	 */
8464 	if (bbr->r_ctl.rc_resend != NULL) {
8465 		return (0);
8466 	}
8467 	if (tiwin && tiwin != tp->snd_wnd) {
8468 		return (0);
8469 	}
8470 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8471 		return (0);
8472 	}
8473 	if (__predict_false((to->to_flags & TOF_TS) &&
8474 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8475 		return (0);
8476 	}
8477 	if (__predict_false((th->th_ack != tp->snd_una))) {
8478 		return (0);
8479 	}
8480 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8481 		return (0);
8482 	}
8483 	if ((to->to_flags & TOF_TS) != 0 &&
8484 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8485 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8486 		tp->ts_recent = to->to_tsval;
8487 	}
8488 	/*
8489 	 * This is a pure, in-sequence data packet with nothing on the
8490 	 * reassembly queue and we have enough buffer space to take it.
8491 	 */
8492 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8493 
8494 #ifdef NETFLIX_SB_LIMITS
8495 	if (so->so_rcv.sb_shlim) {
8496 		mcnt = m_memcnt(m);
8497 		appended = 0;
8498 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8499 		    CFO_NOSLEEP, NULL) == false) {
8500 			counter_u64_add(tcp_sb_shlim_fails, 1);
8501 			m_freem(m);
8502 			return (1);
8503 		}
8504 	}
8505 #endif
8506 	/* Clean receiver SACK report if present */
8507 	if (tp->rcv_numsacks)
8508 		tcp_clean_sackreport(tp);
8509 	KMOD_TCPSTAT_INC(tcps_preddat);
8510 	tp->rcv_nxt += tlen;
8511 	if (tlen &&
8512 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8513 	    (tp->t_fbyte_in == 0)) {
8514 		tp->t_fbyte_in = ticks;
8515 		if (tp->t_fbyte_in == 0)
8516 			tp->t_fbyte_in = 1;
8517 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8518 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8519 	}
8520 	/*
8521 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8522 	 */
8523 	tp->snd_wl1 = th->th_seq;
8524 	/*
8525 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8526 	 */
8527 	tp->rcv_up = tp->rcv_nxt;
8528 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8529 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8530 #ifdef TCPDEBUG
8531 	if (so->so_options & SO_DEBUG)
8532 		tcp_trace(TA_INPUT, ostate, tp,
8533 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8534 #endif
8535 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8536 
8537 	/* Add data to socket buffer. */
8538 	SOCKBUF_LOCK(&so->so_rcv);
8539 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8540 		m_freem(m);
8541 	} else {
8542 		/*
8543 		 * Set new socket buffer size. Give up when limit is
8544 		 * reached.
8545 		 */
8546 		if (newsize)
8547 			if (!sbreserve_locked(&so->so_rcv,
8548 			    newsize, so, NULL))
8549 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8550 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8551 
8552 #ifdef NETFLIX_SB_LIMITS
8553 		appended =
8554 #endif
8555 			sbappendstream_locked(&so->so_rcv, m, 0);
8556 		ctf_calc_rwin(so, tp);
8557 	}
8558 	/* NB: sorwakeup_locked() does an implicit unlock. */
8559 	sorwakeup_locked(so);
8560 #ifdef NETFLIX_SB_LIMITS
8561 	if (so->so_rcv.sb_shlim && mcnt != appended)
8562 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8563 #endif
8564 	if (DELAY_ACK(tp, bbr, nsegs)) {
8565 		bbr->bbr_segs_rcvd += max(1, nsegs);
8566 		tp->t_flags |= TF_DELACK;
8567 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8568 	} else {
8569 		bbr->r_wanted_output = 1;
8570 		tp->t_flags |= TF_ACKNOW;
8571 	}
8572 	return (1);
8573 }
8574 
8575 /*
8576  * This subfunction is used to try to highly optimize the
8577  * fast path. We again allow window updates that are
8578  * in sequence to remain in the fast-path. We also add
8579  * in the __predict's to attempt to help the compiler.
8580  * Note that if we return a 0, then we can *not* process
8581  * it and the caller should push the packet into the
8582  * slow-path. If we return 1, then all is well and
8583  * the packet is fully processed.
8584  */
8585 static int
8586 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8587     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8588     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8589 {
8590 	int32_t acked;
8591 	uint16_t nsegs;
8592 	uint32_t sack_changed;
8593 #ifdef TCPDEBUG
8594 	/*
8595 	 * The size of tcp_saveipgen must be the size of the max ip header,
8596 	 * now IPv6.
8597 	 */
8598 	u_char tcp_saveipgen[IP6_HDR_LEN];
8599 	struct tcphdr tcp_savetcp;
8600 	short ostate = 0;
8601 
8602 #endif
8603 	uint32_t prev_acked = 0;
8604 	struct tcp_bbr *bbr;
8605 
8606 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8607 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8608 		return (0);
8609 	}
8610 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8611 		/* Above what we have sent? */
8612 		return (0);
8613 	}
8614 	if (__predict_false(tiwin == 0)) {
8615 		/* zero window */
8616 		return (0);
8617 	}
8618 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8619 		/* We need a SYN or a FIN, unlikely.. */
8620 		return (0);
8621 	}
8622 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8623 		/* Timestamp is behind .. old ack with seq wrap? */
8624 		return (0);
8625 	}
8626 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8627 		/* Still recovering */
8628 		return (0);
8629 	}
8630 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8631 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8632 		/* We are retransmitting */
8633 		return (0);
8634 	}
8635 	if (__predict_false(bbr->rc_in_persist != 0)) {
8636 		/* In persist mode */
8637 		return (0);
8638 	}
8639 	if (bbr->r_ctl.rc_sacked) {
8640 		/* We have sack holes on our scoreboard */
8641 		return (0);
8642 	}
8643 	/* Ok if we reach here, we can process a fast-ack */
8644 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8645 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8646 	/*
8647 	 * We never detect loss in fast ack [we can't
8648 	 * have a sack and can't be in recovery so
8649 	 * we always pass 0 (nothing detected)].
8650 	 */
8651 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8652 	/* Did the window get updated? */
8653 	if (tiwin != tp->snd_wnd) {
8654 		tp->snd_wnd = tiwin;
8655 		tp->snd_wl1 = th->th_seq;
8656 		if (tp->snd_wnd > tp->max_sndwnd)
8657 			tp->max_sndwnd = tp->snd_wnd;
8658 	}
8659 	/* Do we need to exit persists? */
8660 	if ((bbr->rc_in_persist != 0) &&
8661 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8662 			       bbr_minseg(bbr)))) {
8663 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8664 		bbr->r_wanted_output = 1;
8665 	}
8666 	/* Do we need to enter persists? */
8667 	if ((bbr->rc_in_persist == 0) &&
8668 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8669 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8670 	    (tp->snd_max == tp->snd_una) &&
8671 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8672 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8673 		/* No send window.. we must enter persist */
8674 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8675 	}
8676 	/*
8677 	 * If last ACK falls within this segment's sequence numbers, record
8678 	 * the timestamp. NOTE that the test is modified according to the
8679 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8680 	 */
8681 	if ((to->to_flags & TOF_TS) != 0 &&
8682 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8683 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8684 		tp->ts_recent = to->to_tsval;
8685 	}
8686 	/*
8687 	 * This is a pure ack for outstanding data.
8688 	 */
8689 	KMOD_TCPSTAT_INC(tcps_predack);
8690 
8691 	/*
8692 	 * "bad retransmit" recovery.
8693 	 */
8694 	if (tp->t_flags & TF_PREVVALID) {
8695 		tp->t_flags &= ~TF_PREVVALID;
8696 		if (tp->t_rxtshift == 1 &&
8697 		    (int)(ticks - tp->t_badrxtwin) < 0)
8698 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8699 	}
8700 	/*
8701 	 * Recalculate the transmit timer / rtt.
8702 	 *
8703 	 * Some boxes send broken timestamp replies during the SYN+ACK
8704 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8705 	 * and blow up the retransmit timer.
8706 	 */
8707 	acked = BYTES_THIS_ACK(tp, th);
8708 
8709 #ifdef TCP_HHOOK
8710 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8711 	hhook_run_tcp_est_in(tp, th, to);
8712 #endif
8713 
8714 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8715 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8716 	sbdrop(&so->so_snd, acked);
8717 
8718 	if (SEQ_GT(th->th_ack, tp->snd_una))
8719 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8720 	tp->snd_una = th->th_ack;
8721 	if (tp->snd_wnd < ctf_outstanding(tp))
8722 		/* The peer collapsed its window on us */
8723 		bbr_collapsed_window(bbr);
8724 	else if (bbr->rc_has_collapsed)
8725 		bbr_un_collapse_window(bbr);
8726 
8727 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8728 		tp->snd_recover = tp->snd_una;
8729 	}
8730 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8731 	/*
8732 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8733 	 */
8734 	tp->snd_wl2 = th->th_ack;
8735 	m_freem(m);
8736 	/*
8737 	 * If all outstanding data are acked, stop retransmit timer,
8738 	 * otherwise restart timer using current (possibly backed-off)
8739 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8740 	 * If data are ready to send, let tcp_output decide between more
8741 	 * output or persist.
8742 	 */
8743 #ifdef TCPDEBUG
8744 	if (so->so_options & SO_DEBUG)
8745 		tcp_trace(TA_INPUT, ostate, tp,
8746 		    (void *)tcp_saveipgen,
8747 		    &tcp_savetcp, 0);
8748 #endif
8749 	/* Wake up the socket if we have room to write more */
8750 	sowwakeup(so);
8751 	if (tp->snd_una == tp->snd_max) {
8752 		/* Nothing left outstanding */
8753 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8754 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8755 			bbr->rc_tp->t_acktime = 0;
8756 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8757 		if (bbr->rc_in_persist == 0) {
8758 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8759 		}
8760 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8761 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8762 		/*
8763 		 * We invalidate the last ack here since we
8764 		 * don't want to transfer forward the time
8765 		 * for our sum's calculations.
8766 		 */
8767 		bbr->r_wanted_output = 1;
8768 	}
8769 	if (sbavail(&so->so_snd)) {
8770 		bbr->r_wanted_output = 1;
8771 	}
8772 	return (1);
8773 }
8774 
8775 /*
8776  * Return value of 1, the TCB is unlocked and most
8777  * likely gone, return value of 0, the TCB is still
8778  * locked.
8779  */
8780 static int
8781 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8782     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8783     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8784 {
8785 	int32_t todrop;
8786 	int32_t ourfinisacked = 0;
8787 	struct tcp_bbr *bbr;
8788 	int32_t ret_val = 0;
8789 
8790 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8791 	ctf_calc_rwin(so, tp);
8792 	/*
8793 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8794 	 * SYN, drop the input. if seg contains a RST, then drop the
8795 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8796 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8797 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8798 	 * not support ECN so we will not say we are capable. if SYN has
8799 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8800 	 * segment to be acked (eventually) continue processing rest of
8801 	 * data/controls, beginning with URG
8802 	 */
8803 	if ((thflags & TH_ACK) &&
8804 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8805 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8806 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8807 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8808 		return (1);
8809 	}
8810 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8811 		TCP_PROBE5(connect__refused, NULL, tp,
8812 		    mtod(m, const char *), tp, th);
8813 		tp = tcp_drop(tp, ECONNREFUSED);
8814 		ctf_do_drop(m, tp);
8815 		return (1);
8816 	}
8817 	if (thflags & TH_RST) {
8818 		ctf_do_drop(m, tp);
8819 		return (1);
8820 	}
8821 	if (!(thflags & TH_SYN)) {
8822 		ctf_do_drop(m, tp);
8823 		return (1);
8824 	}
8825 	tp->irs = th->th_seq;
8826 	tcp_rcvseqinit(tp);
8827 	if (thflags & TH_ACK) {
8828 		int tfo_partial = 0;
8829 
8830 		KMOD_TCPSTAT_INC(tcps_connects);
8831 		soisconnected(so);
8832 #ifdef MAC
8833 		mac_socketpeer_set_from_mbuf(m, so);
8834 #endif
8835 		/* Do window scaling on this connection? */
8836 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8837 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8838 			tp->rcv_scale = tp->request_r_scale;
8839 		}
8840 		tp->rcv_adv += min(tp->rcv_wnd,
8841 		    TCP_MAXWIN << tp->rcv_scale);
8842 		/*
8843 		 * If not all the data that was sent in the TFO SYN
8844 		 * has been acked, resend the remainder right away.
8845 		 */
8846 		if (IS_FASTOPEN(tp->t_flags) &&
8847 		    (tp->snd_una != tp->snd_max)) {
8848 			tp->snd_nxt = th->th_ack;
8849 			tfo_partial = 1;
8850 		}
8851 		/*
8852 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8853 		 * will be turned on later.
8854 		 */
8855 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8856 			bbr->bbr_segs_rcvd += 1;
8857 			tp->t_flags |= TF_DELACK;
8858 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8859 		} else {
8860 			bbr->r_wanted_output = 1;
8861 			tp->t_flags |= TF_ACKNOW;
8862 		}
8863 		if (SEQ_GT(th->th_ack, tp->iss)) {
8864 			/*
8865 			 * The SYN is acked
8866 			 * handle it specially.
8867 			 */
8868 			bbr_log_syn(tp, to);
8869 		}
8870 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8871 			/*
8872 			 * We advance snd_una for the
8873 			 * fast open case. If th_ack is
8874 			 * acknowledging data beyond
8875 			 * snd_una we can't just call
8876 			 * ack-processing since the
8877 			 * data stream in our send-map
8878 			 * will start at snd_una + 1 (one
8879 			 * beyond the SYN). If its just
8880 			 * equal we don't need to do that
8881 			 * and there is no send_map.
8882 			 */
8883 			tp->snd_una++;
8884 		}
8885 		/*
8886 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8887 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8888 		 */
8889 		tp->t_starttime = ticks;
8890 		if (tp->t_flags & TF_NEEDFIN) {
8891 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8892 			tp->t_flags &= ~TF_NEEDFIN;
8893 			thflags &= ~TH_SYN;
8894 		} else {
8895 			tcp_state_change(tp, TCPS_ESTABLISHED);
8896 			TCP_PROBE5(connect__established, NULL, tp,
8897 			    mtod(m, const char *), tp, th);
8898 			cc_conn_init(tp);
8899 		}
8900 	} else {
8901 		/*
8902 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8903 		 * open.  If segment contains CC option and there is a
8904 		 * cached CC, apply TAO test. If it succeeds, connection is *
8905 		 * half-synchronized. Otherwise, do 3-way handshake:
8906 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8907 		 * there was no CC option, clear cached CC value.
8908 		 */
8909 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
8910 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8911 	}
8912 	INP_WLOCK_ASSERT(tp->t_inpcb);
8913 	/*
8914 	 * Advance th->th_seq to correspond to first data byte. If data,
8915 	 * trim to stay within window, dropping FIN if necessary.
8916 	 */
8917 	th->th_seq++;
8918 	if (tlen > tp->rcv_wnd) {
8919 		todrop = tlen - tp->rcv_wnd;
8920 		m_adj(m, -todrop);
8921 		tlen = tp->rcv_wnd;
8922 		thflags &= ~TH_FIN;
8923 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8924 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8925 	}
8926 	tp->snd_wl1 = th->th_seq - 1;
8927 	tp->rcv_up = th->th_seq;
8928 	/*
8929 	 * Client side of transaction: already sent SYN and data. If the
8930 	 * remote host used T/TCP to validate the SYN, our data will be
8931 	 * ACK'd; if so, enter normal data segment processing in the middle
8932 	 * of step 5, ack processing. Otherwise, goto step 6.
8933 	 */
8934 	if (thflags & TH_ACK) {
8935 		if ((to->to_flags & TOF_TS) != 0) {
8936 			uint32_t t, rtt;
8937 
8938 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8939 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8940 				rtt = t - to->to_tsecr;
8941 				if (rtt == 0) {
8942 					rtt = 1;
8943 				}
8944 				rtt *= MS_IN_USEC;
8945 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8946 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8947 						       rtt, bbr->r_ctl.rc_rcvtime);
8948 			}
8949 		}
8950 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8951 			return (ret_val);
8952 		/* We may have changed to FIN_WAIT_1 above */
8953 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8954 			/*
8955 			 * In FIN_WAIT_1 STATE in addition to the processing
8956 			 * for the ESTABLISHED state if our FIN is now
8957 			 * acknowledged then enter FIN_WAIT_2.
8958 			 */
8959 			if (ourfinisacked) {
8960 				/*
8961 				 * If we can't receive any more data, then
8962 				 * closing user can proceed. Starting the
8963 				 * timer is contrary to the specification,
8964 				 * but if we don't get a FIN we'll hang
8965 				 * forever.
8966 				 *
8967 				 * XXXjl: we should release the tp also, and
8968 				 * use a compressed state.
8969 				 */
8970 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8971 					soisdisconnected(so);
8972 					tcp_timer_activate(tp, TT_2MSL,
8973 					    (tcp_fast_finwait2_recycle ?
8974 					    tcp_finwait2_timeout :
8975 					    TP_MAXIDLE(tp)));
8976 				}
8977 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8978 			}
8979 		}
8980 	}
8981 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8982 	    tiwin, thflags, nxt_pkt));
8983 }
8984 
8985 /*
8986  * Return value of 1, the TCB is unlocked and most
8987  * likely gone, return value of 0, the TCB is still
8988  * locked.
8989  */
8990 static int
8991 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8992 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8993 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8994 {
8995 	int32_t ourfinisacked = 0;
8996 	int32_t ret_val;
8997 	struct tcp_bbr *bbr;
8998 
8999 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9000 	ctf_calc_rwin(so, tp);
9001 	if ((thflags & TH_ACK) &&
9002 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9003 	     SEQ_GT(th->th_ack, tp->snd_max))) {
9004 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9005 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9006 		return (1);
9007 	}
9008 	if (IS_FASTOPEN(tp->t_flags)) {
9009 		/*
9010 		 * When a TFO connection is in SYN_RECEIVED, the only valid
9011 		 * packets are the initial SYN, a retransmit/copy of the
9012 		 * initial SYN (possibly with a subset of the original
9013 		 * data), a valid ACK, a FIN, or a RST.
9014 		 */
9015 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9016 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9017 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9018 			return (1);
9019 		} else if (thflags & TH_SYN) {
9020 			/* non-initial SYN is ignored */
9021 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9022 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9023 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9024 				ctf_do_drop(m, NULL);
9025 				return (0);
9026 			}
9027 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9028 			ctf_do_drop(m, NULL);
9029 			return (0);
9030 		}
9031 	}
9032 	if ((thflags & TH_RST) ||
9033 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9034 		return (ctf_process_rst(m, th, so, tp));
9035 	/*
9036 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9037 	 * it's less than ts_recent, drop it.
9038 	 */
9039 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9040 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9041 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9042 			return (ret_val);
9043 	}
9044 	/*
9045 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9046 	 * this connection before trimming the data to fit the receive
9047 	 * window.  Check the sequence number versus IRS since we know the
9048 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9049 	 * "LAND" DoS attack.
9050 	 */
9051 	if (SEQ_LT(th->th_seq, tp->irs)) {
9052 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9053 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9054 		return (1);
9055 	}
9056 	INP_WLOCK_ASSERT(tp->t_inpcb);
9057 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9058 		return (ret_val);
9059 	}
9060 	/*
9061 	 * If last ACK falls within this segment's sequence numbers, record
9062 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9063 	 * from the latest proposal of the tcplw@cray.com list (Braden
9064 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9065 	 * with our earlier PAWS tests, so this check should be solely
9066 	 * predicated on the sequence space of this segment. 3) That we
9067 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9068 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9069 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9070 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9071 	 * p.869. In such cases, we can still calculate the RTT correctly
9072 	 * when RCV.NXT == Last.ACK.Sent.
9073 	 */
9074 	if ((to->to_flags & TOF_TS) != 0 &&
9075 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9076 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9077 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9078 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9079 		tp->ts_recent = to->to_tsval;
9080 	}
9081 	tp->snd_wnd = tiwin;
9082 	/*
9083 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9084 	 * is on (half-synchronized state), then queue data for later
9085 	 * processing; else drop segment and return.
9086 	 */
9087 	if ((thflags & TH_ACK) == 0) {
9088 		if (IS_FASTOPEN(tp->t_flags)) {
9089 			cc_conn_init(tp);
9090 		}
9091 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9092 					 tiwin, thflags, nxt_pkt));
9093 	}
9094 	KMOD_TCPSTAT_INC(tcps_connects);
9095 	soisconnected(so);
9096 	/* Do window scaling? */
9097 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9098 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9099 		tp->rcv_scale = tp->request_r_scale;
9100 	}
9101 	/*
9102 	 * ok for the first time in lets see if we can use the ts to figure
9103 	 * out what the initial RTT was.
9104 	 */
9105 	if ((to->to_flags & TOF_TS) != 0) {
9106 		uint32_t t, rtt;
9107 
9108 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9109 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9110 			rtt = t - to->to_tsecr;
9111 			if (rtt == 0) {
9112 				rtt = 1;
9113 			}
9114 			rtt *= MS_IN_USEC;
9115 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9116 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9117 		}
9118 	}
9119 	/* Drop off any SYN in the send map (probably not there)  */
9120 	if (thflags & TH_ACK)
9121 		bbr_log_syn(tp, to);
9122 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9123 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9124 		tp->t_tfo_pending = NULL;
9125 	}
9126 	/*
9127 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9128 	 * FIN-WAIT-1
9129 	 */
9130 	tp->t_starttime = ticks;
9131 	if (tp->t_flags & TF_NEEDFIN) {
9132 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9133 		tp->t_flags &= ~TF_NEEDFIN;
9134 	} else {
9135 		tcp_state_change(tp, TCPS_ESTABLISHED);
9136 		TCP_PROBE5(accept__established, NULL, tp,
9137 			   mtod(m, const char *), tp, th);
9138 		/*
9139 		 * TFO connections call cc_conn_init() during SYN
9140 		 * processing.  Calling it again here for such connections
9141 		 * is not harmless as it would undo the snd_cwnd reduction
9142 		 * that occurs when a TFO SYN|ACK is retransmitted.
9143 		 */
9144 		if (!IS_FASTOPEN(tp->t_flags))
9145 			cc_conn_init(tp);
9146 	}
9147 	/*
9148 	 * Account for the ACK of our SYN prior to
9149 	 * regular ACK processing below, except for
9150 	 * simultaneous SYN, which is handled later.
9151 	 */
9152 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9153 		tp->snd_una++;
9154 	/*
9155 	 * If segment contains data or ACK, will call tcp_reass() later; if
9156 	 * not, do so now to pass queued data to user.
9157 	 */
9158 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9159 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9160 			(struct mbuf *)0);
9161 		if (tp->t_flags & TF_WAKESOR) {
9162 			tp->t_flags &= ~TF_WAKESOR;
9163 			/* NB: sorwakeup_locked() does an implicit unlock. */
9164 			sorwakeup_locked(so);
9165 		}
9166 	}
9167 	tp->snd_wl1 = th->th_seq - 1;
9168 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9169 		return (ret_val);
9170 	}
9171 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9172 		/* We could have went to FIN_WAIT_1 (or EST) above */
9173 		/*
9174 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9175 		 * ESTABLISHED state if our FIN is now acknowledged then
9176 		 * enter FIN_WAIT_2.
9177 		 */
9178 		if (ourfinisacked) {
9179 			/*
9180 			 * If we can't receive any more data, then closing
9181 			 * user can proceed. Starting the timer is contrary
9182 			 * to the specification, but if we don't get a FIN
9183 			 * we'll hang forever.
9184 			 *
9185 			 * XXXjl: we should release the tp also, and use a
9186 			 * compressed state.
9187 			 */
9188 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9189 				soisdisconnected(so);
9190 				tcp_timer_activate(tp, TT_2MSL,
9191 						   (tcp_fast_finwait2_recycle ?
9192 						    tcp_finwait2_timeout :
9193 						    TP_MAXIDLE(tp)));
9194 			}
9195 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9196 		}
9197 	}
9198 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9199 				 tiwin, thflags, nxt_pkt));
9200 }
9201 
9202 /*
9203  * Return value of 1, the TCB is unlocked and most
9204  * likely gone, return value of 0, the TCB is still
9205  * locked.
9206  */
9207 static int
9208 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9209     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9210     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9211 {
9212 	struct tcp_bbr *bbr;
9213 	int32_t ret_val;
9214 
9215 	/*
9216 	 * Header prediction: check for the two common cases of a
9217 	 * uni-directional data xfer.  If the packet has no control flags,
9218 	 * is in-sequence, the window didn't change and we're not
9219 	 * retransmitting, it's a candidate.  If the length is zero and the
9220 	 * ack moved forward, we're the sender side of the xfer.  Just free
9221 	 * the data acked & wake any higher level process that was blocked
9222 	 * waiting for space.  If the length is non-zero and the ack didn't
9223 	 * move, we're the receiver side.  If we're getting packets in-order
9224 	 * (the reassembly queue is empty), add the data toc The socket
9225 	 * buffer and note that we need a delayed ack. Make sure that the
9226 	 * hidden state-flags are also off. Since we check for
9227 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9228 	 */
9229 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9230 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9231 		/*
9232 		 * If we have delived under 4 segments increase the initial
9233 		 * window if raised by the peer. We use this to determine
9234 		 * dynamic and static rwnd's at the end of a connection.
9235 		 */
9236 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9237 	}
9238 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9239 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9240 	    __predict_true(SEGQ_EMPTY(tp)) &&
9241 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9242 		if (tlen == 0) {
9243 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9244 			    tiwin, nxt_pkt, iptos)) {
9245 				return (0);
9246 			}
9247 		} else {
9248 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9249 			    tiwin, nxt_pkt)) {
9250 				return (0);
9251 			}
9252 		}
9253 	}
9254 	ctf_calc_rwin(so, tp);
9255 
9256 	if ((thflags & TH_RST) ||
9257 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9258 		return (ctf_process_rst(m, th, so, tp));
9259 	/*
9260 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9261 	 * synchronized state.
9262 	 */
9263 	if (thflags & TH_SYN) {
9264 		ctf_challenge_ack(m, th, tp, &ret_val);
9265 		return (ret_val);
9266 	}
9267 	/*
9268 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9269 	 * it's less than ts_recent, drop it.
9270 	 */
9271 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9272 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9273 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9274 			return (ret_val);
9275 	}
9276 	INP_WLOCK_ASSERT(tp->t_inpcb);
9277 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9278 		return (ret_val);
9279 	}
9280 	/*
9281 	 * If last ACK falls within this segment's sequence numbers, record
9282 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9283 	 * from the latest proposal of the tcplw@cray.com list (Braden
9284 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9285 	 * with our earlier PAWS tests, so this check should be solely
9286 	 * predicated on the sequence space of this segment. 3) That we
9287 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9288 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9289 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9290 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9291 	 * p.869. In such cases, we can still calculate the RTT correctly
9292 	 * when RCV.NXT == Last.ACK.Sent.
9293 	 */
9294 	if ((to->to_flags & TOF_TS) != 0 &&
9295 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9296 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9297 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9298 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9299 		tp->ts_recent = to->to_tsval;
9300 	}
9301 	/*
9302 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9303 	 * is on (half-synchronized state), then queue data for later
9304 	 * processing; else drop segment and return.
9305 	 */
9306 	if ((thflags & TH_ACK) == 0) {
9307 		if (tp->t_flags & TF_NEEDSYN) {
9308 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9309 			    tiwin, thflags, nxt_pkt));
9310 		} else if (tp->t_flags & TF_ACKNOW) {
9311 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9312 			bbr->r_wanted_output = 1;
9313 			return (ret_val);
9314 		} else {
9315 			ctf_do_drop(m, NULL);
9316 			return (0);
9317 		}
9318 	}
9319 	/*
9320 	 * Ack processing.
9321 	 */
9322 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9323 		return (ret_val);
9324 	}
9325 	if (sbavail(&so->so_snd)) {
9326 		if (ctf_progress_timeout_check(tp, true)) {
9327 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9328 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9329 			return (1);
9330 		}
9331 	}
9332 	/* State changes only happen in bbr_process_data() */
9333 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9334 	    tiwin, thflags, nxt_pkt));
9335 }
9336 
9337 /*
9338  * Return value of 1, the TCB is unlocked and most
9339  * likely gone, return value of 0, the TCB is still
9340  * locked.
9341  */
9342 static int
9343 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9344     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9345     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9346 {
9347 	struct tcp_bbr *bbr;
9348 	int32_t ret_val;
9349 
9350 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9351 	ctf_calc_rwin(so, tp);
9352 	if ((thflags & TH_RST) ||
9353 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9354 		return (ctf_process_rst(m, th, so, tp));
9355 	/*
9356 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9357 	 * synchronized state.
9358 	 */
9359 	if (thflags & TH_SYN) {
9360 		ctf_challenge_ack(m, th, tp, &ret_val);
9361 		return (ret_val);
9362 	}
9363 	/*
9364 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9365 	 * it's less than ts_recent, drop it.
9366 	 */
9367 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9368 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9369 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9370 			return (ret_val);
9371 	}
9372 	INP_WLOCK_ASSERT(tp->t_inpcb);
9373 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9374 		return (ret_val);
9375 	}
9376 	/*
9377 	 * If last ACK falls within this segment's sequence numbers, record
9378 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9379 	 * from the latest proposal of the tcplw@cray.com list (Braden
9380 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9381 	 * with our earlier PAWS tests, so this check should be solely
9382 	 * predicated on the sequence space of this segment. 3) That we
9383 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9384 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9385 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9386 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9387 	 * p.869. In such cases, we can still calculate the RTT correctly
9388 	 * when RCV.NXT == Last.ACK.Sent.
9389 	 */
9390 	if ((to->to_flags & TOF_TS) != 0 &&
9391 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9392 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9393 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9394 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9395 		tp->ts_recent = to->to_tsval;
9396 	}
9397 	/*
9398 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9399 	 * is on (half-synchronized state), then queue data for later
9400 	 * processing; else drop segment and return.
9401 	 */
9402 	if ((thflags & TH_ACK) == 0) {
9403 		if (tp->t_flags & TF_NEEDSYN) {
9404 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9405 			    tiwin, thflags, nxt_pkt));
9406 		} else if (tp->t_flags & TF_ACKNOW) {
9407 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9408 			bbr->r_wanted_output = 1;
9409 			return (ret_val);
9410 		} else {
9411 			ctf_do_drop(m, NULL);
9412 			return (0);
9413 		}
9414 	}
9415 	/*
9416 	 * Ack processing.
9417 	 */
9418 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9419 		return (ret_val);
9420 	}
9421 	if (sbavail(&so->so_snd)) {
9422 		if (ctf_progress_timeout_check(tp, true)) {
9423 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9424 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9425 			return (1);
9426 		}
9427 	}
9428 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9429 	    tiwin, thflags, nxt_pkt));
9430 }
9431 
9432 static int
9433 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9434     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9435 {
9436 
9437 	if (bbr->rc_allow_data_af_clo == 0) {
9438 close_now:
9439 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9440 		/* tcp_close will kill the inp pre-log the Reset */
9441 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9442 		tp = tcp_close(tp);
9443 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9444 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9445 		return (1);
9446 	}
9447 	if (sbavail(&so->so_snd) == 0)
9448 		goto close_now;
9449 	/* Ok we allow data that is ignored and a followup reset */
9450 	tp->rcv_nxt = th->th_seq + *tlen;
9451 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9452 	bbr->r_wanted_output = 1;
9453 	*tlen = 0;
9454 	return (0);
9455 }
9456 
9457 /*
9458  * Return value of 1, the TCB is unlocked and most
9459  * likely gone, return value of 0, the TCB is still
9460  * locked.
9461  */
9462 static int
9463 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9464     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9465     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9466 {
9467 	int32_t ourfinisacked = 0;
9468 	int32_t ret_val;
9469 	struct tcp_bbr *bbr;
9470 
9471 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9472 	ctf_calc_rwin(so, tp);
9473 	if ((thflags & TH_RST) ||
9474 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9475 		return (ctf_process_rst(m, th, so, tp));
9476 	/*
9477 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9478 	 * synchronized state.
9479 	 */
9480 	if (thflags & TH_SYN) {
9481 		ctf_challenge_ack(m, th, tp, &ret_val);
9482 		return (ret_val);
9483 	}
9484 	/*
9485 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9486 	 * it's less than ts_recent, drop it.
9487 	 */
9488 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9489 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9490 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9491 			return (ret_val);
9492 	}
9493 	INP_WLOCK_ASSERT(tp->t_inpcb);
9494 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9495 		return (ret_val);
9496 	}
9497 	/*
9498 	 * If new data are received on a connection after the user processes
9499 	 * are gone, then RST the other end.
9500 	 */
9501 	if ((so->so_state & SS_NOFDREF) && tlen) {
9502 		/*
9503 		 * We call a new function now so we might continue and setup
9504 		 * to reset at all data being ack'd.
9505 		 */
9506 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9507 			return (1);
9508 	}
9509 	/*
9510 	 * If last ACK falls within this segment's sequence numbers, record
9511 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9512 	 * from the latest proposal of the tcplw@cray.com list (Braden
9513 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9514 	 * with our earlier PAWS tests, so this check should be solely
9515 	 * predicated on the sequence space of this segment. 3) That we
9516 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9517 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9518 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9519 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9520 	 * p.869. In such cases, we can still calculate the RTT correctly
9521 	 * when RCV.NXT == Last.ACK.Sent.
9522 	 */
9523 	if ((to->to_flags & TOF_TS) != 0 &&
9524 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9525 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9526 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9527 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9528 		tp->ts_recent = to->to_tsval;
9529 	}
9530 	/*
9531 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9532 	 * is on (half-synchronized state), then queue data for later
9533 	 * processing; else drop segment and return.
9534 	 */
9535 	if ((thflags & TH_ACK) == 0) {
9536 		if (tp->t_flags & TF_NEEDSYN) {
9537 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9538 			    tiwin, thflags, nxt_pkt));
9539 		} else if (tp->t_flags & TF_ACKNOW) {
9540 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9541 			bbr->r_wanted_output = 1;
9542 			return (ret_val);
9543 		} else {
9544 			ctf_do_drop(m, NULL);
9545 			return (0);
9546 		}
9547 	}
9548 	/*
9549 	 * Ack processing.
9550 	 */
9551 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9552 		return (ret_val);
9553 	}
9554 	if (ourfinisacked) {
9555 		/*
9556 		 * If we can't receive any more data, then closing user can
9557 		 * proceed. Starting the timer is contrary to the
9558 		 * specification, but if we don't get a FIN we'll hang
9559 		 * forever.
9560 		 *
9561 		 * XXXjl: we should release the tp also, and use a
9562 		 * compressed state.
9563 		 */
9564 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9565 			soisdisconnected(so);
9566 			tcp_timer_activate(tp, TT_2MSL,
9567 			    (tcp_fast_finwait2_recycle ?
9568 			    tcp_finwait2_timeout :
9569 			    TP_MAXIDLE(tp)));
9570 		}
9571 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9572 	}
9573 	if (sbavail(&so->so_snd)) {
9574 		if (ctf_progress_timeout_check(tp, true)) {
9575 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9576 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9577 			return (1);
9578 		}
9579 	}
9580 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9581 	    tiwin, thflags, nxt_pkt));
9582 }
9583 
9584 /*
9585  * Return value of 1, the TCB is unlocked and most
9586  * likely gone, return value of 0, the TCB is still
9587  * locked.
9588  */
9589 static int
9590 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9591     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9592     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9593 {
9594 	int32_t ourfinisacked = 0;
9595 	int32_t ret_val;
9596 	struct tcp_bbr *bbr;
9597 
9598 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9599 	ctf_calc_rwin(so, tp);
9600 	if ((thflags & TH_RST) ||
9601 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9602 		return (ctf_process_rst(m, th, so, tp));
9603 	/*
9604 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9605 	 * synchronized state.
9606 	 */
9607 	if (thflags & TH_SYN) {
9608 		ctf_challenge_ack(m, th, tp, &ret_val);
9609 		return (ret_val);
9610 	}
9611 	/*
9612 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9613 	 * it's less than ts_recent, drop it.
9614 	 */
9615 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9616 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9617 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9618 			return (ret_val);
9619 	}
9620 	INP_WLOCK_ASSERT(tp->t_inpcb);
9621 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9622 		return (ret_val);
9623 	}
9624 	/*
9625 	 * If new data are received on a connection after the user processes
9626 	 * are gone, then RST the other end.
9627 	 */
9628 	if ((so->so_state & SS_NOFDREF) && tlen) {
9629 		/*
9630 		 * We call a new function now so we might continue and setup
9631 		 * to reset at all data being ack'd.
9632 		 */
9633 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9634 			return (1);
9635 	}
9636 	/*
9637 	 * If last ACK falls within this segment's sequence numbers, record
9638 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9639 	 * from the latest proposal of the tcplw@cray.com list (Braden
9640 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9641 	 * with our earlier PAWS tests, so this check should be solely
9642 	 * predicated on the sequence space of this segment. 3) That we
9643 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9644 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9645 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9646 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9647 	 * p.869. In such cases, we can still calculate the RTT correctly
9648 	 * when RCV.NXT == Last.ACK.Sent.
9649 	 */
9650 	if ((to->to_flags & TOF_TS) != 0 &&
9651 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9652 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9653 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9654 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9655 		tp->ts_recent = to->to_tsval;
9656 	}
9657 	/*
9658 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9659 	 * is on (half-synchronized state), then queue data for later
9660 	 * processing; else drop segment and return.
9661 	 */
9662 	if ((thflags & TH_ACK) == 0) {
9663 		if (tp->t_flags & TF_NEEDSYN) {
9664 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9665 			    tiwin, thflags, nxt_pkt));
9666 		} else if (tp->t_flags & TF_ACKNOW) {
9667 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9668 			bbr->r_wanted_output = 1;
9669 			return (ret_val);
9670 		} else {
9671 			ctf_do_drop(m, NULL);
9672 			return (0);
9673 		}
9674 	}
9675 	/*
9676 	 * Ack processing.
9677 	 */
9678 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9679 		return (ret_val);
9680 	}
9681 	if (ourfinisacked) {
9682 		tcp_twstart(tp);
9683 		m_freem(m);
9684 		return (1);
9685 	}
9686 	if (sbavail(&so->so_snd)) {
9687 		if (ctf_progress_timeout_check(tp, true)) {
9688 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9689 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9690 			return (1);
9691 		}
9692 	}
9693 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9694 	    tiwin, thflags, nxt_pkt));
9695 }
9696 
9697 /*
9698  * Return value of 1, the TCB is unlocked and most
9699  * likely gone, return value of 0, the TCB is still
9700  * locked.
9701  */
9702 static int
9703 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9704     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9705     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9706 {
9707 	int32_t ourfinisacked = 0;
9708 	int32_t ret_val;
9709 	struct tcp_bbr *bbr;
9710 
9711 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9712 	ctf_calc_rwin(so, tp);
9713 	if ((thflags & TH_RST) ||
9714 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9715 		return (ctf_process_rst(m, th, so, tp));
9716 	/*
9717 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9718 	 * synchronized state.
9719 	 */
9720 	if (thflags & TH_SYN) {
9721 		ctf_challenge_ack(m, th, tp, &ret_val);
9722 		return (ret_val);
9723 	}
9724 	/*
9725 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9726 	 * it's less than ts_recent, drop it.
9727 	 */
9728 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9729 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9730 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9731 			return (ret_val);
9732 	}
9733 	INP_WLOCK_ASSERT(tp->t_inpcb);
9734 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9735 		return (ret_val);
9736 	}
9737 	/*
9738 	 * If new data are received on a connection after the user processes
9739 	 * are gone, then RST the other end.
9740 	 */
9741 	if ((so->so_state & SS_NOFDREF) && tlen) {
9742 		/*
9743 		 * We call a new function now so we might continue and setup
9744 		 * to reset at all data being ack'd.
9745 		 */
9746 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9747 			return (1);
9748 	}
9749 	/*
9750 	 * If last ACK falls within this segment's sequence numbers, record
9751 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9752 	 * from the latest proposal of the tcplw@cray.com list (Braden
9753 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9754 	 * with our earlier PAWS tests, so this check should be solely
9755 	 * predicated on the sequence space of this segment. 3) That we
9756 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9757 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9758 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9759 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9760 	 * p.869. In such cases, we can still calculate the RTT correctly
9761 	 * when RCV.NXT == Last.ACK.Sent.
9762 	 */
9763 	if ((to->to_flags & TOF_TS) != 0 &&
9764 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9765 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9766 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9767 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9768 		tp->ts_recent = to->to_tsval;
9769 	}
9770 	/*
9771 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9772 	 * is on (half-synchronized state), then queue data for later
9773 	 * processing; else drop segment and return.
9774 	 */
9775 	if ((thflags & TH_ACK) == 0) {
9776 		if (tp->t_flags & TF_NEEDSYN) {
9777 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9778 			    tiwin, thflags, nxt_pkt));
9779 		} else if (tp->t_flags & TF_ACKNOW) {
9780 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9781 			bbr->r_wanted_output = 1;
9782 			return (ret_val);
9783 		} else {
9784 			ctf_do_drop(m, NULL);
9785 			return (0);
9786 		}
9787 	}
9788 	/*
9789 	 * case TCPS_LAST_ACK: Ack processing.
9790 	 */
9791 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9792 		return (ret_val);
9793 	}
9794 	if (ourfinisacked) {
9795 		tp = tcp_close(tp);
9796 		ctf_do_drop(m, tp);
9797 		return (1);
9798 	}
9799 	if (sbavail(&so->so_snd)) {
9800 		if (ctf_progress_timeout_check(tp, true)) {
9801 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9802 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9803 			return (1);
9804 		}
9805 	}
9806 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9807 	    tiwin, thflags, nxt_pkt));
9808 }
9809 
9810 /*
9811  * Return value of 1, the TCB is unlocked and most
9812  * likely gone, return value of 0, the TCB is still
9813  * locked.
9814  */
9815 static int
9816 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9817     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9818     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9819 {
9820 	int32_t ourfinisacked = 0;
9821 	int32_t ret_val;
9822 	struct tcp_bbr *bbr;
9823 
9824 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9825 	ctf_calc_rwin(so, tp);
9826 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9827 	if ((thflags & TH_RST) ||
9828 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9829 		return (ctf_process_rst(m, th, so, tp));
9830 
9831 	/*
9832 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9833 	 * synchronized state.
9834 	 */
9835 	if (thflags & TH_SYN) {
9836 		ctf_challenge_ack(m, th, tp, &ret_val);
9837 		return (ret_val);
9838 	}
9839 	INP_WLOCK_ASSERT(tp->t_inpcb);
9840 	/*
9841 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9842 	 * it's less than ts_recent, drop it.
9843 	 */
9844 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9845 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9846 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9847 			return (ret_val);
9848 	}
9849 	INP_WLOCK_ASSERT(tp->t_inpcb);
9850 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9851 		return (ret_val);
9852 	}
9853 	/*
9854 	 * If new data are received on a connection after the user processes
9855 	 * are gone, then we may RST the other end depending on the outcome
9856 	 * of bbr_check_data_after_close.
9857 	 */
9858 	if ((so->so_state & SS_NOFDREF) &&
9859 	    tlen) {
9860 		/*
9861 		 * We call a new function now so we might continue and setup
9862 		 * to reset at all data being ack'd.
9863 		 */
9864 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9865 			return (1);
9866 	}
9867 	INP_WLOCK_ASSERT(tp->t_inpcb);
9868 	/*
9869 	 * If last ACK falls within this segment's sequence numbers, record
9870 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9871 	 * from the latest proposal of the tcplw@cray.com list (Braden
9872 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9873 	 * with our earlier PAWS tests, so this check should be solely
9874 	 * predicated on the sequence space of this segment. 3) That we
9875 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9876 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9877 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9878 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9879 	 * p.869. In such cases, we can still calculate the RTT correctly
9880 	 * when RCV.NXT == Last.ACK.Sent.
9881 	 */
9882 	INP_WLOCK_ASSERT(tp->t_inpcb);
9883 	if ((to->to_flags & TOF_TS) != 0 &&
9884 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9885 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9886 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9887 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9888 		tp->ts_recent = to->to_tsval;
9889 	}
9890 	/*
9891 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9892 	 * is on (half-synchronized state), then queue data for later
9893 	 * processing; else drop segment and return.
9894 	 */
9895 	if ((thflags & TH_ACK) == 0) {
9896 		if (tp->t_flags & TF_NEEDSYN) {
9897 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9898 			    tiwin, thflags, nxt_pkt));
9899 		} else if (tp->t_flags & TF_ACKNOW) {
9900 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9901 			bbr->r_wanted_output = 1;
9902 			return (ret_val);
9903 		} else {
9904 			ctf_do_drop(m, NULL);
9905 			return (0);
9906 		}
9907 	}
9908 	/*
9909 	 * Ack processing.
9910 	 */
9911 	INP_WLOCK_ASSERT(tp->t_inpcb);
9912 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9913 		return (ret_val);
9914 	}
9915 	if (sbavail(&so->so_snd)) {
9916 		if (ctf_progress_timeout_check(tp, true)) {
9917 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9918 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9919 			return (1);
9920 		}
9921 	}
9922 	INP_WLOCK_ASSERT(tp->t_inpcb);
9923 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9924 	    tiwin, thflags, nxt_pkt));
9925 }
9926 
9927 static void
9928 bbr_stop_all_timers(struct tcpcb *tp)
9929 {
9930 	struct tcp_bbr *bbr;
9931 
9932 	/*
9933 	 * Assure no timers are running.
9934 	 */
9935 	if (tcp_timer_active(tp, TT_PERSIST)) {
9936 		/* We enter in persists, set the flag appropriately */
9937 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9938 		bbr->rc_in_persist = 1;
9939 	}
9940 	tcp_timer_suspend(tp, TT_PERSIST);
9941 	tcp_timer_suspend(tp, TT_REXMT);
9942 	tcp_timer_suspend(tp, TT_KEEP);
9943 	tcp_timer_suspend(tp, TT_DELACK);
9944 }
9945 
9946 static void
9947 bbr_google_mode_on(struct tcp_bbr *bbr)
9948 {
9949 	bbr->rc_use_google = 1;
9950 	bbr->rc_no_pacing = 0;
9951 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9952 	bbr->r_use_policer = bbr_policer_detection_enabled;
9953 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9954 	bbr->bbr_use_rack_cheat = 0;
9955 	bbr->r_ctl.rc_incr_tmrs = 0;
9956 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9957 	bbr->r_ctl.rc_inc_ip_oh = 0;
9958 	bbr->r_ctl.rc_inc_enet_oh = 0;
9959 	reset_time(&bbr->r_ctl.rc_delrate,
9960 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9961 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9962 			 (11 * USECS_IN_SECOND));
9963 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9964 }
9965 
9966 static void
9967 bbr_google_mode_off(struct tcp_bbr *bbr)
9968 {
9969 	bbr->rc_use_google = 0;
9970 	bbr->r_ctl.bbr_google_discount = 0;
9971 	bbr->no_pacing_until = bbr_no_pacing_until;
9972 	bbr->r_use_policer = 0;
9973 	if (bbr->no_pacing_until)
9974 		bbr->rc_no_pacing = 1;
9975 	else
9976 		bbr->rc_no_pacing = 0;
9977 	if (bbr_use_rack_resend_cheat)
9978 		bbr->bbr_use_rack_cheat = 1;
9979 	else
9980 		bbr->bbr_use_rack_cheat = 0;
9981 	if (bbr_incr_timers)
9982 		bbr->r_ctl.rc_incr_tmrs = 1;
9983 	else
9984 		bbr->r_ctl.rc_incr_tmrs = 0;
9985 	if (bbr_include_tcp_oh)
9986 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9987 	else
9988 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9989 	if (bbr_include_ip_oh)
9990 		bbr->r_ctl.rc_inc_ip_oh = 1;
9991 	else
9992 		bbr->r_ctl.rc_inc_ip_oh = 0;
9993 	if (bbr_include_enet_oh)
9994 		bbr->r_ctl.rc_inc_enet_oh = 1;
9995 	else
9996 		bbr->r_ctl.rc_inc_enet_oh = 0;
9997 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9998 	reset_time(&bbr->r_ctl.rc_delrate,
9999 		   bbr_num_pktepo_for_del_limit);
10000 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10001 			 (bbr_filter_len_sec * USECS_IN_SECOND));
10002 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10003 }
10004 /*
10005  * Return 0 on success, non-zero on failure
10006  * which indicates the error (usually no memory).
10007  */
10008 static int
10009 bbr_init(struct tcpcb *tp)
10010 {
10011 	struct tcp_bbr *bbr = NULL;
10012 	struct inpcb *inp;
10013 	uint32_t cts;
10014 
10015 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10016 	if (tp->t_fb_ptr == NULL) {
10017 		/*
10018 		 * We need to allocate memory but cant. The INP and INP_INFO
10019 		 * locks and they are recusive (happens during setup. So a
10020 		 * scheme to drop the locks fails :(
10021 		 *
10022 		 */
10023 		return (ENOMEM);
10024 	}
10025 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10026 	bbr->rtt_valid = 0;
10027 	inp = tp->t_inpcb;
10028 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10029 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10030 	TAILQ_INIT(&bbr->r_ctl.rc_map);
10031 	TAILQ_INIT(&bbr->r_ctl.rc_free);
10032 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10033 	bbr->rc_tp = tp;
10034 	if (tp->t_inpcb) {
10035 		bbr->rc_inp = tp->t_inpcb;
10036 	}
10037 	cts = tcp_get_usecs(&bbr->rc_tv);
10038 	tp->t_acktime = 0;
10039 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10040 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10041 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
10042 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10043 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10044 	bbr->r_ctl.rc_min_to = bbr_min_to;
10045 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
10046 	bbr->r_ctl.bbr_lost_at_state = 0;
10047 	bbr->r_ctl.rc_lost_at_startup = 0;
10048 	bbr->rc_all_timers_stopped = 0;
10049 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10050 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10051 	bbr->r_ctl.rc_pkt_epoch = 0;
10052 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10053 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10054 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10055 	bbr->r_ctl.rc_went_idle_time = cts;
10056 	bbr->rc_pacer_started = cts;
10057 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10058 	bbr->r_ctl.rc_rcvtime = cts;
10059 	bbr->r_ctl.rc_bbr_state_time = cts;
10060 	bbr->r_ctl.rc_del_time = cts;
10061 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10062 	bbr->r_ctl.last_in_probertt = cts;
10063 	bbr->skip_gain = 0;
10064 	bbr->gain_is_limited = 0;
10065 	bbr->no_pacing_until = bbr_no_pacing_until;
10066 	if (bbr->no_pacing_until)
10067 		bbr->rc_no_pacing = 1;
10068 	if (bbr_use_google_algo) {
10069 		bbr->rc_no_pacing = 0;
10070 		bbr->rc_use_google = 1;
10071 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10072 		bbr->r_use_policer = bbr_policer_detection_enabled;
10073 	} else {
10074 		bbr->rc_use_google = 0;
10075 		bbr->r_ctl.bbr_google_discount = 0;
10076 		bbr->r_use_policer = 0;
10077 	}
10078 	if (bbr_ts_limiting)
10079 		bbr->rc_use_ts_limit = 1;
10080 	else
10081 		bbr->rc_use_ts_limit = 0;
10082 	if (bbr_ts_can_raise)
10083 		bbr->ts_can_raise = 1;
10084 	else
10085 		bbr->ts_can_raise = 0;
10086 	if (V_tcp_delack_enabled == 1)
10087 		tp->t_delayed_ack = 2;
10088 	else if (V_tcp_delack_enabled == 0)
10089 		tp->t_delayed_ack = 0;
10090 	else if (V_tcp_delack_enabled < 100)
10091 		tp->t_delayed_ack = V_tcp_delack_enabled;
10092 	else
10093 		tp->t_delayed_ack = 2;
10094 	if (bbr->rc_use_google == 0)
10095 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10096 	else
10097 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10098 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10099 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10100 	bbr->rc_init_win = bbr_def_init_win;
10101 	if (tp->t_flags & TF_REQ_TSTMP)
10102 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10103 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10104 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10105 	bbr->r_init_rtt = 1;
10106 
10107 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10108 	if (bbr_allow_hdwr_pacing)
10109 		bbr->bbr_hdw_pace_ena = 1;
10110 	else
10111 		bbr->bbr_hdw_pace_ena = 0;
10112 	if (bbr_sends_full_iwnd)
10113 		bbr->bbr_init_win_cheat = 1;
10114 	else
10115 		bbr->bbr_init_win_cheat = 0;
10116 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10117 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10118 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10119 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10120 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10121 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10122 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10123 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10124 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10125 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10126 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10127 	bbr->r_ctl.rc_rtt_shrinks = cts;
10128 	if (bbr->rc_use_google) {
10129 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10130 				  FILTER_TYPE_MAX,
10131 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10132 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10133 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10134 	} else {
10135 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10136 				  FILTER_TYPE_MAX,
10137 				  bbr_num_pktepo_for_del_limit);
10138 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10139 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10140 	}
10141 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10142 	if (bbr_uses_idle_restart)
10143 		bbr->rc_use_idle_restart = 1;
10144 	else
10145 		bbr->rc_use_idle_restart = 0;
10146 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10147 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10148 	if (bbr_resends_use_tso)
10149 		bbr->rc_resends_use_tso = 1;
10150 #ifdef NETFLIX_PEAKRATE
10151 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10152 #endif
10153 	if (tp->snd_una != tp->snd_max) {
10154 		/* Create a send map for the current outstanding data */
10155 		struct bbr_sendmap *rsm;
10156 
10157 		rsm = bbr_alloc(bbr);
10158 		if (rsm == NULL) {
10159 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10160 			tp->t_fb_ptr = NULL;
10161 			return (ENOMEM);
10162 		}
10163 		rsm->r_rtt_not_allowed = 1;
10164 		rsm->r_tim_lastsent[0] = cts;
10165 		rsm->r_rtr_cnt = 1;
10166 		rsm->r_rtr_bytes = 0;
10167 		rsm->r_start = tp->snd_una;
10168 		rsm->r_end = tp->snd_max;
10169 		rsm->r_dupack = 0;
10170 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10171 		rsm->r_ts_valid = 0;
10172 		rsm->r_del_ack_ts = tp->ts_recent;
10173 		rsm->r_del_time = cts;
10174 		if (bbr->r_ctl.r_app_limited_until)
10175 			rsm->r_app_limited = 1;
10176 		else
10177 			rsm->r_app_limited = 0;
10178 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10179 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10180 		rsm->r_in_tmap = 1;
10181 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10182 			rsm->r_bbr_state = bbr_state_val(bbr);
10183 		else
10184 			rsm->r_bbr_state = 8;
10185 	}
10186 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10187 		bbr->bbr_use_rack_cheat = 1;
10188 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10189 		bbr->r_ctl.rc_incr_tmrs = 1;
10190 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10191 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10192 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10193 		bbr->r_ctl.rc_inc_ip_oh = 1;
10194 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10195 		bbr->r_ctl.rc_inc_enet_oh = 1;
10196 
10197 	bbr_log_type_statechange(bbr, cts, __LINE__);
10198 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10199 	    (tp->t_srtt)) {
10200 		uint32_t rtt;
10201 
10202 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10203 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10204 	}
10205 	/* announce the settings and state */
10206 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10207 	tcp_bbr_tso_size_check(bbr, cts);
10208 	/*
10209 	 * Now call the generic function to start a timer. This will place
10210 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10211 	 * flags.
10212 	 */
10213 	bbr_stop_all_timers(tp);
10214 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10215 	return (0);
10216 }
10217 
10218 /*
10219  * Return 0 if we can accept the connection. Return
10220  * non-zero if we can't handle the connection. A EAGAIN
10221  * means you need to wait until the connection is up.
10222  * a EADDRNOTAVAIL means we can never handle the connection
10223  * (no SACK).
10224  */
10225 static int
10226 bbr_handoff_ok(struct tcpcb *tp)
10227 {
10228 	if ((tp->t_state == TCPS_CLOSED) ||
10229 	    (tp->t_state == TCPS_LISTEN)) {
10230 		/* Sure no problem though it may not stick */
10231 		return (0);
10232 	}
10233 	if ((tp->t_state == TCPS_SYN_SENT) ||
10234 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10235 		/*
10236 		 * We really don't know you have to get to ESTAB or beyond
10237 		 * to tell.
10238 		 */
10239 		return (EAGAIN);
10240 	}
10241 	if (tp->t_flags & TF_SENTFIN)
10242 		return (EINVAL);
10243 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10244 		return (0);
10245 	}
10246 	/*
10247 	 * If we reach here we don't do SACK on this connection so we can
10248 	 * never do rack.
10249 	 */
10250 	return (EINVAL);
10251 }
10252 
10253 static void
10254 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10255 {
10256 	if (tp->t_fb_ptr) {
10257 		uint32_t calc;
10258 		struct tcp_bbr *bbr;
10259 		struct bbr_sendmap *rsm;
10260 
10261 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10262 		if (bbr->r_ctl.crte)
10263 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10264 		bbr_log_flowend(bbr);
10265 		bbr->rc_tp = NULL;
10266 		if (tp->t_inpcb) {
10267 			/* Backout any flags2 we applied */
10268 			tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10269 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10270 			tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10271 		}
10272 		if (bbr->bbr_hdrw_pacing)
10273 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10274 		else
10275 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10276 		if (bbr->r_ctl.crte != NULL) {
10277 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10278 			bbr->r_ctl.crte = NULL;
10279 		}
10280 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10281 		while (rsm) {
10282 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10283 			uma_zfree(bbr_zone, rsm);
10284 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10285 		}
10286 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10287 		while (rsm) {
10288 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10289 			uma_zfree(bbr_zone, rsm);
10290 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10291 		}
10292 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10293 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10294 			BBR_STAT_INC(bbr_dynamic_rwnd);
10295 		else
10296 			BBR_STAT_INC(bbr_static_rwnd);
10297 		bbr->r_ctl.rc_free_cnt = 0;
10298 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10299 		tp->t_fb_ptr = NULL;
10300 	}
10301 	/* Make sure snd_nxt is correctly set */
10302 	tp->snd_nxt = tp->snd_max;
10303 }
10304 
10305 static void
10306 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10307 {
10308 	switch (tp->t_state) {
10309 	case TCPS_SYN_SENT:
10310 		bbr->r_state = TCPS_SYN_SENT;
10311 		bbr->r_substate = bbr_do_syn_sent;
10312 		break;
10313 	case TCPS_SYN_RECEIVED:
10314 		bbr->r_state = TCPS_SYN_RECEIVED;
10315 		bbr->r_substate = bbr_do_syn_recv;
10316 		break;
10317 	case TCPS_ESTABLISHED:
10318 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10319 		bbr->r_state = TCPS_ESTABLISHED;
10320 		bbr->r_substate = bbr_do_established;
10321 		break;
10322 	case TCPS_CLOSE_WAIT:
10323 		bbr->r_state = TCPS_CLOSE_WAIT;
10324 		bbr->r_substate = bbr_do_close_wait;
10325 		break;
10326 	case TCPS_FIN_WAIT_1:
10327 		bbr->r_state = TCPS_FIN_WAIT_1;
10328 		bbr->r_substate = bbr_do_fin_wait_1;
10329 		break;
10330 	case TCPS_CLOSING:
10331 		bbr->r_state = TCPS_CLOSING;
10332 		bbr->r_substate = bbr_do_closing;
10333 		break;
10334 	case TCPS_LAST_ACK:
10335 		bbr->r_state = TCPS_LAST_ACK;
10336 		bbr->r_substate = bbr_do_lastack;
10337 		break;
10338 	case TCPS_FIN_WAIT_2:
10339 		bbr->r_state = TCPS_FIN_WAIT_2;
10340 		bbr->r_substate = bbr_do_fin_wait_2;
10341 		break;
10342 	case TCPS_LISTEN:
10343 	case TCPS_CLOSED:
10344 	case TCPS_TIME_WAIT:
10345 	default:
10346 		break;
10347 	};
10348 }
10349 
10350 static void
10351 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10352 {
10353 	/*
10354 	 * Now what state are we going into now? Is there adjustments
10355 	 * needed?
10356 	 */
10357 	int32_t old_state;
10358 
10359 	old_state = bbr_state_val(bbr);
10360 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10361 		/* Save the lowest srtt we saw in our end of the sub-state */
10362 		bbr->rc_hit_state_1 = 0;
10363 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10364 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10365 	}
10366 	bbr->rc_bbr_substate++;
10367 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10368 		/* Cycle back to first state-> gain */
10369 		bbr->rc_bbr_substate = 0;
10370 	}
10371 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10372 		/*
10373 		 * We enter the gain(5/4) cycle (possibly less if
10374 		 * shallow buffer detection is enabled)
10375 		 */
10376 		if (bbr->skip_gain) {
10377 			/*
10378 			 * Hardware pacing has set our rate to
10379 			 * the max and limited our b/w just
10380 			 * do level i.e. no gain.
10381 			 */
10382 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10383 		} else if (bbr->gain_is_limited &&
10384 			   bbr->bbr_hdrw_pacing &&
10385 			   bbr->r_ctl.crte) {
10386 			/*
10387 			 * We can't gain above the hardware pacing
10388 			 * rate which is less than our rate + the gain
10389 			 * calculate the gain needed to reach the hardware
10390 			 * pacing rate..
10391 			 */
10392 			uint64_t bw, rate, gain_calc;
10393 
10394 			bw = bbr_get_bw(bbr);
10395 			rate = bbr->r_ctl.crte->rate;
10396 			if ((rate > bw) &&
10397 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10398 				gain_calc = (rate * BBR_UNIT) / bw;
10399 				if (gain_calc < BBR_UNIT)
10400 					gain_calc = BBR_UNIT;
10401 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10402 			} else {
10403 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10404 			}
10405 		} else
10406 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10407 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10408 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10409 		} else
10410 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10411 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10412 		bbr->rc_hit_state_1 = 1;
10413 		bbr->r_ctl.rc_exta_time_gd = 0;
10414 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10415 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10416 		if (bbr_state_drain_2_tar) {
10417 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10418 		} else
10419 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10420 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10421 	} else {
10422 		/* All other cycles hit here 2-7 */
10423 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10424 			if (bbr_sub_drain_slam_cwnd &&
10425 			    (bbr->rc_use_google == 0) &&
10426 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10427 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10428 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10429 			}
10430 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10431 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10432 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10433 			else
10434 				bbr->r_ctl.rc_exta_time_gd = 0;
10435 			if (bbr->r_ctl.rc_exta_time_gd) {
10436 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10437 				/* Now chop up the time for each state (div by 7) */
10438 				bbr->r_ctl.rc_level_state_extra /= 7;
10439 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10440 					/* Add a randomization */
10441 					bbr_randomize_extra_state_time(bbr);
10442 				}
10443 			}
10444 		}
10445 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10446 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10447 	}
10448 	if (bbr->rc_use_google) {
10449 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10450 	}
10451 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10452 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10453 	if (dolog)
10454 		bbr_log_type_statechange(bbr, cts, line);
10455 
10456 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10457 		uint32_t time_in;
10458 
10459 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10460 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10461 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10462 		} else {
10463 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10464 		}
10465 	}
10466 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10467 	bbr_set_state_target(bbr, __LINE__);
10468 	if (bbr_sub_drain_slam_cwnd &&
10469 	    (bbr->rc_use_google == 0) &&
10470 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10471 		/* Slam down the cwnd */
10472 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10473 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10474 		if (bbr_sub_drain_app_limit) {
10475 			/* Go app limited if we are on a long drain */
10476 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10477 							  ctf_flight_size(bbr->rc_tp,
10478 							      (bbr->r_ctl.rc_sacked +
10479 							       bbr->r_ctl.rc_lost_bytes)));
10480 		}
10481 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10482 	}
10483 	if (bbr->rc_lt_use_bw) {
10484 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10485 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10486 	}
10487 	/* Google changes TSO size every cycle */
10488 	if (bbr->rc_use_google)
10489 		tcp_bbr_tso_size_check(bbr, cts);
10490 	bbr->r_ctl.gain_epoch = cts;
10491 	bbr->r_ctl.rc_bbr_state_time = cts;
10492 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10493 }
10494 
10495 static void
10496 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10497 {
10498 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10499 	    (google_allow_early_out == 1) &&
10500 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10501 		/* We have reached out target flight size possibly early */
10502 		goto change_state;
10503 	}
10504 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10505 		return;
10506 	}
10507 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10508 		/*
10509 		 * Must be a rttProp movement forward before
10510 		 * we can change states.
10511 		 */
10512 		return;
10513 	}
10514 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10515 		/*
10516 		 * The needed time has passed but for
10517 		 * the gain cycle extra rules apply:
10518 		 * 1) If we have seen loss, we exit
10519 		 * 2) If we have not reached the target
10520 		 *    we stay in GAIN (gain-to-target).
10521 		 */
10522 		if (google_consider_lost && losses)
10523 			goto change_state;
10524 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10525 			return;
10526 		}
10527 	}
10528 change_state:
10529 	/* For gain we must reach our target, all others last 1 rttProp */
10530 	bbr_substate_change(bbr, cts, __LINE__, 1);
10531 }
10532 
10533 static void
10534 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10535 {
10536 	uint32_t flight, bbr_cur_cycle_time;
10537 
10538 	if (bbr->rc_use_google) {
10539 		bbr_set_probebw_google_gains(bbr, cts, losses);
10540 		return;
10541 	}
10542 	if (cts == 0) {
10543 		/*
10544 		 * Never alow cts to be 0 we
10545 		 * do this so we can judge if
10546 		 * we have set a timestamp.
10547 		 */
10548 		cts = 1;
10549 	}
10550 	if (bbr_state_is_pkt_epoch)
10551 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10552 	else
10553 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10554 
10555 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10556 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10557 			flight = ctf_flight_size(bbr->rc_tp,
10558 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10559 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10560 				/* Keep it slam down */
10561 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10562 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10563 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10564 				}
10565 				if (bbr_sub_drain_app_limit) {
10566 					/* Go app limited if we are on a long drain */
10567 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10568 				}
10569 			}
10570 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10571 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10572 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10573 				/*
10574 				 * Still here after the same time as
10575 				 * the gain. We need to drain harder
10576 				 * for the next srtt. Reduce by a set amount
10577 				 * the gain drop is capped at DRAIN states
10578 				 * value (88).
10579 				 */
10580 				bbr->r_ctl.flightsize_at_drain = flight;
10581 				if (bbr_drain_drop_mul &&
10582 				    bbr_drain_drop_div &&
10583 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10584 					/* Use your specific drop value (def 4/5 = 20%) */
10585 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10586 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10587 				} else {
10588 					/* You get drop of 20% */
10589 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10590 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10591 				}
10592 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10593 					/* Reduce our gain again to the bottom  */
10594 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10595 				}
10596 				bbr_log_exit_gain(bbr, cts, 4);
10597 				/*
10598 				 * Extend out so we wait another
10599 				 * epoch before dropping again.
10600 				 */
10601 				bbr->r_ctl.gain_epoch = cts;
10602 			}
10603 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10604 				if (bbr_sub_drain_slam_cwnd &&
10605 				    (bbr->rc_use_google == 0) &&
10606 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10607 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10608 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10609 				}
10610 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10611 				bbr_log_exit_gain(bbr, cts, 3);
10612 			}
10613 		} else {
10614 			/* Its a gain  */
10615 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10616 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10617 				goto change_state;
10618 			}
10619 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10620 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10621 			     bbr->rc_tp->snd_wnd)) {
10622 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10623 				bbr_log_exit_gain(bbr, cts, 2);
10624 			}
10625 		}
10626 		/**
10627 		 * We fall through and return always one of two things has
10628 		 * occurred.
10629 		 * 1) We are still not at target
10630 		 *    <or>
10631 		 * 2) We reached the target and set rc_bbr_state_atflight
10632 		 *    which means we no longer hit this block
10633 		 *    next time we are called.
10634 		 */
10635 		return;
10636 	}
10637 change_state:
10638 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10639 		return;
10640 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10641 		/* Less than a full time-period has passed */
10642 		return;
10643 	}
10644 	if (bbr->r_ctl.rc_level_state_extra &&
10645 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10646 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10647 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10648 		/* Less than a full time-period + extra has passed */
10649 		return;
10650 	}
10651 	if (bbr_gain_gets_extra_too &&
10652 	    bbr->r_ctl.rc_level_state_extra &&
10653 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10654 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10655 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10656 		/* Less than a full time-period + extra has passed */
10657 		return;
10658 	}
10659 	bbr_substate_change(bbr, cts, __LINE__, 1);
10660 }
10661 
10662 static uint32_t
10663 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10664 {
10665 	uint32_t mss, tar;
10666 
10667 	if (bbr->rc_use_google) {
10668 		/* Google just uses the cwnd target */
10669 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10670 	} else {
10671 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10672 			  bbr->r_ctl.rc_pace_max_segs);
10673 		/* Get the base cwnd with gain rounded to a mss */
10674 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10675 						      gain), mss);
10676 		/* Make sure it is within our min */
10677 		if (tar < get_min_cwnd(bbr))
10678 			return (get_min_cwnd(bbr));
10679 	}
10680 	return (tar);
10681 }
10682 
10683 static void
10684 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10685 {
10686 	uint32_t tar, meth;
10687 
10688 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10689 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10690 		/* Special case using old probe-rtt method */
10691 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10692 		meth = 1;
10693 	} else {
10694 		/* Non-probe-rtt case and reduced probe-rtt  */
10695 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10696 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10697 			/* For gain cycle we use the hptsi gain */
10698 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10699 			meth = 2;
10700 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10701 			/*
10702 			 * If configured, or for google all other states
10703 			 * get BBR_UNIT.
10704 			 */
10705 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10706 			meth = 3;
10707 		} else {
10708 			/*
10709 			 * Or we set a target based on the pacing gain
10710 			 * for non-google mode and default (non-configured).
10711 			 * Note we don't set a target goal below drain (192).
10712 			 */
10713 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10714 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10715 				meth = 4;
10716 			} else {
10717 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10718 				meth = 5;
10719 			}
10720 		}
10721 	}
10722 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10723 	bbr->r_ctl.rc_target_at_state = tar;
10724 }
10725 
10726 static void
10727 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10728 {
10729 	/* Change to probe_rtt */
10730 	uint32_t time_in;
10731 
10732 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10733 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10734 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10735 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10736 					  + bbr->r_ctl.rc_delivered);
10737 	/* Setup so we force feed the filter */
10738 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10739 		bbr->rc_prtt_set_ts = 1;
10740 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10741 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10742 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10743 	}
10744 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10745 	bbr->r_ctl.rc_rtt_shrinks = cts;
10746 	bbr->r_ctl.last_in_probertt = cts;
10747 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10748 	bbr->r_ctl.rc_bbr_state_time = cts;
10749 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10750 	/* We need to force the filter to update */
10751 
10752 	if ((bbr_sub_drain_slam_cwnd) &&
10753 	    bbr->rc_hit_state_1 &&
10754 	    (bbr->rc_use_google == 0) &&
10755 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10756 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10757 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10758 	} else
10759 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10760 	/* Update the lost */
10761 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10762 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10763 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10764 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10765 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10766 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10767 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10768 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10769 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10770 	} else {
10771 		/*
10772 		 * We bring it down slowly by using a hptsi gain that is
10773 		 * probably 75%. This will slowly float down our outstanding
10774 		 * without tampering with the cwnd.
10775 		 */
10776 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10777 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10778 		bbr_set_state_target(bbr, __LINE__);
10779 		if (bbr_prtt_slam_cwnd &&
10780 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10781 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10782 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10783 		}
10784 	}
10785 	if (ctf_flight_size(bbr->rc_tp,
10786 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10787 	    bbr->r_ctl.rc_target_at_state) {
10788 		/* We are at target */
10789 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10790 	} else {
10791 		/* We need to come down to reach target before our time begins */
10792 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10793 	}
10794 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10795 	BBR_STAT_INC(bbr_enter_probertt);
10796 	bbr_log_exit_gain(bbr, cts, 0);
10797 	bbr_log_type_statechange(bbr, cts, line);
10798 }
10799 
10800 static void
10801 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10802 {
10803 	/*
10804 	 * Sanity check on probe-rtt intervals.
10805 	 * In crazy situations where we are competing
10806 	 * against new-reno flows with huge buffers
10807 	 * our rtt-prop interval could come to dominate
10808 	 * things if we can't get through a full set
10809 	 * of cycles, we need to adjust it.
10810 	 */
10811 	if (bbr_can_adjust_probertt &&
10812 	    (bbr->rc_use_google == 0)) {
10813 		uint16_t val = 0;
10814 		uint32_t cur_rttp, fval, newval, baseval;
10815 
10816 		/* Are we to small and go into probe-rtt to often? */
10817 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10818 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10819 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10820 		if (bbr_is_ratio == 0) {
10821 			if (fval > bbr_rtt_probe_limit)
10822 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10823 			else
10824 				newval = cur_rttp;
10825 		} else {
10826 			int mul;
10827 
10828 			mul = fval / bbr_rtt_probe_limit;
10829 			newval = cur_rttp * mul;
10830 		}
10831 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10832 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10833 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10834 			val = 1;
10835 		} else {
10836 			/*
10837 			 * No adjustments were made
10838 			 * do we need to shrink it?
10839 			 */
10840 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10841 				if (cur_rttp <= bbr_rtt_probe_limit) {
10842 					/*
10843 					 * Things have calmed down lets
10844 					 * shrink all the way to default
10845 					 */
10846 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10847 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10848 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10849 					cur_rttp = bbr_rtt_probe_limit;
10850 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10851 					val = 2;
10852 				} else {
10853 					/*
10854 					 * Well does some adjustment make sense?
10855 					 */
10856 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10857 						/* We can reduce interval time some */
10858 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10859 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10860 						val = 3;
10861 					}
10862 				}
10863 			}
10864 		}
10865 		if (val)
10866 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10867 	}
10868 }
10869 
10870 static void
10871 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10872 {
10873 	/* Exit probe-rtt */
10874 
10875 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10876 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10877 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10878 	}
10879 	bbr_log_exit_gain(bbr, cts, 1);
10880 	bbr->rc_hit_state_1 = 0;
10881 	bbr->r_ctl.rc_rtt_shrinks = cts;
10882 	bbr->r_ctl.last_in_probertt = cts;
10883 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10884 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10885 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10886 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10887 					  bbr->r_ctl.rc_delivered);
10888 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10889 		uint32_t time_in;
10890 
10891 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10892 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10893 	}
10894 	if (bbr->rc_filled_pipe) {
10895 		/* Switch to probe_bw */
10896 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10897 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10898 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10899 		bbr_substate_change(bbr, cts, __LINE__, 0);
10900 		bbr_log_type_statechange(bbr, cts, __LINE__);
10901 	} else {
10902 		/* Back to startup */
10903 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10904 		bbr->r_ctl.rc_bbr_state_time = cts;
10905 		/*
10906 		 * We don't want to give a complete free 3
10907 		 * measurements until we exit, so we use
10908 		 * the number of pe's we were in probe-rtt
10909 		 * to add to the startup_epoch. That way
10910 		 * we will still retain the old state.
10911 		 */
10912 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10913 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10914 		/* Make sure to use the lower pg when shifting back in */
10915 		if (bbr->r_ctl.rc_lost &&
10916 		    bbr_use_lower_gain_in_startup &&
10917 		    (bbr->rc_use_google == 0))
10918 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10919 		else
10920 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10921 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10922 		/* Probably not needed but set it anyway */
10923 		bbr_set_state_target(bbr, __LINE__);
10924 		bbr_log_type_statechange(bbr, cts, __LINE__);
10925 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10926 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10927 	}
10928 	bbr_check_probe_rtt_limits(bbr, cts);
10929 }
10930 
10931 static int32_t inline
10932 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10933 {
10934 	if ((bbr->rc_past_init_win == 1) &&
10935 	    (bbr->rc_in_persist == 0) &&
10936 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10937 		return (1);
10938 	}
10939 	if (bbr_can_force_probertt &&
10940 	    (bbr->rc_in_persist == 0) &&
10941 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10942 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10943 		return (1);
10944 	}
10945 	return (0);
10946 }
10947 
10948 static int32_t
10949 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10950 {
10951 	uint64_t btlbw, gain;
10952 	if (pkt_epoch == 0) {
10953 		/*
10954 		 * Need to be on a pkt-epoch to continue.
10955 		 */
10956 		return (0);
10957 	}
10958 	btlbw = bbr_get_full_bw(bbr);
10959 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10960 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10961 	if (btlbw >= gain) {
10962 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10963 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10964 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10965 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10966 	}
10967 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10968 		return (1);
10969 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10970 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10971 	return(0);
10972 }
10973 
10974 static int32_t inline
10975 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10976 {
10977 	/* Have we gained 25% in the last 3 packet based epoch's? */
10978 	uint64_t btlbw, gain;
10979 	int do_exit;
10980 	int delta, rtt_gain;
10981 
10982 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10983 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10984 		/*
10985 		 * This qualifies as a RTT_PROBE session since we drop the
10986 		 * data outstanding to nothing and waited more than
10987 		 * bbr_rtt_probe_time.
10988 		 */
10989 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10990 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10991 	}
10992 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10993 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10994 		return (0);
10995 	}
10996 	if (bbr->rc_use_google)
10997 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10998 
10999 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11000 	    (bbr_use_lower_gain_in_startup)) {
11001 		/* Drop to a lower gain 1.5 x since we saw loss */
11002 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11003 	}
11004 	if (pkt_epoch == 0) {
11005 		/*
11006 		 * Need to be on a pkt-epoch to continue.
11007 		 */
11008 		return (0);
11009 	}
11010 	if (bbr_rtt_gain_thresh) {
11011 		/*
11012 		 * Do we allow a flow to stay
11013 		 * in startup with no loss and no
11014 		 * gain in rtt over a set threshold?
11015 		 */
11016 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11017 		    bbr->r_ctl.startup_last_srtt &&
11018 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11019 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11020 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11021 		} else
11022 			rtt_gain = 0;
11023 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11024 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11025 			/* First time or new lower value */
11026 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11027 
11028 		if ((bbr->r_ctl.rc_lost == 0) &&
11029 		    (rtt_gain < bbr_rtt_gain_thresh)) {
11030 			/*
11031 			 * No loss, and we are under
11032 			 * our gain threhold for
11033 			 * increasing RTT.
11034 			 */
11035 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11036 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
11037 			bbr_log_startup_event(bbr, cts, rtt_gain,
11038 					      delta, bbr->r_ctl.startup_last_srtt, 10);
11039 			return (0);
11040 		}
11041 	}
11042 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11043 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11044 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11045 		/*
11046 		 * We only assess if we have a new measurment when
11047 		 * we have no loss and are not in recovery.
11048 		 * Drag up by one our last_startup epoch so we will hold
11049 		 * the number of non-gain we have already accumulated.
11050 		 */
11051 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11052 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11053 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11054 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11055 		return (0);
11056 	}
11057 	/* Case where we reduced the lost (bad retransmit) */
11058 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11059 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11060 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11061 	btlbw = bbr_get_full_bw(bbr);
11062 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11063 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11064 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11065 	else
11066 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11067 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11068 	do_exit = 0;
11069 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11070 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11071 	if (btlbw >= gain) {
11072 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11073 		/* Update the lost so we won't exit in next set of tests */
11074 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11075 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11076 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11077 	}
11078 	if ((bbr->rc_loss_exit &&
11079 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11080 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11081 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11082 		/*
11083 		 * If we had no gain,  we had loss and that loss was above
11084 		 * our threshould, the rwnd is not constrained, and we have
11085 		 * had at least 3 packet epochs exit. Note that this is
11086 		 * switched off by sysctl. Google does not do this by the
11087 		 * way.
11088 		 */
11089 		if ((ctf_flight_size(bbr->rc_tp,
11090 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11091 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11092 			do_exit = 1;
11093 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11094 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11095 		} else {
11096 			/* Just record an updated loss value */
11097 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11098 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11099 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11100 		}
11101 	} else
11102 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11103 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11104 	    do_exit) {
11105 		/* Return 1 to exit the startup state. */
11106 		return (1);
11107 	}
11108 	/* Stay in startup */
11109 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11110 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11111 	return (0);
11112 }
11113 
11114 static void
11115 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11116 {
11117 	/*
11118 	 * A tick occurred in the rtt epoch do we need to do anything?
11119 	 */
11120 #ifdef BBR_INVARIANTS
11121 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11122 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11123 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11124 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11125 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11126 		/* Debug code? */
11127 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11128 	}
11129 #endif
11130 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11131 		/* Do we exit the startup state? */
11132 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11133 			uint32_t time_in;
11134 
11135 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11136 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11137 			bbr->rc_filled_pipe = 1;
11138 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11139 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11140 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11141 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11142 			} else
11143 				time_in = 0;
11144 			if (bbr->rc_no_pacing)
11145 				bbr->rc_no_pacing = 0;
11146 			bbr->r_ctl.rc_bbr_state_time = cts;
11147 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11148 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11149 			bbr_set_state_target(bbr, __LINE__);
11150 			if ((bbr->rc_use_google == 0) &&
11151 			    bbr_slam_cwnd_in_main_drain) {
11152 				/* Here we don't have to worry about probe-rtt */
11153 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11154 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11155 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11156 			}
11157 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11158 			bbr_log_type_statechange(bbr, cts, __LINE__);
11159 			if (ctf_flight_size(bbr->rc_tp,
11160 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11161 			    bbr->r_ctl.rc_target_at_state) {
11162 				/*
11163 				 * Switch to probe_bw if we are already
11164 				 * there
11165 				 */
11166 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11167 				bbr_substate_change(bbr, cts, __LINE__, 0);
11168 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11169 				bbr_log_type_statechange(bbr, cts, __LINE__);
11170 			}
11171 		}
11172 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11173 		uint32_t inflight;
11174 		struct tcpcb *tp;
11175 
11176 		tp = bbr->rc_tp;
11177 		inflight = ctf_flight_size(tp,
11178 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11179 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11180 			/* We have reached a flight of the cwnd target */
11181 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11182 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11183 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11184 			bbr_set_state_target(bbr, __LINE__);
11185 			/*
11186 			 * Rig it so we don't do anything crazy and
11187 			 * start fresh with a new randomization.
11188 			 */
11189 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11190 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11191 			bbr_substate_change(bbr, cts, __LINE__, 1);
11192 		}
11193 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11194 		/* Has in-flight reached the bdp (or less)? */
11195 		uint32_t inflight;
11196 		struct tcpcb *tp;
11197 
11198 		tp = bbr->rc_tp;
11199 		inflight = ctf_flight_size(tp,
11200 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11201 		if ((bbr->rc_use_google == 0) &&
11202 		    bbr_slam_cwnd_in_main_drain &&
11203 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11204 			/*
11205 			 * Here we don't have to worry about probe-rtt
11206 			 * re-slam it, but keep it slammed down.
11207 			 */
11208 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11209 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11210 		}
11211 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11212 			/* We have drained */
11213 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11214 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11215 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11216 				uint32_t time_in;
11217 
11218 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11219 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11220 			}
11221 			if ((bbr->rc_use_google == 0) &&
11222 			    bbr_slam_cwnd_in_main_drain &&
11223 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11224 				/* Restore the cwnd */
11225 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11226 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11227 			}
11228 			/* Setup probe-rtt has being done now RRS-HERE */
11229 			bbr->r_ctl.rc_rtt_shrinks = cts;
11230 			bbr->r_ctl.last_in_probertt = cts;
11231 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11232 			/* Randomly pick a sub-state */
11233 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11234 			bbr_substate_change(bbr, cts, __LINE__, 0);
11235 			bbr_log_type_statechange(bbr, cts, __LINE__);
11236 		}
11237 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11238 		uint32_t flight;
11239 
11240 		flight = ctf_flight_size(bbr->rc_tp,
11241 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11242 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11243 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11244 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11245 			/*
11246 			 * We must keep cwnd at the desired MSS.
11247 			 */
11248 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11249 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11250 		} else if ((bbr_prtt_slam_cwnd) &&
11251 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11252 			/* Re-slam it */
11253 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11254 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11255 		}
11256 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11257 			/* Has outstanding reached our target? */
11258 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11259 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11260 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11261 				/* If time is exactly 0, be 1usec off */
11262 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11263 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11264 				if (bbr->rc_use_google == 0) {
11265 					/*
11266 					 * Restore any lowering that as occurred to
11267 					 * reach here
11268 					 */
11269 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11270 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11271 					else
11272 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11273 				}
11274 			}
11275 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11276 			    (bbr->rc_use_google == 0) &&
11277 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11278 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11279 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11280 				/*
11281 				 * We have doddled with our current hptsi
11282 				 * gain an srtt and have still not made it
11283 				 * to target, or we have increased our flight.
11284 				 * Lets reduce the gain by xx%
11285 				 * flooring the reduce at DRAIN (based on
11286 				 * mul/div)
11287 				 */
11288 				int red;
11289 
11290 				bbr->r_ctl.flightsize_at_drain = flight;
11291 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11292 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11293 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11294 					/* Reduce our gain again */
11295 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11296 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11297 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11298 					/* one more chance before we give up */
11299 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11300 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11301 				} else {
11302 					/* At the very bottom */
11303 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11304 				}
11305 			}
11306 		}
11307 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11308 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11309 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11310 			/* Time to exit probe RTT normally */
11311 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11312 		}
11313 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11314 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11315 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11316 			/*
11317 			 * This qualifies as a RTT_PROBE session since we
11318 			 * drop the data outstanding to nothing and waited
11319 			 * more than bbr_rtt_probe_time.
11320 			 */
11321 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11322 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11323 		}
11324 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11325 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11326 		} else {
11327 			bbr_set_probebw_gains(bbr, cts, losses);
11328 		}
11329 	}
11330 }
11331 
11332 static void
11333 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11334 {
11335 	int32_t epoch = 0;
11336 
11337 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11338 		bbr_set_epoch(bbr, cts, line);
11339 		/* At each epoch doe lt bw sampling */
11340 		epoch = 1;
11341 	}
11342 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11343 }
11344 
11345 static int
11346 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11347     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11348     int32_t nxt_pkt, struct timeval *tv)
11349 {
11350 	int32_t thflags, retval;
11351 	uint32_t cts, lcts;
11352 	uint32_t tiwin;
11353 	struct tcpopt to;
11354 	struct tcp_bbr *bbr;
11355 	struct bbr_sendmap *rsm;
11356 	struct timeval ltv;
11357 	int32_t did_out = 0;
11358 	uint16_t nsegs;
11359 	int32_t prev_state;
11360 	uint32_t lost;
11361 
11362 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11363 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11364 	/* add in our stats */
11365 	kern_prefetch(bbr, &prev_state);
11366 	prev_state = 0;
11367 	thflags = th->th_flags;
11368 	/*
11369 	 * If this is either a state-changing packet or current state isn't
11370 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11371 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11372 	 * caller may have unnecessarily acquired a write lock due to a
11373 	 * race.
11374 	 */
11375 	INP_WLOCK_ASSERT(tp->t_inpcb);
11376 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11377 	    __func__));
11378 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11379 	    __func__));
11380 
11381 	tp->t_rcvtime = ticks;
11382 	/*
11383 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11384 	 * the scale is zero.
11385 	 */
11386 	tiwin = th->th_win << tp->snd_scale;
11387 #ifdef STATS
11388 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11389 #endif
11390 
11391 	if (m->m_flags & M_TSTMP) {
11392 		/* Prefer the hardware timestamp if present */
11393 		struct timespec ts;
11394 
11395 		mbuf_tstmp2timespec(m, &ts);
11396 		bbr->rc_tv.tv_sec = ts.tv_sec;
11397 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11398 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11399 	} else if (m->m_flags & M_TSTMP_LRO) {
11400 		/* Next the arrival timestamp */
11401 		struct timespec ts;
11402 
11403 		mbuf_tstmp2timespec(m, &ts);
11404 		bbr->rc_tv.tv_sec = ts.tv_sec;
11405 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11406 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11407 	} else {
11408 		/*
11409 		 * Ok just get the current time.
11410 		 */
11411 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11412 	}
11413 	/*
11414 	 * Parse options on any incoming segment.
11415 	 */
11416 	tcp_dooptions(&to, (u_char *)(th + 1),
11417 	    (th->th_off << 2) - sizeof(struct tcphdr),
11418 	    (thflags & TH_SYN) ? TO_SYN : 0);
11419 
11420 	/*
11421 	 * If timestamps were negotiated during SYN/ACK and a
11422 	 * segment without a timestamp is received, silently drop
11423 	 * the segment, unless it is a RST segment or missing timestamps are
11424 	 * tolerated.
11425 	 * See section 3.2 of RFC 7323.
11426 	 */
11427 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11428 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11429 		retval = 0;
11430 		m_freem(m);
11431 		goto done_with_input;
11432 	}
11433 	/*
11434 	 * If echoed timestamp is later than the current time, fall back to
11435 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11436 	 * were used when this connection was established.
11437 	 */
11438 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11439 		to.to_tsecr -= tp->ts_offset;
11440 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11441 			to.to_tsecr = 0;
11442 	}
11443 	/*
11444 	 * If its the first time in we need to take care of options and
11445 	 * verify we can do SACK for rack!
11446 	 */
11447 	if (bbr->r_state == 0) {
11448 		/*
11449 		 * Process options only when we get SYN/ACK back. The SYN
11450 		 * case for incoming connections is handled in tcp_syncache.
11451 		 * According to RFC1323 the window field in a SYN (i.e., a
11452 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11453 		 * this is traditional behavior, may need to be cleaned up.
11454 		 */
11455 		if (bbr->rc_inp == NULL) {
11456 			bbr->rc_inp = tp->t_inpcb;
11457 		}
11458 		/*
11459 		 * We need to init rc_inp here since its not init'd when
11460 		 * bbr_init is called
11461 		 */
11462 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11463 			if ((to.to_flags & TOF_SCALE) &&
11464 			    (tp->t_flags & TF_REQ_SCALE)) {
11465 				tp->t_flags |= TF_RCVD_SCALE;
11466 				tp->snd_scale = to.to_wscale;
11467 			} else
11468 				tp->t_flags &= ~TF_REQ_SCALE;
11469 			/*
11470 			 * Initial send window.  It will be updated with the
11471 			 * next incoming segment to the scaled value.
11472 			 */
11473 			tp->snd_wnd = th->th_win;
11474 			if ((to.to_flags & TOF_TS) &&
11475 			    (tp->t_flags & TF_REQ_TSTMP)) {
11476 				tp->t_flags |= TF_RCVD_TSTMP;
11477 				tp->ts_recent = to.to_tsval;
11478 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11479 			} else
11480 			    tp->t_flags &= ~TF_REQ_TSTMP;
11481 			if (to.to_flags & TOF_MSS)
11482 				tcp_mss(tp, to.to_mss);
11483 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11484 			    (to.to_flags & TOF_SACKPERM) == 0)
11485 				tp->t_flags &= ~TF_SACK_PERMIT;
11486 			if (IS_FASTOPEN(tp->t_flags)) {
11487 				if (to.to_flags & TOF_FASTOPEN) {
11488 					uint16_t mss;
11489 
11490 					if (to.to_flags & TOF_MSS)
11491 						mss = to.to_mss;
11492 					else
11493 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11494 							mss = TCP6_MSS;
11495 						else
11496 							mss = TCP_MSS;
11497 					tcp_fastopen_update_cache(tp, mss,
11498 					    to.to_tfo_len, to.to_tfo_cookie);
11499 				} else
11500 					tcp_fastopen_disable_path(tp);
11501 			}
11502 		}
11503 		/*
11504 		 * At this point we are at the initial call. Here we decide
11505 		 * if we are doing RACK or not. We do this by seeing if
11506 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11507 		 * we switch to the default code.
11508 		 */
11509 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11510 			/* Bail */
11511 			tcp_switch_back_to_default(tp);
11512 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11513 			    tlen, iptos);
11514 			return (1);
11515 		}
11516 		/* Set the flag */
11517 		bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11518 		tcp_set_hpts(tp->t_inpcb);
11519 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11520 	}
11521 	if (thflags & TH_ACK) {
11522 		/* Track ack types */
11523 		if (to.to_flags & TOF_SACK)
11524 			BBR_STAT_INC(bbr_acks_with_sacks);
11525 		else
11526 			BBR_STAT_INC(bbr_plain_acks);
11527 	}
11528 	/*
11529 	 * This is the one exception case where we set the rack state
11530 	 * always. All other times (timers etc) we must have a rack-state
11531 	 * set (so we assure we have done the checks above for SACK).
11532 	 */
11533 	if (thflags & TH_FIN)
11534 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11535 	if (bbr->r_state != tp->t_state)
11536 		bbr_set_state(tp, bbr, tiwin);
11537 
11538 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11539 		kern_prefetch(rsm, &prev_state);
11540 	prev_state = bbr->r_state;
11541 	bbr->rc_ack_was_delayed = 0;
11542 	lost = bbr->r_ctl.rc_lost;
11543 	bbr->rc_is_pkt_epoch_now = 0;
11544 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11545 		/* Get the real time into lcts and figure the real delay */
11546 		lcts = tcp_get_usecs(&ltv);
11547 		if (TSTMP_GT(lcts, cts)) {
11548 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11549 			bbr->rc_ack_was_delayed = 1;
11550 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11551 				     bbr->r_ctl.highest_hdwr_delay))
11552 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11553 		} else {
11554 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11555 			bbr->rc_ack_was_delayed = 0;
11556 		}
11557 	} else {
11558 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11559 		bbr->rc_ack_was_delayed = 0;
11560 	}
11561 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11562 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11563 		retval = 0;
11564 		m_freem(m);
11565 		goto done_with_input;
11566 	}
11567 	/*
11568 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11569 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11570 	 */
11571 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11572 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11573 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11574 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11575 		return (1);
11576 	}
11577 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11578 		bbr->r_ctl.rc_high_rwnd = tiwin;
11579 #ifdef BBR_INVARIANTS
11580 	if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11581 	    (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11582 		panic("tp:%p bbr:%p given a dropped inp:%p",
11583 		    tp, bbr, tp->t_inpcb);
11584 	}
11585 #endif
11586 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11587 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11588 	bbr->rtt_valid = 0;
11589 	if (to.to_flags & TOF_TS) {
11590 		bbr->rc_ts_valid = 1;
11591 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11592 	} else {
11593 		bbr->rc_ts_valid = 0;
11594 		bbr->r_ctl.last_inbound_ts = 0;
11595 	}
11596 	retval = (*bbr->r_substate) (m, th, so,
11597 	    tp, &to, drop_hdrlen,
11598 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11599 #ifdef BBR_INVARIANTS
11600 	if ((retval == 0) &&
11601 	    (tp->t_inpcb == NULL)) {
11602 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11603 		    retval, tp, prev_state);
11604 	}
11605 #endif
11606 	if (nxt_pkt == 0)
11607 		BBR_STAT_INC(bbr_rlock_left_ret0);
11608 	else
11609 		BBR_STAT_INC(bbr_rlock_left_ret1);
11610 	if (retval == 0) {
11611 		/*
11612 		 * If retval is 1 the tcb is unlocked and most likely the tp
11613 		 * is gone.
11614 		 */
11615 		INP_WLOCK_ASSERT(tp->t_inpcb);
11616 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11617 		if (bbr->rc_is_pkt_epoch_now)
11618 			bbr_set_pktepoch(bbr, cts, __LINE__);
11619 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11620 		if (nxt_pkt == 0) {
11621 			if (bbr->r_wanted_output != 0) {
11622 				bbr->rc_output_starts_timer = 0;
11623 				did_out = 1;
11624 				if (tcp_output(tp) < 0)
11625 					return (1);
11626 			} else
11627 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11628 		}
11629 		if ((nxt_pkt == 0) &&
11630 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11631 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11632 		     (tp->t_flags & TF_DELACK) ||
11633 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11634 		      (tp->t_state <= TCPS_CLOSING)))) {
11635 			/*
11636 			 * We could not send (probably in the hpts but
11637 			 * stopped the timer)?
11638 			 */
11639 			if ((tp->snd_max == tp->snd_una) &&
11640 			    ((tp->t_flags & TF_DELACK) == 0) &&
11641 			    (tcp_in_hpts(bbr->rc_inp)) &&
11642 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11643 				/*
11644 				 * keep alive not needed if we are hptsi
11645 				 * output yet
11646 				 */
11647 				;
11648 			} else {
11649 				if (tcp_in_hpts(bbr->rc_inp)) {
11650 					tcp_hpts_remove(bbr->rc_inp);
11651 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11652 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11653 						uint32_t del;
11654 
11655 						del = lcts - bbr->rc_pacer_started;
11656 						if (bbr->r_ctl.rc_last_delay_val > del) {
11657 							BBR_STAT_INC(bbr_force_timer_start);
11658 							bbr->r_ctl.rc_last_delay_val -= del;
11659 							bbr->rc_pacer_started = lcts;
11660 						} else {
11661 							/* We are late */
11662 							bbr->r_ctl.rc_last_delay_val = 0;
11663 							BBR_STAT_INC(bbr_force_output);
11664 							if (tcp_output(tp) < 0)
11665 								return (1);
11666 						}
11667 					}
11668 				}
11669 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11670 				    0);
11671 			}
11672 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11673 			/* Do we have the correct timer running? */
11674 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11675 		}
11676 		/* Do we have a new state */
11677 		if (bbr->r_state != tp->t_state)
11678 			bbr_set_state(tp, bbr, tiwin);
11679 done_with_input:
11680 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11681 		if (did_out)
11682 			bbr->r_wanted_output = 0;
11683 #ifdef BBR_INVARIANTS
11684 		if (tp->t_inpcb == NULL) {
11685 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11686 			    did_out,
11687 			    retval, tp, prev_state);
11688 		}
11689 #endif
11690 	}
11691 	return (retval);
11692 }
11693 
11694 static void
11695 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11696     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11697 {
11698 	struct timeval tv;
11699 	int retval;
11700 
11701 	/* First lets see if we have old packets */
11702 	if (tp->t_in_pkt) {
11703 		if (ctf_do_queued_segments(so, tp, 1)) {
11704 			m_freem(m);
11705 			return;
11706 		}
11707 	}
11708 	if (m->m_flags & M_TSTMP_LRO) {
11709 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11710 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11711 	} else {
11712 		/* Should not be should we kassert instead? */
11713 		tcp_get_usecs(&tv);
11714 	}
11715 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11716 					 drop_hdrlen, tlen, iptos, 0, &tv);
11717 	if (retval == 0) {
11718 		INP_WUNLOCK(tp->t_inpcb);
11719 	}
11720 }
11721 
11722 /*
11723  * Return how much data can be sent without violating the
11724  * cwnd or rwnd.
11725  */
11726 
11727 static inline uint32_t
11728 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11729     uint32_t avail, int32_t sb_offset, uint32_t cts)
11730 {
11731 	uint32_t len;
11732 
11733 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11734 		/* We never want to go over our peers rcv-window */
11735 		len = 0;
11736 	} else {
11737 		uint32_t flight;
11738 
11739 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11740 		if (flight >= sendwin) {
11741 			/*
11742 			 * We have in flight what we are allowed by cwnd (if
11743 			 * it was rwnd blocking it would have hit above out
11744 			 * >= tp->snd_wnd).
11745 			 */
11746 			return (0);
11747 		}
11748 		len = sendwin - flight;
11749 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11750 			/* We would send too much (beyond the rwnd) */
11751 			len = tp->snd_wnd - ctf_outstanding(tp);
11752 		}
11753 		if ((len + sb_offset) > avail) {
11754 			/*
11755 			 * We don't have that much in the SB, how much is
11756 			 * there?
11757 			 */
11758 			len = avail - sb_offset;
11759 		}
11760 	}
11761 	return (len);
11762 }
11763 
11764 static inline void
11765 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11766 {
11767 #ifdef NETFLIX_STATS
11768 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11769 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11770 #endif
11771 }
11772 
11773 static inline void
11774 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11775 {
11776 	if (error) {
11777 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11778 		return;
11779 	}
11780 	if (rsm) {
11781 		if (rsm->r_flags & BBR_TLP) {
11782 			/*
11783 			 * TLP should not count in retran count, but in its
11784 			 * own bin
11785 			 */
11786 #ifdef NETFLIX_STATS
11787 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11788 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11789 #endif
11790 		} else {
11791 			/* Retransmit */
11792 			tp->t_sndrexmitpack++;
11793 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11794 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11795 #ifdef STATS
11796 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11797 			    len);
11798 #endif
11799 		}
11800 		/*
11801 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11802 		 * sub-state
11803 		 */
11804 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11805 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11806 			/* Non probe_bw log in 1, 2, or 4. */
11807 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11808 		} else {
11809 			/*
11810 			 * Log our probe state 3, and log also 5-13 to show
11811 			 * us the recovery sub-state for the send. This
11812 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11813 			 */
11814 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11815 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11816 		}
11817 		/* Place in both 16's the totals of retransmitted */
11818 		counter_u64_add(bbr_state_lost[16], len);
11819 		counter_u64_add(bbr_state_resend[16], len);
11820 		/* Place in 17's the total sent */
11821 		counter_u64_add(bbr_state_resend[17], len);
11822 		counter_u64_add(bbr_state_lost[17], len);
11823 
11824 	} else {
11825 		/* New sends */
11826 		KMOD_TCPSTAT_INC(tcps_sndpack);
11827 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11828 		/* Place in 17's the total sent */
11829 		counter_u64_add(bbr_state_resend[17], len);
11830 		counter_u64_add(bbr_state_lost[17], len);
11831 #ifdef STATS
11832 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11833 		    len);
11834 #endif
11835 	}
11836 }
11837 
11838 static void
11839 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11840 {
11841 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11842 		/*
11843 		 * Limit the cwnd to not be above N x the target plus whats
11844 		 * is outstanding. The target is based on the current b/w
11845 		 * estimate.
11846 		 */
11847 		uint32_t target;
11848 
11849 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11850 		target += ctf_outstanding(tp);
11851 		target *= bbr_target_cwnd_mult_limit;
11852 		if (tp->snd_cwnd > target)
11853 			tp->snd_cwnd = target;
11854 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11855 	}
11856 }
11857 
11858 static int
11859 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11860 {
11861 	/*
11862 	 * "adv" is the amount we could increase the window, taking into
11863 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11864 	 */
11865 	int32_t adv;
11866 	int32_t oldwin;
11867 
11868 	adv = recwin;
11869 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11870 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11871 		if (adv > oldwin)
11872 			adv -= oldwin;
11873 		else {
11874 			/* We can't increase the window */
11875 			adv = 0;
11876 		}
11877 	} else
11878 		oldwin = 0;
11879 
11880 	/*
11881 	 * If the new window size ends up being the same as or less
11882 	 * than the old size when it is scaled, then don't force
11883 	 * a window update.
11884 	 */
11885 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11886 		return (0);
11887 
11888 	if (adv >= (2 * maxseg) &&
11889 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11890 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11891 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11892 		return (1);
11893 	}
11894 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11895 		return (1);
11896 	return (0);
11897 }
11898 
11899 /*
11900  * Return 0 on success and a errno on failure to send.
11901  * Note that a 0 return may not mean we sent anything
11902  * if the TCB was on the hpts. A non-zero return
11903  * does indicate the error we got from ip[6]_output.
11904  */
11905 static int
11906 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11907 {
11908 	struct socket *so;
11909 	int32_t len;
11910 	uint32_t cts;
11911 	uint32_t recwin, sendwin;
11912 	int32_t sb_offset;
11913 	int32_t flags, abandon, error = 0;
11914 	struct tcp_log_buffer *lgb = NULL;
11915 	struct mbuf *m;
11916 	struct mbuf *mb;
11917 	uint32_t if_hw_tsomaxsegcount = 0;
11918 	uint32_t if_hw_tsomaxsegsize = 0;
11919 	uint32_t if_hw_tsomax = 0;
11920 	struct ip *ip = NULL;
11921 #ifdef TCPDEBUG
11922 	struct ipovly *ipov = NULL;
11923 #endif
11924 	struct tcp_bbr *bbr;
11925 	struct tcphdr *th;
11926 	struct udphdr *udp = NULL;
11927 	u_char opt[TCP_MAXOLEN];
11928 	unsigned ipoptlen, optlen, hdrlen;
11929 	unsigned ulen;
11930 	uint32_t bbr_seq;
11931 	uint32_t delay_calc=0;
11932 	uint8_t doing_tlp = 0;
11933 	uint8_t local_options;
11934 #ifdef BBR_INVARIANTS
11935 	uint8_t doing_retran_from = 0;
11936 	uint8_t picked_up_retran = 0;
11937 #endif
11938 	uint8_t wanted_cookie = 0;
11939 	uint8_t more_to_rxt=0;
11940 	int32_t prefetch_so_done = 0;
11941 	int32_t prefetch_rsm = 0;
11942 	uint32_t tot_len = 0;
11943 	uint32_t rtr_cnt = 0;
11944 	uint32_t maxseg, pace_max_segs, p_maxseg;
11945 	int32_t csum_flags = 0;
11946  	int32_t hw_tls;
11947 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11948 	unsigned ipsec_optlen = 0;
11949 
11950 #endif
11951 	volatile int32_t sack_rxmit;
11952 	struct bbr_sendmap *rsm = NULL;
11953 	int32_t tso, mtu;
11954 	struct tcpopt to;
11955 	int32_t slot = 0;
11956 	struct inpcb *inp;
11957 	struct sockbuf *sb;
11958 	uint32_t hpts_calling;
11959 #ifdef INET6
11960 	struct ip6_hdr *ip6 = NULL;
11961 	int32_t isipv6;
11962 #endif
11963 	uint8_t app_limited = BBR_JR_SENT_DATA;
11964 	uint8_t filled_all = 0;
11965 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11966 	/* We take a cache hit here */
11967 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11968 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11969 	inp = bbr->rc_inp;
11970 	so = inp->inp_socket;
11971 	sb = &so->so_snd;
11972  	if (sb->sb_flags & SB_TLS_IFNET)
11973  		hw_tls = 1;
11974  	else
11975  		hw_tls = 0;
11976 	kern_prefetch(sb, &maxseg);
11977 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11978 	if (bbr_minseg(bbr) < maxseg) {
11979 		tcp_bbr_tso_size_check(bbr, cts);
11980 	}
11981 	/* Remove any flags that indicate we are pacing on the inp  */
11982 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11983 	p_maxseg = min(maxseg, pace_max_segs);
11984 	INP_WLOCK_ASSERT(inp);
11985 #ifdef TCP_OFFLOAD
11986 	if (tp->t_flags & TF_TOE)
11987 		return (tcp_offload_output(tp));
11988 #endif
11989 
11990 #ifdef INET6
11991 	if (bbr->r_state) {
11992 		/* Use the cache line loaded if possible */
11993 		isipv6 = bbr->r_is_v6;
11994 	} else {
11995 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11996 	}
11997 #endif
11998 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11999 	    tcp_in_hpts(inp)) {
12000 		/*
12001 		 * We are on the hpts for some timer but not hptsi output.
12002 		 * Possibly remove from the hpts so we can send/recv etc.
12003 		 */
12004 		if ((tp->t_flags & TF_ACKNOW) == 0) {
12005 			/*
12006 			 * No immediate demand right now to send an ack, but
12007 			 * the user may have read, making room for new data
12008 			 * (a window update). If so we may want to cancel
12009 			 * whatever timer is running (KEEP/DEL-ACK?) and
12010 			 * continue to send out a window update. Or we may
12011 			 * have gotten more data into the socket buffer to
12012 			 * send.
12013 			 */
12014 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12015 				      (long)TCP_MAXWIN << tp->rcv_scale);
12016 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12017 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
12018 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12019 			    (tp->snd_max - tp->snd_una))) {
12020 				/*
12021 				 * Nothing new to send and no window update
12022 				 * is needed to send. Lets just return and
12023 				 * let the timer-run off.
12024 				 */
12025 				return (0);
12026 			}
12027 		}
12028 		tcp_hpts_remove(inp);
12029 		bbr_timer_cancel(bbr, __LINE__, cts);
12030 	}
12031 	if (bbr->r_ctl.rc_last_delay_val) {
12032 		/* Calculate a rough delay for early escape to sending  */
12033 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12034 			delay_calc = cts - bbr->rc_pacer_started;
12035 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12036 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12037 		else
12038 			delay_calc = 0;
12039 	}
12040 	/* Mark that we have called bbr_output(). */
12041 	if ((bbr->r_timer_override) ||
12042 	    (tp->t_state < TCPS_ESTABLISHED)) {
12043 		/* Timeouts or early states are exempt */
12044 		if (tcp_in_hpts(inp))
12045 			tcp_hpts_remove(inp);
12046 	} else if (tcp_in_hpts(inp)) {
12047 		if ((bbr->r_ctl.rc_last_delay_val) &&
12048 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12049 		    delay_calc) {
12050 			/*
12051 			 * We were being paced for output and the delay has
12052 			 * already exceeded when we were supposed to be
12053 			 * called, lets go ahead and pull out of the hpts
12054 			 * and call output.
12055 			 */
12056 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12057 			bbr->r_ctl.rc_last_delay_val = 0;
12058 			tcp_hpts_remove(inp);
12059 		} else if (tp->t_state == TCPS_CLOSED) {
12060 			bbr->r_ctl.rc_last_delay_val = 0;
12061 			tcp_hpts_remove(inp);
12062 		} else {
12063 			/*
12064 			 * On the hpts, you shall not pass! even if ACKNOW
12065 			 * is on, we will when the hpts fires, unless of
12066 			 * course we are overdue.
12067 			 */
12068 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12069 			return (0);
12070 		}
12071 	}
12072 	bbr->rc_cwnd_limited = 0;
12073 	if (bbr->r_ctl.rc_last_delay_val) {
12074 		/* recalculate the real delay and deal with over/under  */
12075 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12076 			delay_calc = cts - bbr->rc_pacer_started;
12077 		else
12078 			delay_calc = 0;
12079 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12080 			/* Setup the delay which will be added in */
12081 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12082 		else {
12083 			/*
12084 			 * We are early setup to adjust
12085 			 * our slot time.
12086 			 */
12087 			uint64_t merged_val;
12088 
12089 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12090 			bbr->r_agg_early_set = 1;
12091 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12092 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12093 					/* Nope our previous late cancels out the early */
12094 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12095 					bbr->r_agg_early_set = 0;
12096 					bbr->r_ctl.rc_agg_early = 0;
12097 				} else {
12098 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12099 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12100 				}
12101 			}
12102 			merged_val = bbr->rc_pacer_started;
12103 			merged_val <<= 32;
12104 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12105 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12106 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12107 						 bbr->r_agg_early_set, 3);
12108 			bbr->r_ctl.rc_last_delay_val = 0;
12109 			BBR_STAT_INC(bbr_early);
12110 			delay_calc = 0;
12111 		}
12112 	} else {
12113 		/* We were not delayed due to hptsi */
12114 		if (bbr->r_agg_early_set)
12115 			bbr->r_ctl.rc_agg_early = 0;
12116 		bbr->r_agg_early_set = 0;
12117 		delay_calc = 0;
12118 	}
12119 	if (delay_calc) {
12120 		/*
12121 		 * We had a hptsi delay which means we are falling behind on
12122 		 * sending at the expected rate. Calculate an extra amount
12123 		 * of data we can send, if any, to put us back on track.
12124 		 */
12125 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12126 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12127 		else
12128 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12129 	}
12130 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12131 	if ((tp->snd_una == tp->snd_max) &&
12132 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12133 	    (sbavail(sb))) {
12134 		/*
12135 		 * Ok we have been idle with nothing outstanding
12136 		 * we possibly need to start fresh with either a new
12137 		 * suite of states or a fast-ramp up.
12138 		 */
12139 		bbr_restart_after_idle(bbr,
12140 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12141 	}
12142 	/*
12143 	 * Now was there a hptsi delay where we are behind? We only count
12144 	 * being behind if: a) We are not in recovery. b) There was a delay.
12145 	 * <and> c) We had room to send something.
12146 	 *
12147 	 */
12148 	hpts_calling = inp->inp_hpts_calls;
12149 	inp->inp_hpts_calls = 0;
12150 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12151 		int retval;
12152 
12153 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12154 		if (retval != 0) {
12155 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12156 			/*
12157 			 * If timers want tcp_drop(), then pass error out,
12158 			 * otherwise suppress it.
12159 			 */
12160 			return (retval < 0 ? retval : 0);
12161 		}
12162 	}
12163 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12164 	if (hpts_calling &&
12165 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12166 		bbr->r_ctl.rc_last_delay_val = 0;
12167 	}
12168 	bbr->r_timer_override = 0;
12169 	bbr->r_wanted_output = 0;
12170 	/*
12171 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12172 	 * SYN|ACK and those sent by the retransmit timer.
12173 	 */
12174 	if (IS_FASTOPEN(tp->t_flags) &&
12175 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12176 	     (tp->t_state == TCPS_SYN_SENT)) &&
12177 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12178 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12179 		len = 0;
12180 		goto just_return_nolock;
12181 	}
12182 	/*
12183 	 * Before sending anything check for a state update. For hpts
12184 	 * calling without input this is important. If its input calling
12185 	 * then this was already done.
12186 	 */
12187 	if (bbr->rc_use_google == 0)
12188 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12189 again:
12190 	/*
12191 	 * If we've recently taken a timeout, snd_max will be greater than
12192 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12193 	 * for historic reasons the persist timer still uses it. This means
12194 	 * we have to look at it. All retransmissions that are not persits
12195 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12196 	 * end of this routine we pull snd_nxt always up to snd_max.
12197 	 */
12198 	doing_tlp = 0;
12199 #ifdef BBR_INVARIANTS
12200 	doing_retran_from = picked_up_retran = 0;
12201 #endif
12202 	error = 0;
12203 	tso = 0;
12204 	slot = 0;
12205 	mtu = 0;
12206 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12207 	sb_offset = tp->snd_max - tp->snd_una;
12208 	flags = tcp_outflags[tp->t_state];
12209 	sack_rxmit = 0;
12210 	len = 0;
12211 	rsm = NULL;
12212 	if (flags & TH_RST) {
12213 		SOCKBUF_LOCK(sb);
12214 		goto send;
12215 	}
12216 recheck_resend:
12217 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12218 		/* We need to always have one in reserve */
12219 		rsm = bbr_alloc(bbr);
12220 		if (rsm == NULL) {
12221 			error = ENOMEM;
12222 			/* Lie to get on the hpts */
12223 			tot_len = tp->t_maxseg;
12224 			if (hpts_calling)
12225 				/* Retry in a ms */
12226 				slot = 1001;
12227 			goto just_return_nolock;
12228 		}
12229 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12230 		bbr->r_ctl.rc_free_cnt++;
12231 		rsm = NULL;
12232 	}
12233 	/* What do we send, a resend? */
12234 	if (bbr->r_ctl.rc_resend == NULL) {
12235 		/* Check for rack timeout */
12236 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12237 		if (bbr->r_ctl.rc_resend) {
12238 #ifdef BBR_INVARIANTS
12239 			picked_up_retran = 1;
12240 #endif
12241 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12242 		}
12243 	}
12244 	if (bbr->r_ctl.rc_resend) {
12245 		rsm = bbr->r_ctl.rc_resend;
12246 #ifdef BBR_INVARIANTS
12247 		doing_retran_from = 1;
12248 #endif
12249 		/* Remove any TLP flags its a RACK or T-O */
12250 		rsm->r_flags &= ~BBR_TLP;
12251 		bbr->r_ctl.rc_resend = NULL;
12252 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12253 #ifdef BBR_INVARIANTS
12254 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12255 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12256 			goto recheck_resend;
12257 #else
12258 			/* TSNH */
12259 			rsm = NULL;
12260 			goto recheck_resend;
12261 #endif
12262 		}
12263 		rtr_cnt++;
12264 		if (rsm->r_flags & BBR_HAS_SYN) {
12265 			/* Only retransmit a SYN by itself */
12266 			len = 0;
12267 			if ((flags & TH_SYN) == 0) {
12268 				/* Huh something is wrong */
12269 				rsm->r_start++;
12270 				if (rsm->r_start == rsm->r_end) {
12271 					/* Clean it up, somehow we missed the ack? */
12272 					bbr_log_syn(tp, NULL);
12273 				} else {
12274 					/* TFO with data? */
12275 					rsm->r_flags &= ~BBR_HAS_SYN;
12276 					len = rsm->r_end - rsm->r_start;
12277 				}
12278 			} else {
12279 				/* Retransmitting SYN */
12280 				rsm = NULL;
12281 				SOCKBUF_LOCK(sb);
12282 				goto send;
12283 			}
12284 		} else
12285 			len = rsm->r_end - rsm->r_start;
12286 		if ((bbr->rc_resends_use_tso == 0) &&
12287 		    (len > maxseg)) {
12288 			len = maxseg;
12289 			more_to_rxt = 1;
12290 		}
12291 		sb_offset = rsm->r_start - tp->snd_una;
12292 		if (len > 0) {
12293 			sack_rxmit = 1;
12294 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12295 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12296 			    min(len, maxseg));
12297 		} else {
12298 			/* I dont think this can happen */
12299 			rsm = NULL;
12300 			goto recheck_resend;
12301 		}
12302 		BBR_STAT_INC(bbr_resends_set);
12303 	} else if (bbr->r_ctl.rc_tlp_send) {
12304 		/*
12305 		 * Tail loss probe
12306 		 */
12307 		doing_tlp = 1;
12308 		rsm = bbr->r_ctl.rc_tlp_send;
12309 		bbr->r_ctl.rc_tlp_send = NULL;
12310 		sack_rxmit = 1;
12311 		len = rsm->r_end - rsm->r_start;
12312 		rtr_cnt++;
12313 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12314 			len = maxseg;
12315 
12316 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12317 #ifdef BBR_INVARIANTS
12318 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12319 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12320 #else
12321 			/* TSNH */
12322 			rsm = NULL;
12323 			goto recheck_resend;
12324 #endif
12325 		}
12326 		sb_offset = rsm->r_start - tp->snd_una;
12327 		BBR_STAT_INC(bbr_tlp_set);
12328 	}
12329 	/*
12330 	 * Enforce a connection sendmap count limit if set
12331 	 * as long as we are not retransmiting.
12332 	 */
12333 	if ((rsm == NULL) &&
12334 	    (V_tcp_map_entries_limit > 0) &&
12335 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12336 		BBR_STAT_INC(bbr_alloc_limited);
12337 		if (!bbr->alloc_limit_reported) {
12338 			bbr->alloc_limit_reported = 1;
12339 			BBR_STAT_INC(bbr_alloc_limited_conns);
12340 		}
12341 		goto just_return_nolock;
12342 	}
12343 #ifdef BBR_INVARIANTS
12344 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12345 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12346 		    tp, bbr, rsm, sb_offset, len);
12347 	}
12348 #endif
12349 	/*
12350 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12351 	 * state flags.
12352 	 */
12353 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12354 		flags |= TH_FIN;
12355 	if (tp->t_flags & TF_NEEDSYN)
12356 		flags |= TH_SYN;
12357 
12358 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12359 		/* we are retransmitting the fin */
12360 		len--;
12361 		if (len) {
12362 			/*
12363 			 * When retransmitting data do *not* include the
12364 			 * FIN. This could happen from a TLP probe if we
12365 			 * allowed data with a FIN.
12366 			 */
12367 			flags &= ~TH_FIN;
12368 		}
12369 	} else if (rsm) {
12370 		if (flags & TH_FIN)
12371 			flags &= ~TH_FIN;
12372 	}
12373 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12374 		void *end_rsm;
12375 
12376 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12377 		if (end_rsm)
12378 			kern_prefetch(end_rsm, &prefetch_rsm);
12379 		prefetch_rsm = 1;
12380 	}
12381 	SOCKBUF_LOCK(sb);
12382 	/*
12383 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12384 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12385 	 * negative length.  This can also occur when TCP opens up its
12386 	 * congestion window while receiving additional duplicate acks after
12387 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12388 	 * the fast-retransmit.
12389 	 *
12390 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12391 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12392 	 * up 0.
12393 	 *
12394 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12395 	 * in which case len is already set.
12396 	 */
12397 	if (sack_rxmit == 0) {
12398 		uint32_t avail;
12399 
12400 		avail = sbavail(sb);
12401 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12402 			sb_offset = tp->snd_max - tp->snd_una;
12403 		else
12404 			sb_offset = 0;
12405 		if (bbr->rc_tlp_new_data) {
12406 			/* TLP is forcing out new data */
12407 			uint32_t tlplen;
12408 
12409 			doing_tlp = 1;
12410 			tlplen = maxseg;
12411 
12412 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12413 				tlplen = (uint32_t)(avail - sb_offset);
12414 			}
12415 			if (tlplen > tp->snd_wnd) {
12416 				len = tp->snd_wnd;
12417 			} else {
12418 				len = tlplen;
12419 			}
12420 			bbr->rc_tlp_new_data = 0;
12421 		} else {
12422 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12423 			if ((len < p_maxseg) &&
12424 			    (bbr->rc_in_persist == 0) &&
12425 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12426 			    ((avail - sb_offset) >= p_maxseg)) {
12427 				/*
12428 				 * We are not completing whats in the socket
12429 				 * buffer (i.e. there is at least a segment
12430 				 * waiting to send) and we have 2 or more
12431 				 * segments outstanding. There is no sense
12432 				 * of sending a little piece. Lets defer and
12433 				 * and wait until we can send a whole
12434 				 * segment.
12435 				 */
12436 				len = 0;
12437 			}
12438 			if (bbr->rc_in_persist) {
12439 				/*
12440 				 * We are in persists, figure out if
12441 				 * a retransmit is available (maybe the previous
12442 				 * persists we sent) or if we have to send new
12443 				 * data.
12444 				 */
12445 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12446 				if (rsm) {
12447 					len = rsm->r_end - rsm->r_start;
12448 					if (rsm->r_flags & BBR_HAS_FIN)
12449 						len--;
12450 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12451 						len = maxseg;
12452 					if (len > 1)
12453 						BBR_STAT_INC(bbr_persist_reneg);
12454 					/*
12455 					 * XXXrrs we could force the len to
12456 					 * 1 byte here to cause the chunk to
12457 					 * split apart.. but that would then
12458 					 * mean we always retransmit it as
12459 					 * one byte even after the window
12460 					 * opens.
12461 					 */
12462 					sack_rxmit = 1;
12463 					sb_offset = rsm->r_start - tp->snd_una;
12464 				} else {
12465 					/*
12466 					 * First time through in persists or peer
12467 					 * acked our one byte. Though we do have
12468 					 * to have something in the sb.
12469 					 */
12470 					len = 1;
12471 					sb_offset = 0;
12472 					if (avail == 0)
12473 					    len = 0;
12474 				}
12475 			}
12476 		}
12477 	}
12478 	if (prefetch_so_done == 0) {
12479 		kern_prefetch(so, &prefetch_so_done);
12480 		prefetch_so_done = 1;
12481 	}
12482 	/*
12483 	 * Lop off SYN bit if it has already been sent.  However, if this is
12484 	 * SYN-SENT state and if segment contains data and if we don't know
12485 	 * that foreign host supports TAO, suppress sending segment.
12486 	 */
12487 	if ((flags & TH_SYN) && (rsm == NULL) &&
12488 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12489 		if (tp->t_state != TCPS_SYN_RECEIVED)
12490 			flags &= ~TH_SYN;
12491 		/*
12492 		 * When sending additional segments following a TFO SYN|ACK,
12493 		 * do not include the SYN bit.
12494 		 */
12495 		if (IS_FASTOPEN(tp->t_flags) &&
12496 		    (tp->t_state == TCPS_SYN_RECEIVED))
12497 			flags &= ~TH_SYN;
12498 		sb_offset--, len++;
12499 		if (sbavail(sb) == 0)
12500 			len = 0;
12501 	} else if ((flags & TH_SYN) && rsm) {
12502 		/*
12503 		 * Subtract one from the len for the SYN being
12504 		 * retransmitted.
12505 		 */
12506 		len--;
12507 	}
12508 	/*
12509 	 * Be careful not to send data and/or FIN on SYN segments. This
12510 	 * measure is needed to prevent interoperability problems with not
12511 	 * fully conformant TCP implementations.
12512 	 */
12513 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12514 		len = 0;
12515 		flags &= ~TH_FIN;
12516 	}
12517 	/*
12518 	 * On TFO sockets, ensure no data is sent in the following cases:
12519 	 *
12520 	 *  - When retransmitting SYN|ACK on a passively-created socket
12521 	 *  - When retransmitting SYN on an actively created socket
12522 	 *  - When sending a zero-length cookie (cookie request) on an
12523 	 *    actively created socket
12524 	 *  - When the socket is in the CLOSED state (RST is being sent)
12525 	 */
12526 	if (IS_FASTOPEN(tp->t_flags) &&
12527 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12528 	     ((tp->t_state == TCPS_SYN_SENT) &&
12529 	      (tp->t_tfo_client_cookie_len == 0)) ||
12530 	     (flags & TH_RST))) {
12531 		len = 0;
12532 		sack_rxmit = 0;
12533 		rsm = NULL;
12534 	}
12535 	/* Without fast-open there should never be data sent on a SYN */
12536 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12537 		len = 0;
12538 	if (len <= 0) {
12539 		/*
12540 		 * If FIN has been sent but not acked, but we haven't been
12541 		 * called to retransmit, len will be < 0.  Otherwise, window
12542 		 * shrank after we sent into it.  If window shrank to 0,
12543 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12544 		 * window, and set the persist timer if it isn't already
12545 		 * going.  If the window didn't close completely, just wait
12546 		 * for an ACK.
12547 		 *
12548 		 * We also do a general check here to ensure that we will
12549 		 * set the persist timer when we have data to send, but a
12550 		 * 0-byte window. This makes sure the persist timer is set
12551 		 * even if the packet hits one of the "goto send" lines
12552 		 * below.
12553 		 */
12554 		len = 0;
12555 		if ((tp->snd_wnd == 0) &&
12556 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12557 		    (tp->snd_una == tp->snd_max) &&
12558 		    (sb_offset < (int)sbavail(sb))) {
12559 			/*
12560 			 * Not enough room in the rwnd to send
12561 			 * a paced segment out.
12562 			 */
12563 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12564 		}
12565 	} else if ((rsm == NULL) &&
12566 		   (doing_tlp == 0) &&
12567 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12568 		/*
12569 		 * We are not sending a full segment for
12570 		 * some reason. Should we not send anything (think
12571 		 * sws or persists)?
12572 		 */
12573 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12574 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12575 		    (len < (int)(sbavail(sb) - sb_offset))) {
12576 			/*
12577 			 * Here the rwnd is less than
12578 			 * the pacing size, this is not a retransmit,
12579 			 * we are established and
12580 			 * the send is not the last in the socket buffer
12581 			 * lets not send, and possibly enter persists.
12582 			 */
12583 			len = 0;
12584 			if (tp->snd_max == tp->snd_una)
12585 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12586 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12587 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12588 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12589 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12590 			   (len < bbr_minseg(bbr))) {
12591 			/*
12592 			 * Here we are not retransmitting, and
12593 			 * the cwnd is not so small that we could
12594 			 * not send at least a min size (rxt timer
12595 			 * not having gone off), We have 2 segments or
12596 			 * more already in flight, its not the tail end
12597 			 * of the socket buffer  and the cwnd is blocking
12598 			 * us from sending out minimum pacing segment size.
12599 			 * Lets not send anything.
12600 			 */
12601 			bbr->rc_cwnd_limited = 1;
12602 			len = 0;
12603 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12604 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12605 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12606 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12607 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12608 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12609 			/*
12610 			 * Here we have a send window but we have
12611 			 * filled it up and we can't send another pacing segment.
12612 			 * We also have in flight more than 2 segments
12613 			 * and we are not completing the sb i.e. we allow
12614 			 * the last bytes of the sb to go out even if
12615 			 * its not a full pacing segment.
12616 			 */
12617 			len = 0;
12618 		}
12619 	}
12620 	/* len will be >= 0 after this point. */
12621 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12622 	tcp_sndbuf_autoscale(tp, so, sendwin);
12623 	/*
12624 	 *
12625 	 */
12626 	if (bbr->rc_in_persist &&
12627 	    len &&
12628 	    (rsm == NULL) &&
12629 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12630 		/*
12631 		 * We are in persist, not doing a retransmit and don't have enough space
12632 		 * yet to send a full TSO. So is it at the end of the sb
12633 		 * if so we need to send else nuke to 0 and don't send.
12634 		 */
12635 		int sbleft;
12636 		if (sbavail(sb) > sb_offset)
12637 			sbleft = sbavail(sb) - sb_offset;
12638 		else
12639 			sbleft = 0;
12640 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12641 			/* not at end of sb lets not send */
12642 			len = 0;
12643 		}
12644 	}
12645 	/*
12646 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12647 	 * hardware).
12648 	 *
12649 	 * TSO may only be used if we are in a pure bulk sending state.  The
12650 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12651 	 * options prevent using TSO.  With TSO the TCP header is the same
12652 	 * (except for the sequence number) for all generated packets.  This
12653 	 * makes it impossible to transmit any options which vary per
12654 	 * generated segment or packet.
12655 	 *
12656 	 * IPv4 handling has a clear separation of ip options and ip header
12657 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12658 	 * does the right thing below to provide length of just ip options
12659 	 * and thus checking for ipoptlen is enough to decide if ip options
12660 	 * are present.
12661 	 */
12662 #ifdef INET6
12663 	if (isipv6)
12664 		ipoptlen = ip6_optlen(inp);
12665 	else
12666 #endif
12667 	if (inp->inp_options)
12668 		ipoptlen = inp->inp_options->m_len -
12669 		    offsetof(struct ipoption, ipopt_list);
12670 	else
12671 		ipoptlen = 0;
12672 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12673 	/*
12674 	 * Pre-calculate here as we save another lookup into the darknesses
12675 	 * of IPsec that way and can actually decide if TSO is ok.
12676 	 */
12677 #ifdef INET6
12678 	if (isipv6 && IPSEC_ENABLED(ipv6))
12679 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12680 #ifdef INET
12681 	else
12682 #endif
12683 #endif				/* INET6 */
12684 #ifdef INET
12685 	if (IPSEC_ENABLED(ipv4))
12686 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12687 #endif				/* INET */
12688 #endif				/* IPSEC */
12689 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12690 	ipoptlen += ipsec_optlen;
12691 #endif
12692 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12693 	    (len > maxseg) &&
12694 	    (tp->t_port == 0) &&
12695 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12696 	    tp->rcv_numsacks == 0 &&
12697 	    ipoptlen == 0)
12698 		tso = 1;
12699 
12700 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12701 	    (long)TCP_MAXWIN << tp->rcv_scale);
12702 	/*
12703 	 * Sender silly window avoidance.   We transmit under the following
12704 	 * conditions when len is non-zero:
12705 	 *
12706 	 * - We have a full segment (or more with TSO) - This is the last
12707 	 * buffer in a write()/send() and we are either idle or running
12708 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12709 	 * then 1/2 the maximum send window's worth of data (receiver may be
12710 	 * limited the window size) - we need to retransmit
12711 	 */
12712 	if (rsm)
12713 		goto send;
12714 	if (len) {
12715 		if (sack_rxmit)
12716 			goto send;
12717 		if (len >= p_maxseg)
12718 			goto send;
12719 		/*
12720 		 * NOTE! on localhost connections an 'ack' from the remote
12721 		 * end may occur synchronously with the output and cause us
12722 		 * to flush a buffer queued with moretocome.  XXX
12723 		 *
12724 		 */
12725 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12726 		    ((tp->t_flags & TF_NODELAY) ||
12727 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12728 		    (tp->t_flags & TF_NOPUSH) == 0) {
12729 			goto send;
12730 		}
12731 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12732 			goto send;
12733 		}
12734 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12735 			goto send;
12736 		}
12737 	}
12738 	/*
12739 	 * Sending of standalone window updates.
12740 	 *
12741 	 * Window updates are important when we close our window due to a
12742 	 * full socket buffer and are opening it again after the application
12743 	 * reads data from it.  Once the window has opened again and the
12744 	 * remote end starts to send again the ACK clock takes over and
12745 	 * provides the most current window information.
12746 	 *
12747 	 * We must avoid the silly window syndrome whereas every read from
12748 	 * the receive buffer, no matter how small, causes a window update
12749 	 * to be sent.  We also should avoid sending a flurry of window
12750 	 * updates when the socket buffer had queued a lot of data and the
12751 	 * application is doing small reads.
12752 	 *
12753 	 * Prevent a flurry of pointless window updates by only sending an
12754 	 * update when we can increase the advertized window by more than
12755 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12756 	 * full or is very small be more aggressive and send an update
12757 	 * whenever we can increase by two mss sized segments. In all other
12758 	 * situations the ACK's to new incoming data will carry further
12759 	 * window increases.
12760 	 *
12761 	 * Don't send an independent window update if a delayed ACK is
12762 	 * pending (it will get piggy-backed on it) or the remote side
12763 	 * already has done a half-close and won't send more data.  Skip
12764 	 * this if the connection is in T/TCP half-open state.
12765 	 */
12766 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12767 	    !(tp->t_flags & TF_DELACK) &&
12768 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12769 		/* Check to see if we should do a window update */
12770 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12771 			goto send;
12772 	}
12773 	/*
12774 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12775 	 * is also a catch-all for the retransmit timer timeout case.
12776 	 */
12777 	if (tp->t_flags & TF_ACKNOW) {
12778 		goto send;
12779 	}
12780 	if (flags & TH_RST) {
12781 		/* Always send a RST if one is due */
12782 		goto send;
12783 	}
12784 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12785 		goto send;
12786 	}
12787 	/*
12788 	 * If our state indicates that FIN should be sent and we have not
12789 	 * yet done so, then we need to send.
12790 	 */
12791 	if (flags & TH_FIN &&
12792 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12793 		goto send;
12794 	}
12795 	/*
12796 	 * No reason to send a segment, just return.
12797 	 */
12798 just_return:
12799 	SOCKBUF_UNLOCK(sb);
12800 just_return_nolock:
12801 	if (tot_len)
12802 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12803 	if (bbr->rc_no_pacing)
12804 		slot = 0;
12805 	if (tot_len == 0) {
12806 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12807 		    tp->snd_wnd) {
12808 			BBR_STAT_INC(bbr_rwnd_limited);
12809 			app_limited = BBR_JR_RWND_LIMITED;
12810 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12811 			if ((bbr->rc_in_persist == 0) &&
12812 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12813 			    (tp->snd_max == tp->snd_una) &&
12814 			    sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
12815 				/* No send window.. we must enter persist */
12816 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12817 			}
12818 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12819 			BBR_STAT_INC(bbr_app_limited);
12820 			app_limited = BBR_JR_APP_LIMITED;
12821 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12822 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12823 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12824 			BBR_STAT_INC(bbr_cwnd_limited);
12825  			app_limited = BBR_JR_CWND_LIMITED;
12826 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12827 									bbr->r_ctl.rc_lost_bytes)));
12828 			bbr->rc_cwnd_limited = 1;
12829 		} else {
12830 			BBR_STAT_INC(bbr_app_limited);
12831 			app_limited = BBR_JR_APP_LIMITED;
12832 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12833 		}
12834 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12835 		bbr->r_agg_early_set = 0;
12836 		bbr->r_ctl.rc_agg_early = 0;
12837 		bbr->r_ctl.rc_last_delay_val = 0;
12838 	} else if (bbr->rc_use_google == 0)
12839 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12840 	/* Are we app limited? */
12841 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12842 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12843 		/**
12844 		 * We are application limited.
12845 		 */
12846 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12847 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12848 	}
12849 	if (tot_len == 0)
12850 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12851 	/* Dont update the time if we did not send */
12852 	bbr->r_ctl.rc_last_delay_val = 0;
12853 	bbr->rc_output_starts_timer = 1;
12854 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12855 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12856 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12857 		/* Make sure snd_nxt is drug up */
12858 		tp->snd_nxt = tp->snd_max;
12859 	}
12860 	return (error);
12861 
12862 send:
12863 	if (doing_tlp == 0) {
12864 		/*
12865 		 * Data not a TLP, and its not the rxt firing. If it is the
12866 		 * rxt firing, we want to leave the tlp_in_progress flag on
12867 		 * so we don't send another TLP. It has to be a rack timer
12868 		 * or normal send (response to acked data) to clear the tlp
12869 		 * in progress flag.
12870 		 */
12871 		bbr->rc_tlp_in_progress = 0;
12872 		bbr->rc_tlp_rtx_out = 0;
12873 	} else {
12874 		/*
12875 		 * Its a TLP.
12876 		 */
12877 		bbr->rc_tlp_in_progress = 1;
12878 	}
12879 	bbr_timer_cancel(bbr, __LINE__, cts);
12880 	if (rsm == NULL) {
12881 		if (sbused(sb) > 0) {
12882 			/*
12883 			 * This is sub-optimal. We only send a stand alone
12884 			 * FIN on its own segment.
12885 			 */
12886 			if (flags & TH_FIN) {
12887 				flags &= ~TH_FIN;
12888 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12889 					/* Lets not send this */
12890 					slot = 0;
12891 					goto just_return;
12892 				}
12893 			}
12894 		}
12895 	} else {
12896 		/*
12897 		 * We do *not* send a FIN on a retransmit if it has data.
12898 		 * The if clause here where len > 1 should never come true.
12899 		 */
12900 		if ((len > 0) &&
12901 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12902 		    (flags & TH_FIN))) {
12903 			flags &= ~TH_FIN;
12904 			len--;
12905 		}
12906 	}
12907 	SOCKBUF_LOCK_ASSERT(sb);
12908 	if (len > 0) {
12909 		if ((tp->snd_una == tp->snd_max) &&
12910 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12911 			/*
12912 			 * This qualifies as a RTT_PROBE session since we
12913 			 * drop the data outstanding to nothing and waited
12914 			 * more than bbr_rtt_probe_time.
12915 			 */
12916 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12917 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12918 		}
12919 		if (len >= maxseg)
12920 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12921 		else
12922 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12923 	}
12924 	/*
12925 	 * Before ESTABLISHED, force sending of initial options unless TCP
12926 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12927 	 * plus TCP options always fit in a single mbuf, leaving room for a
12928 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12929 	 * + optlen <= MCLBYTES
12930 	 */
12931 	optlen = 0;
12932 #ifdef INET6
12933 	if (isipv6)
12934 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12935 	else
12936 #endif
12937 		hdrlen = sizeof(struct tcpiphdr);
12938 
12939 	/*
12940 	 * Compute options for segment. We only have to care about SYN and
12941 	 * established connection segments.  Options for SYN-ACK segments
12942 	 * are handled in TCP syncache.
12943 	 */
12944 	to.to_flags = 0;
12945 	local_options = 0;
12946 	if ((tp->t_flags & TF_NOOPT) == 0) {
12947 		/* Maximum segment size. */
12948 		if (flags & TH_SYN) {
12949 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12950 			if (tp->t_port)
12951 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12952 			to.to_flags |= TOF_MSS;
12953 			/*
12954 			 * On SYN or SYN|ACK transmits on TFO connections,
12955 			 * only include the TFO option if it is not a
12956 			 * retransmit, as the presence of the TFO option may
12957 			 * have caused the original SYN or SYN|ACK to have
12958 			 * been dropped by a middlebox.
12959 			 */
12960 			if (IS_FASTOPEN(tp->t_flags) &&
12961 			    (tp->t_rxtshift == 0)) {
12962 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12963 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12964 					to.to_tfo_cookie =
12965 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12966 					to.to_flags |= TOF_FASTOPEN;
12967 					wanted_cookie = 1;
12968 				} else if (tp->t_state == TCPS_SYN_SENT) {
12969 					to.to_tfo_len =
12970 					    tp->t_tfo_client_cookie_len;
12971 					to.to_tfo_cookie =
12972 					    tp->t_tfo_cookie.client;
12973 					to.to_flags |= TOF_FASTOPEN;
12974 					wanted_cookie = 1;
12975 				}
12976 			}
12977 		}
12978 		/* Window scaling. */
12979 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12980 			to.to_wscale = tp->request_r_scale;
12981 			to.to_flags |= TOF_SCALE;
12982 		}
12983 		/* Timestamps. */
12984 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12985 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12986 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12987 			to.to_tsecr = tp->ts_recent;
12988 			to.to_flags |= TOF_TS;
12989 			local_options += TCPOLEN_TIMESTAMP + 2;
12990 		}
12991 		/* Set receive buffer autosizing timestamp. */
12992 		if (tp->rfbuf_ts == 0 &&
12993 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12994 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12995 		/* Selective ACK's. */
12996 		if (flags & TH_SYN)
12997 			to.to_flags |= TOF_SACKPERM;
12998 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12999 		    tp->rcv_numsacks > 0) {
13000 			to.to_flags |= TOF_SACK;
13001 			to.to_nsacks = tp->rcv_numsacks;
13002 			to.to_sacks = (u_char *)tp->sackblks;
13003 		}
13004 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13005 		/* TCP-MD5 (RFC2385). */
13006 		if (tp->t_flags & TF_SIGNATURE)
13007 			to.to_flags |= TOF_SIGNATURE;
13008 #endif				/* TCP_SIGNATURE */
13009 
13010 		/* Processing the options. */
13011 		hdrlen += (optlen = tcp_addoptions(&to, opt));
13012 		/*
13013 		 * If we wanted a TFO option to be added, but it was unable
13014 		 * to fit, ensure no data is sent.
13015 		 */
13016 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13017 		    !(to.to_flags & TOF_FASTOPEN))
13018 			len = 0;
13019 	}
13020 	if (tp->t_port) {
13021 		if (V_tcp_udp_tunneling_port == 0) {
13022 			/* The port was removed?? */
13023 			SOCKBUF_UNLOCK(&so->so_snd);
13024 			return (EHOSTUNREACH);
13025 		}
13026 		hdrlen += sizeof(struct udphdr);
13027 	}
13028 #ifdef INET6
13029 	if (isipv6)
13030 		ipoptlen = ip6_optlen(tp->t_inpcb);
13031 	else
13032 #endif
13033 	if (tp->t_inpcb->inp_options)
13034 		ipoptlen = tp->t_inpcb->inp_options->m_len -
13035 		    offsetof(struct ipoption, ipopt_list);
13036 	else
13037 		ipoptlen = 0;
13038 	ipoptlen = 0;
13039 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13040 	ipoptlen += ipsec_optlen;
13041 #endif
13042 	if (bbr->rc_last_options != local_options) {
13043 		/*
13044 		 * Cache the options length this generally does not change
13045 		 * on a connection. We use this to calculate TSO.
13046 		 */
13047 		bbr->rc_last_options = local_options;
13048 	}
13049 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
13050 	p_maxseg = min(maxseg, pace_max_segs);
13051 	/*
13052 	 * Adjust data length if insertion of options will bump the packet
13053 	 * length beyond the t_maxseg length. Clear the FIN bit because we
13054 	 * cut off the tail of the segment.
13055 	 */
13056 	if (len > maxseg) {
13057 		if (len != 0 && (flags & TH_FIN)) {
13058 			flags &= ~TH_FIN;
13059 		}
13060 		if (tso) {
13061 			uint32_t moff;
13062 			int32_t max_len;
13063 
13064 			/* extract TSO information */
13065 			if_hw_tsomax = tp->t_tsomax;
13066 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13067 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13068 			KASSERT(ipoptlen == 0,
13069 			    ("%s: TSO can't do IP options", __func__));
13070 
13071 			/*
13072 			 * Check if we should limit by maximum payload
13073 			 * length:
13074 			 */
13075 			if (if_hw_tsomax != 0) {
13076 				/* compute maximum TSO length */
13077 				max_len = (if_hw_tsomax - hdrlen -
13078 				    max_linkhdr);
13079 				if (max_len <= 0) {
13080 					len = 0;
13081 				} else if (len > max_len) {
13082 					len = max_len;
13083 				}
13084 			}
13085 			/*
13086 			 * Prevent the last segment from being fractional
13087 			 * unless the send sockbuf can be emptied:
13088 			 */
13089 			if ((sb_offset + len) < sbavail(sb)) {
13090 				moff = len % (uint32_t)maxseg;
13091 				if (moff != 0) {
13092 					len -= moff;
13093 				}
13094 			}
13095 			/*
13096 			 * In case there are too many small fragments don't
13097 			 * use TSO:
13098 			 */
13099 			if (len <= maxseg) {
13100 				len = maxseg;
13101 				tso = 0;
13102 			}
13103 		} else {
13104 			/* Not doing TSO */
13105 			if (optlen + ipoptlen >= tp->t_maxseg) {
13106 				/*
13107 				 * Since we don't have enough space to put
13108 				 * the IP header chain and the TCP header in
13109 				 * one packet as required by RFC 7112, don't
13110 				 * send it. Also ensure that at least one
13111 				 * byte of the payload can be put into the
13112 				 * TCP segment.
13113 				 */
13114 				SOCKBUF_UNLOCK(&so->so_snd);
13115 				error = EMSGSIZE;
13116 				sack_rxmit = 0;
13117 				goto out;
13118 			}
13119 			len = maxseg;
13120 		}
13121 	} else {
13122 		/* Not doing TSO */
13123 		if_hw_tsomaxsegcount = 0;
13124 		tso = 0;
13125 	}
13126 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13127 	    ("%s: len > IP_MAXPACKET", __func__));
13128 #ifdef DIAGNOSTIC
13129 #ifdef INET6
13130 	if (max_linkhdr + hdrlen > MCLBYTES)
13131 #else
13132 	if (max_linkhdr + hdrlen > MHLEN)
13133 #endif
13134 		panic("tcphdr too big");
13135 #endif
13136 	/*
13137 	 * This KASSERT is here to catch edge cases at a well defined place.
13138 	 * Before, those had triggered (random) panic conditions further
13139 	 * down.
13140 	 */
13141 #ifdef BBR_INVARIANTS
13142 	if (sack_rxmit) {
13143 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13144 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13145 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13146 		}
13147 	}
13148 #endif
13149 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13150 	if ((len == 0) &&
13151 	    (flags & TH_FIN) &&
13152 	    (sbused(sb))) {
13153 		/*
13154 		 * We have outstanding data, don't send a fin by itself!.
13155 		 */
13156 		slot = 0;
13157 		goto just_return;
13158 	}
13159 	/*
13160 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13161 	 * and initialize the header from the template for sends on this
13162 	 * connection.
13163 	 */
13164 	if (len) {
13165 		uint32_t moff;
13166 
13167 		/*
13168 		 * We place a limit on sending with hptsi.
13169 		 */
13170 		if ((rsm == NULL) && len > pace_max_segs)
13171 			len = pace_max_segs;
13172 		if (len <= maxseg)
13173 			tso = 0;
13174 #ifdef INET6
13175 		if (MHLEN < hdrlen + max_linkhdr)
13176 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13177 		else
13178 #endif
13179 			m = m_gethdr(M_NOWAIT, MT_DATA);
13180 
13181 		if (m == NULL) {
13182 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13183 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13184 			SOCKBUF_UNLOCK(sb);
13185 			error = ENOBUFS;
13186 			sack_rxmit = 0;
13187 			goto out;
13188 		}
13189 		m->m_data += max_linkhdr;
13190 		m->m_len = hdrlen;
13191 		/*
13192 		 * Start the m_copy functions from the closest mbuf to the
13193 		 * sb_offset in the socket buffer chain.
13194 		 */
13195 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13196 #ifdef BBR_INVARIANTS
13197 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13198 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13199 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13200 				    doing_retran_from,
13201 				    picked_up_retran,
13202 				    doing_tlp);
13203 
13204 #endif
13205 			/*
13206 			 * In this messed up situation we have two choices,
13207 			 * a) pretend the send worked, and just start timers
13208 			 * and what not (not good since that may lead us
13209 			 * back here a lot). <or> b) Send the lowest segment
13210 			 * in the map. <or> c) Drop the connection. Lets do
13211 			 * <b> which if it continues to happen will lead to
13212 			 * <c> via timeouts.
13213 			 */
13214 			BBR_STAT_INC(bbr_offset_recovery);
13215 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13216 			sb_offset = 0;
13217 			if (rsm == NULL) {
13218 				sack_rxmit = 0;
13219 				len = sbavail(sb);
13220 			} else {
13221 				sack_rxmit = 1;
13222 				if (rsm->r_start != tp->snd_una) {
13223 					/*
13224 					 * Things are really messed up, <c>
13225 					 * is the only thing to do.
13226 					 */
13227 					BBR_STAT_INC(bbr_offset_drop);
13228 					SOCKBUF_UNLOCK(sb);
13229 					(void)m_free(m);
13230 					return (-EFAULT); /* tcp_drop() */
13231 				}
13232 				len = rsm->r_end - rsm->r_start;
13233 			}
13234 			if (len > sbavail(sb))
13235 				len = sbavail(sb);
13236 			if (len > maxseg)
13237 				len = maxseg;
13238 		}
13239 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13240 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13241 			m_copydata(mb, moff, (int)len,
13242 			    mtod(m, caddr_t)+hdrlen);
13243 			if (rsm == NULL)
13244 				sbsndptr_adv(sb, mb, len);
13245 			m->m_len += len;
13246 		} else {
13247 			struct sockbuf *msb;
13248 
13249 			if (rsm)
13250 				msb = NULL;
13251 			else
13252 				msb = sb;
13253 #ifdef BBR_INVARIANTS
13254 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13255 				if (rsm) {
13256 					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 ",
13257 					    tp, bbr, len, moff,
13258 					    sbavail(sb), rsm,
13259 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13260 					    doing_retran_from,
13261 					    picked_up_retran,
13262 					    doing_tlp, sack_rxmit);
13263 				} else {
13264 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13265 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13266 				}
13267 			}
13268 #endif
13269 			m->m_next = tcp_m_copym(
13270 				mb, moff, &len,
13271 				if_hw_tsomaxsegcount,
13272 				if_hw_tsomaxsegsize, msb,
13273 				((rsm == NULL) ? hw_tls : 0)
13274 #ifdef NETFLIX_COPY_ARGS
13275 				, &filled_all
13276 #endif
13277 				);
13278 			if (len <= maxseg) {
13279 				/*
13280 				 * Must have ran out of mbufs for the copy
13281 				 * shorten it to no longer need tso. Lets
13282 				 * not put on sendalot since we are low on
13283 				 * mbufs.
13284 				 */
13285 				tso = 0;
13286 			}
13287 			if (m->m_next == NULL) {
13288 				SOCKBUF_UNLOCK(sb);
13289 				(void)m_free(m);
13290 				error = ENOBUFS;
13291 				sack_rxmit = 0;
13292 				goto out;
13293 			}
13294 		}
13295 #ifdef BBR_INVARIANTS
13296 		if (tso && len < maxseg) {
13297 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13298 			    tp, len, maxseg);
13299 		}
13300 		if (tso && if_hw_tsomaxsegcount) {
13301 			int32_t seg_cnt = 0;
13302 			struct mbuf *foo;
13303 
13304 			foo = m;
13305 			while (foo) {
13306 				seg_cnt++;
13307 				foo = foo->m_next;
13308 			}
13309 			if (seg_cnt > if_hw_tsomaxsegcount) {
13310 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13311 			}
13312 		}
13313 #endif
13314 		/*
13315 		 * If we're sending everything we've got, set PUSH. (This
13316 		 * will keep happy those implementations which only give
13317 		 * data to the user when a buffer fills or a PUSH comes in.)
13318 		 */
13319 		if (sb_offset + len == sbused(sb) &&
13320 		    sbused(sb) &&
13321 		    !(flags & TH_SYN)) {
13322 			flags |= TH_PUSH;
13323 		}
13324 		SOCKBUF_UNLOCK(sb);
13325 	} else {
13326 		SOCKBUF_UNLOCK(sb);
13327 		if (tp->t_flags & TF_ACKNOW)
13328 			KMOD_TCPSTAT_INC(tcps_sndacks);
13329 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13330 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13331 		else
13332 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13333 
13334 		m = m_gethdr(M_NOWAIT, MT_DATA);
13335 		if (m == NULL) {
13336 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13337 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13338 			error = ENOBUFS;
13339 			/* Fudge the send time since we could not send */
13340 			sack_rxmit = 0;
13341 			goto out;
13342 		}
13343 #ifdef INET6
13344 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13345 		    MHLEN >= hdrlen) {
13346 			M_ALIGN(m, hdrlen);
13347 		} else
13348 #endif
13349 			m->m_data += max_linkhdr;
13350 		m->m_len = hdrlen;
13351 	}
13352 	SOCKBUF_UNLOCK_ASSERT(sb);
13353 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13354 #ifdef MAC
13355 	mac_inpcb_create_mbuf(inp, m);
13356 #endif
13357 #ifdef INET6
13358 	if (isipv6) {
13359 		ip6 = mtod(m, struct ip6_hdr *);
13360 		if (tp->t_port) {
13361 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13362 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13363 			udp->uh_dport = tp->t_port;
13364 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13365 			udp->uh_ulen = htons(ulen);
13366 			th = (struct tcphdr *)(udp + 1);
13367 		} else {
13368 			th = (struct tcphdr *)(ip6 + 1);
13369 		}
13370 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13371 	} else
13372 #endif				/* INET6 */
13373 	{
13374 		ip = mtod(m, struct ip *);
13375 #ifdef TCPDEBUG
13376 		ipov = (struct ipovly *)ip;
13377 #endif
13378 		if (tp->t_port) {
13379 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13380 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13381 			udp->uh_dport = tp->t_port;
13382 			ulen = hdrlen + len - sizeof(struct ip);
13383 			udp->uh_ulen = htons(ulen);
13384 			th = (struct tcphdr *)(udp + 1);
13385 		} else {
13386 			th = (struct tcphdr *)(ip + 1);
13387 		}
13388 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13389 	}
13390 	/*
13391 	 * If we are doing retransmissions, then snd_nxt will not reflect
13392 	 * the first unsent octet.  For ACK only packets, we do not want the
13393 	 * sequence number of the retransmitted packet, we want the sequence
13394 	 * number of the next unsent octet.  So, if there is no data (and no
13395 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13396 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13397 	 * one byte beyond the right edge of the window, so use snd_nxt in
13398 	 * that case, since we know we aren't doing a retransmission.
13399 	 * (retransmit and persist are mutually exclusive...)
13400 	 */
13401 	if (sack_rxmit == 0) {
13402 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13403 			/* New data (including new persists) */
13404 			th->th_seq = htonl(tp->snd_max);
13405 			bbr_seq = tp->snd_max;
13406 		} else if (flags & TH_SYN) {
13407 			/* Syn's always send from iss */
13408 			th->th_seq = htonl(tp->iss);
13409 			bbr_seq = tp->iss;
13410 		} else if (flags & TH_FIN) {
13411 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13412 				/*
13413 				 * If we sent the fin already its 1 minus
13414 				 * snd_max
13415 				 */
13416 				th->th_seq = (htonl(tp->snd_max - 1));
13417 				bbr_seq = (tp->snd_max - 1);
13418 			} else {
13419 				/* First time FIN use snd_max */
13420 				th->th_seq = htonl(tp->snd_max);
13421 				bbr_seq = tp->snd_max;
13422 			}
13423 		} else {
13424 			/*
13425 			 * len == 0 and not persist we use snd_max, sending
13426 			 * an ack unless we have sent the fin then its 1
13427 			 * minus.
13428 			 */
13429 			/*
13430 			 * XXXRRS Question if we are in persists and we have
13431 			 * nothing outstanding to send and we have not sent
13432 			 * a FIN, we will send an ACK. In such a case it
13433 			 * might be better to send (tp->snd_una - 1) which
13434 			 * would force the peer to ack.
13435 			 */
13436 			if (tp->t_flags & TF_SENTFIN) {
13437 				th->th_seq = htonl(tp->snd_max - 1);
13438 				bbr_seq = (tp->snd_max - 1);
13439 			} else {
13440 				th->th_seq = htonl(tp->snd_max);
13441 				bbr_seq = tp->snd_max;
13442 			}
13443 		}
13444 	} else {
13445 		/* All retransmits use the rsm to guide the send */
13446 		th->th_seq = htonl(rsm->r_start);
13447 		bbr_seq = rsm->r_start;
13448 	}
13449 	th->th_ack = htonl(tp->rcv_nxt);
13450 	if (optlen) {
13451 		bcopy(opt, th + 1, optlen);
13452 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13453 	}
13454 	th->th_flags = flags;
13455 	/*
13456 	 * Calculate receive window.  Don't shrink window, but avoid silly
13457 	 * window syndrome.
13458 	 */
13459 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13460 				  recwin < maxseg)))
13461 		recwin = 0;
13462 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13463 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13464 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13465 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13466 		recwin = TCP_MAXWIN << tp->rcv_scale;
13467 
13468 	/*
13469 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13470 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13471 	 * handled in syncache.
13472 	 */
13473 	if (flags & TH_SYN)
13474 		th->th_win = htons((u_short)
13475 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13476 	else {
13477 		/* Avoid shrinking window with window scaling. */
13478 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13479 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13480 	}
13481 	/*
13482 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13483 	 * window.  This may cause the remote transmitter to stall.  This
13484 	 * flag tells soreceive() to disable delayed acknowledgements when
13485 	 * draining the buffer.  This can occur if the receiver is
13486 	 * attempting to read more data than can be buffered prior to
13487 	 * transmitting on the connection.
13488 	 */
13489 	if (th->th_win == 0) {
13490 		tp->t_sndzerowin++;
13491 		tp->t_flags |= TF_RXWIN0SENT;
13492 	} else
13493 		tp->t_flags &= ~TF_RXWIN0SENT;
13494 	/*
13495 	 * We don't support urgent data, but drag along
13496 	 * the pointer in case of a stack switch.
13497 	 */
13498 	tp->snd_up = tp->snd_una;
13499 
13500 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13501 	if (to.to_flags & TOF_SIGNATURE) {
13502 		/*
13503 		 * Calculate MD5 signature and put it into the place
13504 		 * determined before. NOTE: since TCP options buffer doesn't
13505 		 * point into mbuf's data, calculate offset and use it.
13506 		 */
13507 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13508 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13509 			/*
13510 			 * Do not send segment if the calculation of MD5
13511 			 * digest has failed.
13512 			 */
13513 			goto out;
13514 		}
13515 	}
13516 #endif
13517 
13518 	/*
13519 	 * Put TCP length in extended header, and then checksum extended
13520 	 * header and data.
13521 	 */
13522 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13523 #ifdef INET6
13524 	if (isipv6) {
13525 		/*
13526 		 * ip6_plen is not need to be filled now, and will be filled
13527 		 * in ip6_output.
13528 		 */
13529 		if (tp->t_port) {
13530 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13531 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13532 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13533 			th->th_sum = htons(0);
13534 			UDPSTAT_INC(udps_opackets);
13535 		} else {
13536 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13537 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13538 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13539 			    optlen + len, IPPROTO_TCP, 0);
13540 		}
13541 	}
13542 #endif
13543 #if defined(INET6) && defined(INET)
13544 	else
13545 #endif
13546 #ifdef INET
13547 	{
13548 		if (tp->t_port) {
13549 			m->m_pkthdr.csum_flags = CSUM_UDP;
13550 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13551 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13552 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13553 			th->th_sum = htons(0);
13554 			UDPSTAT_INC(udps_opackets);
13555 		} else {
13556 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13557 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13558 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13559 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13560 			    IPPROTO_TCP + len + optlen));
13561 		}
13562 		/* IP version must be set here for ipv4/ipv6 checking later */
13563 		KASSERT(ip->ip_v == IPVERSION,
13564 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13565 	}
13566 #endif
13567 
13568 	/*
13569 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13570 	 * header checksum is always provided. XXX: Fixme: This is currently
13571 	 * not the case for IPv6.
13572 	 */
13573 	if (tso) {
13574 		KASSERT(len > maxseg,
13575 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13576 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13577 		csum_flags |= CSUM_TSO;
13578 		m->m_pkthdr.tso_segsz = maxseg;
13579 	}
13580 	KASSERT(len + hdrlen == m_length(m, NULL),
13581 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13582 	    __func__, len, hdrlen, m_length(m, NULL)));
13583 
13584 #ifdef TCP_HHOOK
13585 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13586 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13587 #endif
13588 #ifdef TCPDEBUG
13589 	/*
13590 	 * Trace.
13591 	 */
13592 	if (so->so_options & SO_DEBUG) {
13593 		u_short save = 0;
13594 
13595 #ifdef INET6
13596 		if (!isipv6)
13597 #endif
13598 		{
13599 			save = ipov->ih_len;
13600 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13601 			      * (th->th_off << 2) */ );
13602 		}
13603 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13604 #ifdef INET6
13605 		if (!isipv6)
13606 #endif
13607 			ipov->ih_len = save;
13608 	}
13609 #endif				/* TCPDEBUG */
13610 
13611 	/* Log to the black box */
13612 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13613 		union tcp_log_stackspecific log;
13614 
13615 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13616 		/* Record info on type of transmission */
13617 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13618 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13619 		log.u_bbr.flex3 = maxseg;
13620 		log.u_bbr.flex4 = delay_calc;
13621 		/* Encode filled_all into the upper flex5 bit */
13622 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13623 		log.u_bbr.flex5 <<= 1;
13624 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13625 		log.u_bbr.flex5 <<= 29;
13626 		if (filled_all)
13627 			log.u_bbr.flex5 |= 0x80000000;
13628 		log.u_bbr.flex5 |= tp->t_maxseg;
13629 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13630 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13631 		/* lets poke in the low and the high here for debugging */
13632 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13633 		if (rsm || sack_rxmit) {
13634 			if (doing_tlp)
13635 				log.u_bbr.flex8 = 2;
13636 			else
13637 				log.u_bbr.flex8 = 1;
13638 		} else {
13639 			log.u_bbr.flex8 = 0;
13640 		}
13641 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13642 		    len, &log, false, NULL, NULL, 0, tv);
13643 	} else {
13644 		lgb = NULL;
13645 	}
13646 	/*
13647 	 * Fill in IP length and desired time to live and send to IP level.
13648 	 * There should be a better way to handle ttl and tos; we could keep
13649 	 * them in the template, but need a way to checksum without them.
13650 	 */
13651 	/*
13652 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13653 	 * because in6_cksum() need it.
13654 	 */
13655 #ifdef INET6
13656 	if (isipv6) {
13657 		/*
13658 		 * we separately set hoplimit for every segment, since the
13659 		 * user might want to change the value via setsockopt. Also,
13660 		 * desired default hop limit might be changed via Neighbor
13661 		 * Discovery.
13662 		 */
13663 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13664 
13665 		/*
13666 		 * Set the packet size here for the benefit of DTrace
13667 		 * probes. ip6_output() will set it properly; it's supposed
13668 		 * to include the option header lengths as well.
13669 		 */
13670 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13671 
13672 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13673 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13674 		else
13675 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13676 
13677 		if (tp->t_state == TCPS_SYN_SENT)
13678 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13679 
13680 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13681 		/* TODO: IPv6 IP6TOS_ECT bit on */
13682 		error = ip6_output(m, inp->in6p_outputopts,
13683 		    &inp->inp_route6,
13684 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13685 		    NULL, NULL, inp);
13686 
13687 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13688 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13689 	}
13690 #endif				/* INET6 */
13691 #if defined(INET) && defined(INET6)
13692 	else
13693 #endif
13694 #ifdef INET
13695 	{
13696 		ip->ip_len = htons(m->m_pkthdr.len);
13697 #ifdef INET6
13698 		if (isipv6)
13699 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13700 #endif				/* INET6 */
13701 		/*
13702 		 * If we do path MTU discovery, then we set DF on every
13703 		 * packet. This might not be the best thing to do according
13704 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13705 		 * the problem so it affects only the first tcp connection
13706 		 * with a host.
13707 		 *
13708 		 * NB: Don't set DF on small MTU/MSS to have a safe
13709 		 * fallback.
13710 		 */
13711 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13712 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13713 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13714 				ip->ip_off |= htons(IP_DF);
13715 			}
13716 		} else {
13717 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13718 		}
13719 
13720 		if (tp->t_state == TCPS_SYN_SENT)
13721 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13722 
13723 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13724 
13725 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13726 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13727 		    inp);
13728 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13729 			mtu = inp->inp_route.ro_nh->nh_mtu;
13730 	}
13731 #endif				/* INET */
13732 out:
13733 
13734 	if (lgb) {
13735 		lgb->tlb_errno = error;
13736 		lgb = NULL;
13737 	}
13738 	/*
13739 	 * In transmit state, time the transmission and arrange for the
13740 	 * retransmit.  In persist state, just set snd_max.
13741 	 */
13742 	if (error == 0) {
13743 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13744 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13745 		    (tp->t_flags & TF_SACK_PERMIT) &&
13746 		    tp->rcv_numsacks > 0)
13747 			tcp_clean_dsack_blocks(tp);
13748 		/* We sent an ack clear the bbr_segs_rcvd count */
13749 		bbr->output_error_seen = 0;
13750 		bbr->oerror_cnt = 0;
13751 		bbr->bbr_segs_rcvd = 0;
13752 		if (len == 0)
13753 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13754 		/* Do accounting for new sends */
13755 		if ((len > 0) && (rsm == NULL)) {
13756 			int idx;
13757 			if (tp->snd_una == tp->snd_max) {
13758 				/*
13759 				 * Special case to match google, when
13760 				 * nothing is in flight the delivered
13761 				 * time does get updated to the current
13762 				 * time (see tcp_rate_bsd.c).
13763 				 */
13764 				bbr->r_ctl.rc_del_time = cts;
13765 			}
13766 			if (len >= maxseg) {
13767 				idx = (len / maxseg) + 3;
13768 				if (idx >= TCP_MSS_ACCT_ATIMER)
13769 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13770 				else
13771 					counter_u64_add(bbr_out_size[idx], 1);
13772 			} else {
13773 				/* smaller than a MSS */
13774 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13775 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13776 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13777 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13778 			}
13779 		}
13780 	}
13781 	abandon = 0;
13782 	/*
13783 	 * We must do the send accounting before we log the output,
13784 	 * otherwise the state of the rsm could change and we account to the
13785 	 * wrong bucket.
13786 	 */
13787 	if (len > 0) {
13788 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13789 		if (error == 0) {
13790 			if (tp->snd_una == tp->snd_max)
13791 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13792 		}
13793 	}
13794 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13795 	    cts, mb, &abandon, rsm, 0, sb);
13796 	if (abandon) {
13797 		/*
13798 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13799 		 * sent we should hit this condition.
13800 		 */
13801 		return (0);
13802 	}
13803 	if (bbr->rc_in_persist == 0) {
13804 		/*
13805 		 * Advance snd_nxt over sequence space of this segment.
13806 		 */
13807 		if (error)
13808 			/* We don't log or do anything with errors */
13809 			goto skip_upd;
13810 
13811 		if (tp->snd_una == tp->snd_max &&
13812 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13813 			/*
13814 			 * Update the time we just added data since none was
13815 			 * outstanding.
13816 			 */
13817 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13818 			bbr->rc_tp->t_acktime  = ticks;
13819 		}
13820 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13821 			if (flags & TH_SYN) {
13822 				/*
13823 				 * Smack the snd_max to iss + 1
13824 				 * if its a FO we will add len below.
13825 				 */
13826 				tp->snd_max = tp->iss + 1;
13827 			}
13828 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13829 				tp->snd_max++;
13830 				tp->t_flags |= TF_SENTFIN;
13831 			}
13832 		}
13833 		if (sack_rxmit == 0)
13834 			tp->snd_max += len;
13835 skip_upd:
13836 		if ((error == 0) && len)
13837 			tot_len += len;
13838 	} else {
13839 		/* Persists case */
13840 		int32_t xlen = len;
13841 
13842 		if (error)
13843 			goto nomore;
13844 
13845 		if (flags & TH_SYN)
13846 			++xlen;
13847 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13848 			++xlen;
13849 			tp->t_flags |= TF_SENTFIN;
13850 		}
13851 		if (xlen && (tp->snd_una == tp->snd_max)) {
13852 			/*
13853 			 * Update the time we just added data since none was
13854 			 * outstanding.
13855 			 */
13856 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13857 			bbr->rc_tp->t_acktime = ticks;
13858 		}
13859 		if (sack_rxmit == 0)
13860 			tp->snd_max += xlen;
13861 		tot_len += (len + optlen + ipoptlen);
13862 	}
13863 nomore:
13864 	if (error) {
13865 		/*
13866 		 * Failures do not advance the seq counter above. For the
13867 		 * case of ENOBUFS we will fall out and become ack-clocked.
13868 		 * capping the cwnd at the current flight.
13869 		 * Everything else will just have to retransmit with the timer
13870 		 * (no pacer).
13871 		 */
13872 		SOCKBUF_UNLOCK_ASSERT(sb);
13873 		BBR_STAT_INC(bbr_saw_oerr);
13874 		/* Clear all delay/early tracks */
13875 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13876 		bbr->r_ctl.rc_agg_early = 0;
13877 		bbr->r_agg_early_set = 0;
13878 		bbr->output_error_seen = 1;
13879 		if (bbr->oerror_cnt < 0xf)
13880 			bbr->oerror_cnt++;
13881 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13882 			/* drop the session */
13883 			return (-ENETDOWN);
13884 		}
13885 		switch (error) {
13886 		case ENOBUFS:
13887 			/*
13888 			 * Make this guy have to get ack's to send
13889 			 * more but lets make sure we don't
13890 			 * slam him below a T-O (1MSS).
13891 			 */
13892 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13893 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13894 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13895 				if (tp->snd_cwnd < maxseg)
13896 					tp->snd_cwnd = maxseg;
13897 			}
13898 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13899 			BBR_STAT_INC(bbr_saw_enobuf);
13900 			if (bbr->bbr_hdrw_pacing)
13901 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13902 			else
13903 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13904 			/*
13905 			 * Here even in the enobuf's case we want to do our
13906 			 * state update. The reason being we may have been
13907 			 * called by the input function. If so we have had
13908 			 * things change.
13909 			 */
13910 			error = 0;
13911 			goto enobufs;
13912 		case EMSGSIZE:
13913 			/*
13914 			 * For some reason the interface we used initially
13915 			 * to send segments changed to another or lowered
13916 			 * its MTU. If TSO was active we either got an
13917 			 * interface without TSO capabilits or TSO was
13918 			 * turned off. If we obtained mtu from ip_output()
13919 			 * then update it and try again.
13920 			 */
13921 			/* Turn on tracing (or try to) */
13922 			{
13923 				int old_maxseg;
13924 
13925 				old_maxseg = tp->t_maxseg;
13926 				BBR_STAT_INC(bbr_saw_emsgsiz);
13927 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13928 				if (mtu != 0)
13929 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13930 				if (old_maxseg <= tp->t_maxseg) {
13931 					/* Huh it did not shrink? */
13932 					tp->t_maxseg = old_maxseg - 40;
13933 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13934 				}
13935 				/*
13936 				 * Nuke all other things that can interfere
13937 				 * with slot
13938 				 */
13939 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13940 					slot = bbr_get_pacing_delay(bbr,
13941 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13942 					    (tot_len + len), cts, 0);
13943 					if (slot < bbr_error_base_paceout)
13944 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13945 				} else
13946 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13947 				bbr->rc_output_starts_timer = 1;
13948 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13949 				    tot_len);
13950 				return (error);
13951 			}
13952 		case EPERM:
13953 			tp->t_softerror = error;
13954 			/* Fall through */
13955 		case EHOSTDOWN:
13956 		case EHOSTUNREACH:
13957 		case ENETDOWN:
13958 		case ENETUNREACH:
13959 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13960 				tp->t_softerror = error;
13961 			}
13962 			/* FALLTHROUGH */
13963 		default:
13964 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13965 			bbr->rc_output_starts_timer = 1;
13966 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13967 			return (error);
13968 		}
13969 #ifdef STATS
13970 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13971 		    len &&
13972 		    (rsm == NULL) &&
13973 	    (bbr->rc_in_persist == 0)) {
13974 		tp->gput_seq = bbr_seq;
13975 		tp->gput_ack = bbr_seq +
13976 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13977 		tp->gput_ts = cts;
13978 		tp->t_flags |= TF_GPUTINPROG;
13979 #endif
13980 	}
13981 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13982 	if ((bbr->bbr_hdw_pace_ena) &&
13983 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13984 	    (bbr->rc_past_init_win) &&
13985 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13986 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13987 	    (inp->inp_route.ro_nh &&
13988 	     inp->inp_route.ro_nh->nh_ifp)) {
13989 		/*
13990 		 * We are past the initial window and
13991 		 * have at least one measurement so we
13992 		 * could use hardware pacing if its available.
13993 		 * We have an interface and we have not attempted
13994 		 * to setup hardware pacing, lets try to now.
13995 		 */
13996 		uint64_t rate_wanted;
13997 		int err = 0;
13998 
13999 		rate_wanted = bbr_get_hardware_rate(bbr);
14000 		bbr->bbr_attempt_hdwr_pace = 1;
14001 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
14002 						      inp->inp_route.ro_nh->nh_ifp,
14003 						      rate_wanted,
14004 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
14005 						      &err, NULL);
14006 		if (bbr->r_ctl.crte) {
14007 			bbr_type_log_hdwr_pacing(bbr,
14008 						 bbr->r_ctl.crte->ptbl->rs_ifp,
14009 						 rate_wanted,
14010 						 bbr->r_ctl.crte->rate,
14011 						 __LINE__, cts, err);
14012 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14013 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14014 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
14015 			bbr->bbr_hdrw_pacing = 1;
14016 			/* Now what is our gain status? */
14017 			if (bbr->r_ctl.crte->rate < rate_wanted) {
14018 				/* We have a problem */
14019 				bbr_setup_less_of_rate(bbr, cts,
14020 						       bbr->r_ctl.crte->rate, rate_wanted);
14021 			} else {
14022 				/* We are good */
14023 				bbr->gain_is_limited = 0;
14024 				bbr->skip_gain = 0;
14025 			}
14026 			tcp_bbr_tso_size_check(bbr, cts);
14027 		} else {
14028 			bbr_type_log_hdwr_pacing(bbr,
14029 						 inp->inp_route.ro_nh->nh_ifp,
14030 						 rate_wanted,
14031 						 0,
14032 						 __LINE__, cts, err);
14033 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14034 		}
14035 	}
14036 	if (bbr->bbr_hdrw_pacing) {
14037 		/*
14038 		 * Worry about cases where the route
14039 		 * changes or something happened that we
14040 		 * lost our hardware pacing possibly during
14041 		 * the last ip_output call.
14042 		 */
14043 		if (inp->inp_snd_tag == NULL) {
14044 			/* A change during ip output disabled hw pacing? */
14045 			bbr->bbr_hdrw_pacing = 0;
14046 		} else if ((inp->inp_route.ro_nh == NULL) ||
14047 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
14048 			/*
14049 			 * We had an interface or route change,
14050 			 * detach from the current hdwr pacing
14051 			 * and setup to re-attempt next go
14052 			 * round.
14053 			 */
14054 			bbr->bbr_hdrw_pacing = 0;
14055 			bbr->bbr_attempt_hdwr_pace = 0;
14056 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14057 			tcp_bbr_tso_size_check(bbr, cts);
14058 		}
14059 	}
14060 	/*
14061 	 * Data sent (as far as we can tell). If this advertises a larger
14062 	 * window than any other segment, then remember the size of the
14063 	 * advertised window. Any pending ACK has now been sent.
14064 	 */
14065 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14066 		tp->rcv_adv = tp->rcv_nxt + recwin;
14067 
14068 	tp->last_ack_sent = tp->rcv_nxt;
14069 	if ((error == 0) &&
14070 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14071 	    (doing_tlp == 0) &&
14072 	    (tso == 0) &&
14073 	    (len > 0) &&
14074 	    ((flags & TH_RST) == 0) &&
14075 	    ((flags & TH_SYN) == 0) &&
14076 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14077 	    (bbr->rc_in_persist == 0) &&
14078 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14079 		/*
14080 		 * For non-tso we need to goto again until we have sent out
14081 		 * enough data to match what we are hptsi out every hptsi
14082 		 * interval.
14083 		 */
14084 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14085 			/* Make sure snd_nxt is drug up */
14086 			tp->snd_nxt = tp->snd_max;
14087 		}
14088 		if (rsm != NULL) {
14089 			rsm = NULL;
14090 			goto skip_again;
14091 		}
14092 		rsm = NULL;
14093 		sack_rxmit = 0;
14094 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14095 		goto again;
14096 	}
14097 skip_again:
14098 	if ((error == 0) && (flags & TH_FIN))
14099 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14100 	if ((error == 0) && (flags & TH_RST))
14101 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14102 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14103 		/*
14104 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14105 		 * what we have sent so far
14106 		 */
14107 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14108 		if (bbr->rc_no_pacing)
14109 			slot = 0;
14110 	}
14111 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14112 enobufs:
14113 	if (bbr->rc_use_google == 0)
14114 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14115 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14116 							bbr->r_ctl.rc_lost_bytes)));
14117 	bbr->rc_output_starts_timer = 1;
14118 	if (bbr->bbr_use_rack_cheat &&
14119 	    (more_to_rxt ||
14120 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14121 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14122 		if (slot > 1000)
14123 			slot = 1000;
14124 	}
14125 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14126 		/*
14127 		 * We don't change the tso size until some number of sends
14128 		 * to give the hardware commands time to get down
14129 		 * to the interface.
14130 		 */
14131 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14132 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14133 			bbr->hw_pacing_set = 1;
14134 			tcp_bbr_tso_size_check(bbr, cts);
14135 		}
14136 	}
14137 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14138 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14139 		/* Make sure snd_nxt is drug up */
14140 		tp->snd_nxt = tp->snd_max;
14141 	}
14142 	return (error);
14143 
14144 }
14145 
14146 /*
14147  * See bbr_output_wtime() for return values.
14148  */
14149 static int
14150 bbr_output(struct tcpcb *tp)
14151 {
14152 	int32_t ret;
14153 	struct timeval tv;
14154 
14155 	NET_EPOCH_ASSERT();
14156 
14157 	INP_WLOCK_ASSERT(tp->t_inpcb);
14158 	(void)tcp_get_usecs(&tv);
14159 	ret = bbr_output_wtime(tp, &tv);
14160 	return (ret);
14161 }
14162 
14163 static void
14164 bbr_mtu_chg(struct tcpcb *tp)
14165 {
14166 	struct tcp_bbr *bbr;
14167 	struct bbr_sendmap *rsm, *frsm = NULL;
14168 	uint32_t maxseg;
14169 
14170 	/*
14171 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14172 	 * over the current size as SACK_PASS so a retransmit will occur.
14173 	 */
14174 
14175 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14176 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14177 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14178 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14179 		/* Don't mess with ones acked (by sack?) */
14180 		if (rsm->r_flags & BBR_ACKED)
14181 			continue;
14182 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14183 			/*
14184 			 * We mark sack-passed on all the previous large
14185 			 * sends we did. This will force them to retransmit.
14186 			 */
14187 			rsm->r_flags |= BBR_SACK_PASSED;
14188 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14189 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14190 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14191 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14192 				rsm->r_flags |= BBR_MARKED_LOST;
14193 			}
14194 			if (frsm == NULL)
14195 				frsm = rsm;
14196 		}
14197 	}
14198 	if (frsm) {
14199 		bbr->r_ctl.rc_resend = frsm;
14200 	}
14201 }
14202 
14203 static int
14204 bbr_pru_options(struct tcpcb *tp, int flags)
14205 {
14206 	if (flags & PRUS_OOB)
14207 		return (EOPNOTSUPP);
14208 	return (0);
14209 }
14210 
14211 struct tcp_function_block __tcp_bbr = {
14212 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14213 	.tfb_tcp_output = bbr_output,
14214 	.tfb_do_queued_segments = ctf_do_queued_segments,
14215 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14216 	.tfb_tcp_do_segment = bbr_do_segment,
14217 	.tfb_tcp_ctloutput = bbr_ctloutput,
14218 	.tfb_tcp_fb_init = bbr_init,
14219 	.tfb_tcp_fb_fini = bbr_fini,
14220 	.tfb_tcp_timer_stop_all = bbr_stopall,
14221 	.tfb_tcp_timer_activate = bbr_timer_activate,
14222 	.tfb_tcp_timer_active = bbr_timer_active,
14223 	.tfb_tcp_timer_stop = bbr_timer_stop,
14224 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14225 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14226 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14227 	.tfb_pru_options = bbr_pru_options,
14228 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14229 };
14230 
14231 /*
14232  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14233  * socket option arguments.  When it re-acquires the lock after the copy, it
14234  * has to revalidate that the connection is still valid for the socket
14235  * option.
14236  */
14237 static int
14238 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14239 		struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14240 {
14241 	struct epoch_tracker et;
14242 	int32_t error = 0, optval;
14243 
14244 	switch (sopt->sopt_level) {
14245 	case IPPROTO_IPV6:
14246 	case IPPROTO_IP:
14247 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14248 	}
14249 
14250 	switch (sopt->sopt_name) {
14251 	case TCP_RACK_PACE_MAX_SEG:
14252 	case TCP_RACK_MIN_TO:
14253 	case TCP_RACK_REORD_THRESH:
14254 	case TCP_RACK_REORD_FADE:
14255 	case TCP_RACK_TLP_THRESH:
14256 	case TCP_RACK_PKT_DELAY:
14257 	case TCP_BBR_ALGORITHM:
14258 	case TCP_BBR_TSLIMITS:
14259 	case TCP_BBR_IWINTSO:
14260 	case TCP_BBR_RECFORCE:
14261 	case TCP_BBR_STARTUP_PG:
14262 	case TCP_BBR_DRAIN_PG:
14263 	case TCP_BBR_RWND_IS_APP:
14264 	case TCP_BBR_PROBE_RTT_INT:
14265 	case TCP_BBR_PROBE_RTT_GAIN:
14266 	case TCP_BBR_PROBE_RTT_LEN:
14267 	case TCP_BBR_STARTUP_LOSS_EXIT:
14268 	case TCP_BBR_USEDEL_RATE:
14269 	case TCP_BBR_MIN_RTO:
14270 	case TCP_BBR_MAX_RTO:
14271 	case TCP_BBR_PACE_PER_SEC:
14272 	case TCP_DELACK:
14273 	case TCP_BBR_PACE_DEL_TAR:
14274 	case TCP_BBR_SEND_IWND_IN_TSO:
14275 	case TCP_BBR_EXTRA_STATE:
14276 	case TCP_BBR_UTTER_MAX_TSO:
14277 	case TCP_BBR_MIN_TOPACEOUT:
14278 	case TCP_BBR_FLOOR_MIN_TSO:
14279 	case TCP_BBR_TSTMP_RAISES:
14280 	case TCP_BBR_POLICER_DETECT:
14281 	case TCP_BBR_USE_RACK_CHEAT:
14282 	case TCP_DATA_AFTER_CLOSE:
14283 	case TCP_BBR_HDWR_PACE:
14284 	case TCP_BBR_PACE_SEG_MAX:
14285 	case TCP_BBR_PACE_SEG_MIN:
14286 	case TCP_BBR_PACE_CROSS:
14287 	case TCP_BBR_PACE_OH:
14288 #ifdef NETFLIX_PEAKRATE
14289 	case TCP_MAXPEAKRATE:
14290 #endif
14291 	case TCP_BBR_TMR_PACE_OH:
14292 	case TCP_BBR_RACK_RTT_USE:
14293 	case TCP_BBR_RETRAN_WTSO:
14294 		break;
14295 	default:
14296 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14297 		break;
14298 	}
14299 	INP_WUNLOCK(inp);
14300 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14301 	if (error)
14302 		return (error);
14303 	INP_WLOCK(inp);
14304 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14305 		INP_WUNLOCK(inp);
14306 		return (ECONNRESET);
14307 	}
14308 	tp = intotcpcb(inp);
14309 	if (tp->t_fb != &__tcp_bbr) {
14310 		INP_WUNLOCK(inp);
14311 		return (ENOPROTOOPT);
14312 	}
14313 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14314 	switch (sopt->sopt_name) {
14315 	case TCP_BBR_PACE_PER_SEC:
14316 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14317 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14318 		break;
14319 	case TCP_BBR_PACE_DEL_TAR:
14320 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14321 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14322 		break;
14323 	case TCP_BBR_PACE_SEG_MAX:
14324 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14325 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14326 		break;
14327 	case TCP_BBR_PACE_SEG_MIN:
14328 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14329 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14330 		break;
14331 	case TCP_BBR_PACE_CROSS:
14332 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14333 		bbr->r_ctl.bbr_cross_over = optval;
14334 		break;
14335 	case TCP_BBR_ALGORITHM:
14336 		BBR_OPTS_INC(tcp_bbr_algorithm);
14337 		if (optval && (bbr->rc_use_google == 0)) {
14338 			/* Turn on the google mode */
14339 			bbr_google_mode_on(bbr);
14340 			if ((optval > 3) && (optval < 500)) {
14341 				/*
14342 				 * Must be at least greater than .3%
14343 				 * and must be less than 50.0%.
14344 				 */
14345 				bbr->r_ctl.bbr_google_discount = optval;
14346 			}
14347 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14348 			/* Turn off the google mode */
14349 			bbr_google_mode_off(bbr);
14350 		}
14351 		break;
14352 	case TCP_BBR_TSLIMITS:
14353 		BBR_OPTS_INC(tcp_bbr_tslimits);
14354 		if (optval == 1)
14355 			bbr->rc_use_ts_limit = 1;
14356 		else if (optval == 0)
14357 			bbr->rc_use_ts_limit = 0;
14358 		else
14359 			error = EINVAL;
14360 		break;
14361 
14362 	case TCP_BBR_IWINTSO:
14363 		BBR_OPTS_INC(tcp_bbr_iwintso);
14364 		if ((optval >= 0) && (optval < 128)) {
14365 			uint32_t twin;
14366 
14367 			bbr->rc_init_win = optval;
14368 			twin = bbr_initial_cwnd(bbr, tp);
14369 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14370 				tp->snd_cwnd = twin;
14371 			else
14372 				error = EBUSY;
14373 		} else
14374 			error = EINVAL;
14375 		break;
14376 	case TCP_BBR_STARTUP_PG:
14377 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14378 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14379 			bbr->r_ctl.rc_startup_pg = optval;
14380 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14381 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14382 			}
14383 		} else
14384 			error = EINVAL;
14385 		break;
14386 	case TCP_BBR_DRAIN_PG:
14387 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14388 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14389 			bbr->r_ctl.rc_drain_pg = optval;
14390 		else
14391 			error = EINVAL;
14392 		break;
14393 	case TCP_BBR_PROBE_RTT_LEN:
14394 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14395 		if (optval <= 1)
14396 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14397 		else
14398 			error = EINVAL;
14399 		break;
14400 	case TCP_BBR_PROBE_RTT_GAIN:
14401 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14402 		if (optval <= BBR_UNIT)
14403 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14404 		else
14405 			error = EINVAL;
14406 		break;
14407 	case TCP_BBR_PROBE_RTT_INT:
14408 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14409 		if (optval > 1000)
14410 			bbr->r_ctl.rc_probertt_int = optval;
14411 		else
14412 			error = EINVAL;
14413 		break;
14414 	case TCP_BBR_MIN_TOPACEOUT:
14415 		BBR_OPTS_INC(tcp_bbr_topaceout);
14416 		if (optval == 0) {
14417 			bbr->no_pacing_until = 0;
14418 			bbr->rc_no_pacing = 0;
14419 		} else if (optval <= 0x00ff) {
14420 			bbr->no_pacing_until = optval;
14421 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14422 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14423 				/* Turn on no pacing */
14424 				bbr->rc_no_pacing = 1;
14425 			}
14426 		} else
14427 			error = EINVAL;
14428 		break;
14429 	case TCP_BBR_STARTUP_LOSS_EXIT:
14430 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14431 		bbr->rc_loss_exit = optval;
14432 		break;
14433 	case TCP_BBR_USEDEL_RATE:
14434 		error = EINVAL;
14435 		break;
14436 	case TCP_BBR_MIN_RTO:
14437 		BBR_OPTS_INC(tcp_bbr_min_rto);
14438 		bbr->r_ctl.rc_min_rto_ms = optval;
14439 		break;
14440 	case TCP_BBR_MAX_RTO:
14441 		BBR_OPTS_INC(tcp_bbr_max_rto);
14442 		bbr->rc_max_rto_sec = optval;
14443 		break;
14444 	case TCP_RACK_MIN_TO:
14445 		/* Minimum time between rack t-o's in ms */
14446 		BBR_OPTS_INC(tcp_rack_min_to);
14447 		bbr->r_ctl.rc_min_to = optval;
14448 		break;
14449 	case TCP_RACK_REORD_THRESH:
14450 		/* RACK reorder threshold (shift amount) */
14451 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14452 		if ((optval > 0) && (optval < 31))
14453 			bbr->r_ctl.rc_reorder_shift = optval;
14454 		else
14455 			error = EINVAL;
14456 		break;
14457 	case TCP_RACK_REORD_FADE:
14458 		/* Does reordering fade after ms time */
14459 		BBR_OPTS_INC(tcp_rack_reord_fade);
14460 		bbr->r_ctl.rc_reorder_fade = optval;
14461 		break;
14462 	case TCP_RACK_TLP_THRESH:
14463 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14464 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14465 		if (optval)
14466 			bbr->rc_tlp_threshold = optval;
14467 		else
14468 			error = EINVAL;
14469 		break;
14470 	case TCP_BBR_USE_RACK_CHEAT:
14471 		BBR_OPTS_INC(tcp_use_rackcheat);
14472 		if (bbr->rc_use_google) {
14473 			error = EINVAL;
14474 			break;
14475 		}
14476 		BBR_OPTS_INC(tcp_rack_cheat);
14477 		if (optval)
14478 			bbr->bbr_use_rack_cheat = 1;
14479 		else
14480 			bbr->bbr_use_rack_cheat = 0;
14481 		break;
14482 	case TCP_BBR_FLOOR_MIN_TSO:
14483 		BBR_OPTS_INC(tcp_utter_max_tso);
14484 		if ((optval >= 0) && (optval < 40))
14485 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14486 		else
14487 			error = EINVAL;
14488 		break;
14489 	case TCP_BBR_UTTER_MAX_TSO:
14490 		BBR_OPTS_INC(tcp_utter_max_tso);
14491 		if ((optval >= 0) && (optval < 0xffff))
14492 			bbr->r_ctl.bbr_utter_max = optval;
14493 		else
14494 			error = EINVAL;
14495 		break;
14496 
14497 	case TCP_BBR_EXTRA_STATE:
14498 		BBR_OPTS_INC(tcp_extra_state);
14499 		if (optval)
14500 			bbr->rc_use_idle_restart = 1;
14501 		else
14502 			bbr->rc_use_idle_restart = 0;
14503 		break;
14504 	case TCP_BBR_SEND_IWND_IN_TSO:
14505 		BBR_OPTS_INC(tcp_iwnd_tso);
14506 		if (optval) {
14507 			bbr->bbr_init_win_cheat = 1;
14508 			if (bbr->rc_past_init_win == 0) {
14509 				uint32_t cts;
14510 				cts = tcp_get_usecs(&bbr->rc_tv);
14511 				tcp_bbr_tso_size_check(bbr, cts);
14512 			}
14513 		} else
14514 			bbr->bbr_init_win_cheat = 0;
14515 		break;
14516 	case TCP_BBR_HDWR_PACE:
14517 		BBR_OPTS_INC(tcp_hdwr_pacing);
14518 		if (optval){
14519 			bbr->bbr_hdw_pace_ena = 1;
14520 			bbr->bbr_attempt_hdwr_pace = 0;
14521 		} else {
14522 			bbr->bbr_hdw_pace_ena = 0;
14523 #ifdef RATELIMIT
14524 			if (bbr->r_ctl.crte != NULL) {
14525 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14526 				bbr->r_ctl.crte = NULL;
14527 			}
14528 #endif
14529 		}
14530 		break;
14531 
14532 	case TCP_DELACK:
14533 		BBR_OPTS_INC(tcp_delack);
14534 		if (optval < 100) {
14535 			if (optval == 0) /* off */
14536 				tp->t_delayed_ack = 0;
14537 			else if (optval == 1) /* on which is 2 */
14538 				tp->t_delayed_ack = 2;
14539 			else /* higher than 2 and less than 100 */
14540 				tp->t_delayed_ack = optval;
14541 			if (tp->t_flags & TF_DELACK) {
14542 				tp->t_flags &= ~TF_DELACK;
14543 				tp->t_flags |= TF_ACKNOW;
14544 				NET_EPOCH_ENTER(et);
14545 				bbr_output(tp);
14546 				NET_EPOCH_EXIT(et);
14547 			}
14548 		} else
14549 			error = EINVAL;
14550 		break;
14551 	case TCP_RACK_PKT_DELAY:
14552 		/* RACK added ms i.e. rack-rtt + reord + N */
14553 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14554 		bbr->r_ctl.rc_pkt_delay = optval;
14555 		break;
14556 #ifdef NETFLIX_PEAKRATE
14557 	case TCP_MAXPEAKRATE:
14558 		BBR_OPTS_INC(tcp_maxpeak);
14559 		error = tcp_set_maxpeakrate(tp, optval);
14560 		if (!error)
14561 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14562 		break;
14563 #endif
14564 	case TCP_BBR_RETRAN_WTSO:
14565 		BBR_OPTS_INC(tcp_retran_wtso);
14566 		if (optval)
14567 			bbr->rc_resends_use_tso = 1;
14568 		else
14569 			bbr->rc_resends_use_tso = 0;
14570 		break;
14571 	case TCP_DATA_AFTER_CLOSE:
14572 		BBR_OPTS_INC(tcp_data_ac);
14573 		if (optval)
14574 			bbr->rc_allow_data_af_clo = 1;
14575 		else
14576 			bbr->rc_allow_data_af_clo = 0;
14577 		break;
14578 	case TCP_BBR_POLICER_DETECT:
14579 		BBR_OPTS_INC(tcp_policer_det);
14580 		if (bbr->rc_use_google == 0)
14581 			error = EINVAL;
14582 		else if (optval)
14583 			bbr->r_use_policer = 1;
14584 		else
14585 			bbr->r_use_policer = 0;
14586 		break;
14587 
14588 	case TCP_BBR_TSTMP_RAISES:
14589 		BBR_OPTS_INC(tcp_ts_raises);
14590 		if (optval)
14591 			bbr->ts_can_raise = 1;
14592 		else
14593 			bbr->ts_can_raise = 0;
14594 		break;
14595 	case TCP_BBR_TMR_PACE_OH:
14596 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14597 		if (bbr->rc_use_google) {
14598 			error = EINVAL;
14599 		} else {
14600 			if (optval)
14601 				bbr->r_ctl.rc_incr_tmrs = 1;
14602 			else
14603 				bbr->r_ctl.rc_incr_tmrs = 0;
14604 		}
14605 		break;
14606 	case TCP_BBR_PACE_OH:
14607 		BBR_OPTS_INC(tcp_pacing_oh);
14608 		if (bbr->rc_use_google) {
14609 			error = EINVAL;
14610 		} else {
14611 			if (optval > (BBR_INCL_TCP_OH|
14612 				      BBR_INCL_IP_OH|
14613 				      BBR_INCL_ENET_OH)) {
14614 				error = EINVAL;
14615 				break;
14616 			}
14617 			if (optval & BBR_INCL_TCP_OH)
14618 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14619 			else
14620 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14621 			if (optval & BBR_INCL_IP_OH)
14622 				bbr->r_ctl.rc_inc_ip_oh = 1;
14623 			else
14624 				bbr->r_ctl.rc_inc_ip_oh = 0;
14625 			if (optval & BBR_INCL_ENET_OH)
14626 				bbr->r_ctl.rc_inc_enet_oh = 1;
14627 			else
14628 				bbr->r_ctl.rc_inc_enet_oh = 0;
14629 		}
14630 		break;
14631 	default:
14632 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14633 		break;
14634 	}
14635 #ifdef NETFLIX_STATS
14636 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14637 #endif
14638 	INP_WUNLOCK(inp);
14639 	return (error);
14640 }
14641 
14642 /*
14643  * return 0 on success, error-num on failure
14644  */
14645 static int
14646 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14647     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14648 {
14649 	int32_t error, optval;
14650 
14651 	/*
14652 	 * Because all our options are either boolean or an int, we can just
14653 	 * pull everything into optval and then unlock and copy. If we ever
14654 	 * add a option that is not a int, then this will have quite an
14655 	 * impact to this routine.
14656 	 */
14657 	switch (sopt->sopt_name) {
14658 	case TCP_BBR_PACE_PER_SEC:
14659 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14660 		break;
14661 	case TCP_BBR_PACE_DEL_TAR:
14662 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14663 		break;
14664 	case TCP_BBR_PACE_SEG_MAX:
14665 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14666 		break;
14667 	case TCP_BBR_MIN_TOPACEOUT:
14668 		optval = bbr->no_pacing_until;
14669 		break;
14670 	case TCP_BBR_PACE_SEG_MIN:
14671 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14672 		break;
14673 	case TCP_BBR_PACE_CROSS:
14674 		optval = bbr->r_ctl.bbr_cross_over;
14675 		break;
14676 	case TCP_BBR_ALGORITHM:
14677 		optval = bbr->rc_use_google;
14678 		break;
14679 	case TCP_BBR_TSLIMITS:
14680 		optval = bbr->rc_use_ts_limit;
14681 		break;
14682 	case TCP_BBR_IWINTSO:
14683 		optval = bbr->rc_init_win;
14684 		break;
14685 	case TCP_BBR_STARTUP_PG:
14686 		optval = bbr->r_ctl.rc_startup_pg;
14687 		break;
14688 	case TCP_BBR_DRAIN_PG:
14689 		optval = bbr->r_ctl.rc_drain_pg;
14690 		break;
14691 	case TCP_BBR_PROBE_RTT_INT:
14692 		optval = bbr->r_ctl.rc_probertt_int;
14693 		break;
14694 	case TCP_BBR_PROBE_RTT_LEN:
14695 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14696 		break;
14697 	case TCP_BBR_PROBE_RTT_GAIN:
14698 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14699 		break;
14700 	case TCP_BBR_STARTUP_LOSS_EXIT:
14701 		optval = bbr->rc_loss_exit;
14702 		break;
14703 	case TCP_BBR_USEDEL_RATE:
14704 		error = EINVAL;
14705 		break;
14706 	case TCP_BBR_MIN_RTO:
14707 		optval = bbr->r_ctl.rc_min_rto_ms;
14708 		break;
14709 	case TCP_BBR_MAX_RTO:
14710 		optval = bbr->rc_max_rto_sec;
14711 		break;
14712 	case TCP_RACK_PACE_MAX_SEG:
14713 		/* Max segments in a pace */
14714 		optval = bbr->r_ctl.rc_pace_max_segs;
14715 		break;
14716 	case TCP_RACK_MIN_TO:
14717 		/* Minimum time between rack t-o's in ms */
14718 		optval = bbr->r_ctl.rc_min_to;
14719 		break;
14720 	case TCP_RACK_REORD_THRESH:
14721 		/* RACK reorder threshold (shift amount) */
14722 		optval = bbr->r_ctl.rc_reorder_shift;
14723 		break;
14724 	case TCP_RACK_REORD_FADE:
14725 		/* Does reordering fade after ms time */
14726 		optval = bbr->r_ctl.rc_reorder_fade;
14727 		break;
14728 	case TCP_BBR_USE_RACK_CHEAT:
14729 		/* Do we use the rack cheat for rxt */
14730 		optval = bbr->bbr_use_rack_cheat;
14731 		break;
14732 	case TCP_BBR_FLOOR_MIN_TSO:
14733 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14734 		break;
14735 	case TCP_BBR_UTTER_MAX_TSO:
14736 		optval = bbr->r_ctl.bbr_utter_max;
14737 		break;
14738 	case TCP_BBR_SEND_IWND_IN_TSO:
14739 		/* Do we send TSO size segments initially */
14740 		optval = bbr->bbr_init_win_cheat;
14741 		break;
14742 	case TCP_BBR_EXTRA_STATE:
14743 		optval = bbr->rc_use_idle_restart;
14744 		break;
14745 	case TCP_RACK_TLP_THRESH:
14746 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14747 		optval = bbr->rc_tlp_threshold;
14748 		break;
14749 	case TCP_RACK_PKT_DELAY:
14750 		/* RACK added ms i.e. rack-rtt + reord + N */
14751 		optval = bbr->r_ctl.rc_pkt_delay;
14752 		break;
14753 	case TCP_BBR_RETRAN_WTSO:
14754 		optval = bbr->rc_resends_use_tso;
14755 		break;
14756 	case TCP_DATA_AFTER_CLOSE:
14757 		optval = bbr->rc_allow_data_af_clo;
14758 		break;
14759 	case TCP_DELACK:
14760 		optval = tp->t_delayed_ack;
14761 		break;
14762 	case TCP_BBR_HDWR_PACE:
14763 		optval = bbr->bbr_hdw_pace_ena;
14764 		break;
14765 	case TCP_BBR_POLICER_DETECT:
14766 		optval = bbr->r_use_policer;
14767 		break;
14768 	case TCP_BBR_TSTMP_RAISES:
14769 		optval = bbr->ts_can_raise;
14770 		break;
14771 	case TCP_BBR_TMR_PACE_OH:
14772 		optval = bbr->r_ctl.rc_incr_tmrs;
14773 		break;
14774 	case TCP_BBR_PACE_OH:
14775 		optval = 0;
14776 		if (bbr->r_ctl.rc_inc_tcp_oh)
14777 			optval |= BBR_INCL_TCP_OH;
14778 		if (bbr->r_ctl.rc_inc_ip_oh)
14779 			optval |= BBR_INCL_IP_OH;
14780 		if (bbr->r_ctl.rc_inc_enet_oh)
14781 			optval |= BBR_INCL_ENET_OH;
14782 		break;
14783 	default:
14784 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14785 		break;
14786 	}
14787 	INP_WUNLOCK(inp);
14788 	error = sooptcopyout(sopt, &optval, sizeof optval);
14789 	return (error);
14790 }
14791 
14792 /*
14793  * return 0 on success, error-num on failure
14794  */
14795 static int
14796 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
14797 {
14798 	int32_t error = EINVAL;
14799 	struct tcp_bbr *bbr;
14800 
14801 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14802 	if (bbr == NULL) {
14803 		/* Huh? */
14804 		goto out;
14805 	}
14806 	if (sopt->sopt_dir == SOPT_SET) {
14807 		return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
14808 	} else if (sopt->sopt_dir == SOPT_GET) {
14809 		return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
14810 	}
14811 out:
14812 	INP_WUNLOCK(inp);
14813 	return (error);
14814 }
14815 
14816 static const char *bbr_stack_names[] = {
14817 	__XSTRING(STACKNAME),
14818 #ifdef STACKALIAS
14819 	__XSTRING(STACKALIAS),
14820 #endif
14821 };
14822 
14823 static bool bbr_mod_inited = false;
14824 
14825 static int
14826 tcp_addbbr(module_t mod, int32_t type, void *data)
14827 {
14828 	int32_t err = 0;
14829 	int num_stacks;
14830 
14831 	switch (type) {
14832 	case MOD_LOAD:
14833 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14834 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14835 		    sizeof(struct bbr_sendmap),
14836 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14837 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14838 		    sizeof(struct tcp_bbr),
14839 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14840 		sysctl_ctx_init(&bbr_sysctl_ctx);
14841 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14842 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14843 		    OID_AUTO,
14844 #ifdef STACKALIAS
14845 		    __XSTRING(STACKALIAS),
14846 #else
14847 		    __XSTRING(STACKNAME),
14848 #endif
14849 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14850 		    "");
14851 		if (bbr_sysctl_root == NULL) {
14852 			printf("Failed to add sysctl node\n");
14853 			err = EFAULT;
14854 			goto free_uma;
14855 		}
14856 		bbr_init_sysctls();
14857 		num_stacks = nitems(bbr_stack_names);
14858 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14859 		    bbr_stack_names, &num_stacks);
14860 		if (err) {
14861 			printf("Failed to register %s stack name for "
14862 			    "%s module\n", bbr_stack_names[num_stacks],
14863 			    __XSTRING(MODNAME));
14864 			sysctl_ctx_free(&bbr_sysctl_ctx);
14865 	free_uma:
14866 			uma_zdestroy(bbr_zone);
14867 			uma_zdestroy(bbr_pcb_zone);
14868 			bbr_counter_destroy();
14869 			printf("Failed to register " __XSTRING(MODNAME)
14870 			    " module err:%d\n", err);
14871 			return (err);
14872 		}
14873 		tcp_lro_reg_mbufq();
14874 		bbr_mod_inited = true;
14875 		printf(__XSTRING(MODNAME) " is now available\n");
14876 		break;
14877 	case MOD_QUIESCE:
14878 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14879 		break;
14880 	case MOD_UNLOAD:
14881 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14882 		if (err == EBUSY)
14883 			break;
14884 		if (bbr_mod_inited) {
14885 			uma_zdestroy(bbr_zone);
14886 			uma_zdestroy(bbr_pcb_zone);
14887 			sysctl_ctx_free(&bbr_sysctl_ctx);
14888 			bbr_counter_destroy();
14889 			printf(__XSTRING(MODNAME)
14890 			    " is now no longer available\n");
14891 			bbr_mod_inited = false;
14892 		}
14893 		tcp_lro_dereg_mbufq();
14894 		err = 0;
14895 		break;
14896 	default:
14897 		return (EOPNOTSUPP);
14898 	}
14899 	return (err);
14900 }
14901 
14902 static moduledata_t tcp_bbr = {
14903 	.name = __XSTRING(MODNAME),
14904 	    .evhand = tcp_addbbr,
14905 	    .priv = 0
14906 };
14907 
14908 MODULE_VERSION(MODNAME, 1);
14909 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14910 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14911