xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 55224280e2f20474f83001cbc402b21fba8f1c4b)
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 upper, lower, 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 		upper = (bw >> 32) & 0x00000000ffffffff;
6515 		lower = bw & 0x00000000ffffffff;
6516 		/*
6517 		 * If we are using this b/w shove it in now so we
6518 		 * can see in the trace viewer if it gets over-ridden.
6519 		 */
6520 		if (rsm->r_ts_valid &&
6521 		    bbr->rc_ts_valid &&
6522 		    bbr->rc_ts_clock_set &&
6523 		    (bbr->rc_ts_cant_be_used == 0) &&
6524 		    bbr->rc_use_ts_limit) {
6525 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6526 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6527 			if ((delivered == 0) ||
6528 			    (rtt < 1000)) {
6529 				/* Can't use the ts */
6530 				bbr_log_type_bbrupd(bbr, 61, cts,
6531 						    ts_diff,
6532 						    bbr->r_ctl.last_inbound_ts,
6533 						    rsm->r_del_ack_ts, 0,
6534 						    0, 0, 0, delivered);
6535 			} else {
6536 				ts_bw = (uint64_t)delivered;
6537 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6538 				ts_bw /= ts_diff;
6539 				bbr_log_type_bbrupd(bbr, 62, cts,
6540 						    (ts_bw >> 32),
6541 						    (ts_bw & 0xffffffff), 0, 0,
6542 						    0, 0, ts_diff, delivered);
6543 				if ((bbr->ts_can_raise) &&
6544 				    (ts_bw > bw)) {
6545 					bbr_log_type_bbrupd(bbr, 8, cts,
6546 							    delivered,
6547 							    ts_diff,
6548 							    (bw >> 32),
6549 							    (bw & 0x00000000ffffffff),
6550 							    0, 0, 0, 0);
6551 					bw = ts_bw;
6552 				} else if (ts_bw && (ts_bw < bw)) {
6553 					bbr_log_type_bbrupd(bbr, 7, cts,
6554 							    delivered,
6555 							    ts_diff,
6556 							    (bw >> 32),
6557 							    (bw & 0x00000000ffffffff),
6558 							    0, 0, 0, 0);
6559 					bw = ts_bw;
6560 				}
6561 			}
6562 		}
6563 		if (rsm->r_first_sent_time &&
6564 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6565 			uint64_t sbw, sti;
6566 			/*
6567 			 * We use what was in flight at the time of our
6568 			 * send  and the size of this send to figure
6569 			 * out what we have been sending at (amount).
6570 			 * For the time we take from the time of
6571 			 * the send of the first send outstanding
6572 			 * until this send plus this sends pacing
6573 			 * time. This gives us a good calculation
6574 			 * as to the rate we have been sending at.
6575 			 */
6576 
6577 			sbw = (uint64_t)(rsm->r_flight_at_send);
6578 			sbw *= (uint64_t)USECS_IN_SECOND;
6579 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6580 			sti += rsm->r_pacing_delay;
6581 			sbw /= sti;
6582 			if (sbw < bw) {
6583 				bbr_log_type_bbrupd(bbr, 6, cts,
6584 						    delivered,
6585 						    (uint32_t)sti,
6586 						    (bw >> 32),
6587 						    (uint32_t)bw,
6588 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6589 						    (uint32_t)sbw);
6590 				bw = sbw;
6591 			}
6592 		}
6593 		/* Use the google algorithm for b/w measurements */
6594 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6595 		if ((rsm->r_app_limited == 0) ||
6596 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6597 			tcp_bbr_commit_bw(bbr, cts);
6598 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6599 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6600 		}
6601 	}
6602 }
6603 
6604 static void
6605 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6606 {
6607 	if (bbr->rc_in_persist == 0) {
6608 		/* We log only when not in persist */
6609 		/* Translate to a Bytes Per Second */
6610 		uint64_t tim, bw;
6611 		uint32_t upper, lower, delivered;
6612 		int no_apply = 0;
6613 
6614 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6615 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6616 		else
6617 			tim = 1;
6618 		/*
6619 		 * Now that we have processed the tim (skipping the sample
6620 		 * or possibly updating the time, go ahead and
6621 		 * calculate the cdr.
6622 		 */
6623 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6624 		bw = (uint64_t)delivered;
6625 		bw *= (uint64_t)USECS_IN_SECOND;
6626 		bw /= tim;
6627 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6628 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6629 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6630 
6631 			no_apply = 1;
6632 		}
6633 		upper = (bw >> 32) & 0x00000000ffffffff;
6634 		lower = bw & 0x00000000ffffffff;
6635 		/*
6636 		 * If we are using this b/w shove it in now so we
6637 		 * can see in the trace viewer if it gets over-ridden.
6638 		 */
6639 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6640 		/* Gate by the sending rate */
6641 		if (rsm->r_first_sent_time &&
6642 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6643 			uint64_t sbw, sti;
6644 			/*
6645 			 * We use what was in flight at the time of our
6646 			 * send  and the size of this send to figure
6647 			 * out what we have been sending at (amount).
6648 			 * For the time we take from the time of
6649 			 * the send of the first send outstanding
6650 			 * until this send plus this sends pacing
6651 			 * time. This gives us a good calculation
6652 			 * as to the rate we have been sending at.
6653 			 */
6654 
6655 			sbw = (uint64_t)(rsm->r_flight_at_send);
6656 			sbw *= (uint64_t)USECS_IN_SECOND;
6657 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6658 			sti += rsm->r_pacing_delay;
6659 			sbw /= sti;
6660 			if (sbw < bw) {
6661 				bbr_log_type_bbrupd(bbr, 6, cts,
6662 						    delivered,
6663 						    (uint32_t)sti,
6664 						    (bw >> 32),
6665 						    (uint32_t)bw,
6666 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6667 						    (uint32_t)sbw);
6668 				bw = sbw;
6669 			}
6670 			if ((sti > tim) &&
6671 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6672 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6673 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6674 				no_apply = 1;
6675 			} else
6676 				no_apply = 0;
6677 		}
6678 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6679 		if ((no_apply == 0) &&
6680 		    ((rsm->r_app_limited == 0) ||
6681 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6682 			tcp_bbr_commit_bw(bbr, cts);
6683 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6684 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6685 		}
6686 	}
6687 }
6688 
6689 static void
6690 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6691     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6692 {
6693 	uint64_t old_rttprop;
6694 
6695 	/* Update our delivery time and amount */
6696 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6697 	bbr->r_ctl.rc_del_time = cts;
6698 	if (rtt == 0) {
6699 		/*
6700 		 * 0 means its a retransmit, for now we don't use these for
6701 		 * the rest of BBR.
6702 		 */
6703 		return;
6704 	}
6705 	if ((bbr->rc_use_google == 0) &&
6706 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6707 	    (match != BBR_RTT_BY_TIMESTAMP)){
6708 		/*
6709 		 * We get a lot of rtt updates, lets not pay attention to
6710 		 * any that are not an exact match. That way we don't have
6711 		 * to worry about timestamps and the whole nonsense of
6712 		 * unsure if its a retransmission etc (if we ever had the
6713 		 * timestamp fixed to always have the last thing sent this
6714 		 * would not be a issue).
6715 		 */
6716 		return;
6717 	}
6718 	if ((bbr_no_retran && bbr->rc_use_google) &&
6719 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6720 	    (match != BBR_RTT_BY_TIMESTAMP)){
6721 		/*
6722 		 * We only do measurements in google mode
6723 		 * with bbr_no_retran on for sure things.
6724 		 */
6725 		return;
6726 	}
6727 	/* Only update srtt if we know by exact match */
6728 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6729 	if (ack_type == BBR_CUM_ACKED)
6730 		bbr->rc_ack_is_cumack = 1;
6731 	else
6732 		bbr->rc_ack_is_cumack = 0;
6733 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6734 	/*
6735 	 * Note the following code differs to the original
6736 	 * BBR spec. It calls for <= not <. However after a
6737 	 * long discussion in email with Neal, he acknowledged
6738 	 * that it should be < than so that we will have flows
6739 	 * going into probe-rtt (we were seeing cases where that
6740 	 * did not happen and caused ugly things to occur). We
6741 	 * have added this agreed upon fix to our code base.
6742 	 */
6743 	if (rtt < old_rttprop) {
6744 		/* Update when we last saw a rtt drop */
6745 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6746 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6747 	}
6748 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6749 	    match, rsm->r_start, rsm->r_flags);
6750 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6751 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6752 		/*
6753 		 * The RTT-prop moved, reset the target (may be a
6754 		 * nop for some states).
6755 		 */
6756 		bbr_set_state_target(bbr, __LINE__);
6757 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6758 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6759 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6760 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6761 			/* It went up */
6762 			bbr_check_probe_rtt_limits(bbr, cts);
6763 	}
6764 	if ((bbr->rc_use_google == 0) &&
6765 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6766 		/*
6767 		 * We don't do b/w update with
6768 		 * these since they are not really
6769 		 * reliable.
6770 		 */
6771 		return;
6772 	}
6773 	if (bbr->r_ctl.r_app_limited_until &&
6774 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6775 		/* We are no longer app-limited */
6776 		bbr->r_ctl.r_app_limited_until = 0;
6777 	}
6778 	if (bbr->rc_use_google) {
6779 		bbr_google_measurement(bbr, rsm, rtt, cts);
6780 	} else {
6781 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6782 	}
6783 }
6784 
6785 /*
6786  * Convert a timestamp that the main stack
6787  * uses (milliseconds) into one that bbr uses
6788  * (microseconds). Return that converted timestamp.
6789  */
6790 static uint32_t
6791 bbr_ts_convert(uint32_t cts) {
6792 	uint32_t sec, msec;
6793 
6794 	sec = cts / MS_IN_USEC;
6795 	msec = cts - (MS_IN_USEC * sec);
6796 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6797 }
6798 
6799 /*
6800  * Return 0 if we did not update the RTT time, return
6801  * 1 if we did.
6802  */
6803 static int
6804 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6805     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6806 {
6807 	int32_t i;
6808 	uint32_t t, uts = 0;
6809 
6810 	if ((rsm->r_flags & BBR_ACKED) ||
6811 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6812 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6813 		/* Already done */
6814 		return (0);
6815 	}
6816 	if (rsm->r_rtt_not_allowed) {
6817 		/* Not allowed */
6818 		return (0);
6819 	}
6820 	if (rsm->r_rtr_cnt == 1) {
6821 		/*
6822 		 * Only one transmit. Hopefully the normal case.
6823 		 */
6824 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6825 			t = cts - rsm->r_tim_lastsent[0];
6826 		else
6827 			t = 1;
6828 		if ((int)t <= 0)
6829 			t = 1;
6830 		bbr->r_ctl.rc_last_rtt = t;
6831 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6832 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6833 		return (1);
6834 	}
6835 	/* Convert to usecs */
6836 	if ((bbr_can_use_ts_for_rtt == 1) &&
6837 	    (bbr->rc_use_google == 1) &&
6838 	    (ack_type == BBR_CUM_ACKED) &&
6839 	    (to->to_flags & TOF_TS) &&
6840 	    (to->to_tsecr != 0)) {
6841 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6842 		if (t < 1)
6843 			t = 1;
6844 		t *= MS_IN_USEC;
6845 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6846 				    BBR_RTT_BY_TIMESTAMP,
6847 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6848 				    ack_type, to);
6849 		return (1);
6850 	}
6851 	uts = bbr_ts_convert(to->to_tsecr);
6852 	if ((to->to_flags & TOF_TS) &&
6853 	    (to->to_tsecr != 0) &&
6854 	    (ack_type == BBR_CUM_ACKED) &&
6855 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6856 		/*
6857 		 * Now which timestamp does it match? In this block the ACK
6858 		 * may be coming from a previous transmission.
6859 		 */
6860 		uint32_t fudge;
6861 
6862 		fudge = BBR_TIMER_FUDGE;
6863 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6864 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6865 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6866 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6867 					t = cts - rsm->r_tim_lastsent[i];
6868 				else
6869 					t = 1;
6870 				if ((int)t <= 0)
6871 					t = 1;
6872 				bbr->r_ctl.rc_last_rtt = t;
6873 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6874 						    rsm->r_tim_lastsent[i], ack_type, to);
6875 				if ((i + 1) < rsm->r_rtr_cnt) {
6876 					/* Likely */
6877 					return (0);
6878 				} else if (rsm->r_flags & BBR_TLP) {
6879 					bbr->rc_tlp_rtx_out = 0;
6880 				}
6881 				return (1);
6882 			}
6883 		}
6884 		/* Fall through if we can't find a matching timestamp */
6885 	}
6886 	/*
6887 	 * Ok its a SACK block that we retransmitted. or a windows
6888 	 * machine without timestamps. We can tell nothing from the
6889 	 * time-stamp since its not there or the time the peer last
6890 	 * recieved a segment that moved forward its cum-ack point.
6891 	 *
6892 	 * Lets look at the last retransmit and see what we can tell
6893 	 * (with BBR for space we only keep 2 note we have to keep
6894 	 * at least 2 so the map can not be condensed more).
6895 	 */
6896 	i = rsm->r_rtr_cnt - 1;
6897 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6898 		t = cts - rsm->r_tim_lastsent[i];
6899 	else
6900 		goto not_sure;
6901 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6902 		/*
6903 		 * We retransmitted and the ack came back in less
6904 		 * than the smallest rtt we have observed in the
6905 		 * windowed rtt. We most likey did an improper
6906 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6907 		 * the rack-draft.
6908 		 *
6909 		 * Use the prior transmission to update all the
6910 		 * information as long as there is only one prior
6911 		 * transmission.
6912 		 */
6913 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6914 #ifdef BBR_INVARIANTS
6915 			if (rsm->r_rtr_cnt == 1)
6916 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6917 #endif
6918 			i = rsm->r_rtr_cnt - 2;
6919 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6920 				t = cts - rsm->r_tim_lastsent[i];
6921 			else
6922 				t = 1;
6923 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6924 					    rsm->r_tim_lastsent[i], ack_type, to);
6925 			return (0);
6926 		} else {
6927 			/*
6928 			 * Too many prior transmissions, just
6929 			 * updated BBR delivered
6930 			 */
6931 not_sure:
6932 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6933 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6934 		}
6935 	} else {
6936 		/*
6937 		 * We retransmitted it and the retransmit did the
6938 		 * job.
6939 		 */
6940 		if (rsm->r_flags & BBR_TLP)
6941 			bbr->rc_tlp_rtx_out = 0;
6942 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6943 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6944 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6945 		else
6946 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6947 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6948 		return (1);
6949 	}
6950 	return (0);
6951 }
6952 
6953 /*
6954  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6955  */
6956 static void
6957 bbr_log_sack_passed(struct tcpcb *tp,
6958     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6959 {
6960 	struct bbr_sendmap *nrsm;
6961 
6962 	nrsm = rsm;
6963 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6964 	    bbr_head, r_tnext) {
6965 		if (nrsm == rsm) {
6966 			/* Skip orginal segment he is acked */
6967 			continue;
6968 		}
6969 		if (nrsm->r_flags & BBR_ACKED) {
6970 			/* Skip ack'd segments */
6971 			continue;
6972 		}
6973 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6974 			/*
6975 			 * We found one that is already marked
6976 			 * passed, we have been here before and
6977 			 * so all others below this are marked.
6978 			 */
6979 			break;
6980 		}
6981 		BBR_STAT_INC(bbr_sack_passed);
6982 		nrsm->r_flags |= BBR_SACK_PASSED;
6983 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6984 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6985 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6986 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6987 			nrsm->r_flags |= BBR_MARKED_LOST;
6988 		}
6989 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6990 	}
6991 }
6992 
6993 /*
6994  * Returns the number of bytes that were
6995  * newly ack'd by sack blocks.
6996  */
6997 static uint32_t
6998 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6999     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
7000 {
7001 	int32_t times = 0;
7002 	uint32_t start, end, maxseg, changed = 0;
7003 	struct bbr_sendmap *rsm, *nrsm;
7004 	int32_t used_ref = 1;
7005 	uint8_t went_back = 0, went_fwd = 0;
7006 
7007 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7008 	start = sack->start;
7009 	end = sack->end;
7010 	rsm = *prsm;
7011 	if (rsm == NULL)
7012 		used_ref = 0;
7013 
7014 	/* Do we locate the block behind where we last were? */
7015 	if (rsm && SEQ_LT(start, rsm->r_start)) {
7016 		went_back = 1;
7017 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7018 			if (SEQ_GEQ(start, rsm->r_start) &&
7019 			    SEQ_LT(start, rsm->r_end)) {
7020 				goto do_rest_ofb;
7021 			}
7022 		}
7023 	}
7024 start_at_beginning:
7025 	went_fwd = 1;
7026 	/*
7027 	 * Ok lets locate the block where this guy is fwd from rsm (if its
7028 	 * set)
7029 	 */
7030 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7031 		if (SEQ_GEQ(start, rsm->r_start) &&
7032 		    SEQ_LT(start, rsm->r_end)) {
7033 			break;
7034 		}
7035 	}
7036 do_rest_ofb:
7037 	if (rsm == NULL) {
7038 		/*
7039 		 * This happens when we get duplicate sack blocks with the
7040 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7041 		 * will not change there location so we would just start at
7042 		 * the end of the first one and get lost.
7043 		 */
7044 		if (tp->t_flags & TF_SENTFIN) {
7045 			/*
7046 			 * Check to see if we have not logged the FIN that
7047 			 * went out.
7048 			 */
7049 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7050 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7051 				/*
7052 				 * Ok we did not get the FIN logged.
7053 				 */
7054 				nrsm->r_end++;
7055 				rsm = nrsm;
7056 				goto do_rest_ofb;
7057 			}
7058 		}
7059 		if (times == 1) {
7060 #ifdef BBR_INVARIANTS
7061 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7062 			    tp, bbr, sack, to, prsm);
7063 #else
7064 			goto out;
7065 #endif
7066 		}
7067 		times++;
7068 		BBR_STAT_INC(bbr_sack_proc_restart);
7069 		rsm = NULL;
7070 		goto start_at_beginning;
7071 	}
7072 	/* Ok we have an ACK for some piece of rsm */
7073 	if (rsm->r_start != start) {
7074 		/*
7075 		 * Need to split this in two pieces the before and after.
7076 		 */
7077 		if (bbr_sack_mergable(rsm, start, end))
7078 			nrsm = bbr_alloc_full_limit(bbr);
7079 		else
7080 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7081 		if (nrsm == NULL) {
7082 			/* We could not allocate ignore the sack */
7083 			struct sackblk blk;
7084 
7085 			blk.start = start;
7086 			blk.end = end;
7087 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7088 			goto out;
7089 		}
7090 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7091 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7092 		if (rsm->r_in_tmap) {
7093 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7094 			nrsm->r_in_tmap = 1;
7095 		}
7096 		rsm->r_flags &= (~BBR_HAS_FIN);
7097 		rsm = nrsm;
7098 	}
7099 	if (SEQ_GEQ(end, rsm->r_end)) {
7100 		/*
7101 		 * The end of this block is either beyond this guy or right
7102 		 * at this guy.
7103 		 */
7104 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7105 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7106 			changed += (rsm->r_end - rsm->r_start);
7107 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7108 			bbr_log_sack_passed(tp, bbr, rsm);
7109 			if (rsm->r_flags & BBR_MARKED_LOST) {
7110 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7111 			}
7112 			/* Is Reordering occuring? */
7113 			if (rsm->r_flags & BBR_SACK_PASSED) {
7114 				BBR_STAT_INC(bbr_reorder_seen);
7115 				bbr->r_ctl.rc_reorder_ts = cts;
7116 				if (rsm->r_flags & BBR_MARKED_LOST) {
7117 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7118 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7119 						/* LT sampling also needs adjustment */
7120 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7121 				}
7122 			}
7123 			rsm->r_flags |= BBR_ACKED;
7124 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7125 			if (rsm->r_in_tmap) {
7126 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7127 				rsm->r_in_tmap = 0;
7128 			}
7129 		}
7130 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7131 		if (end == rsm->r_end) {
7132 			/* This block only - done */
7133 			goto out;
7134 		}
7135 		/* There is more not coverend by this rsm move on */
7136 		start = rsm->r_end;
7137 		nrsm = TAILQ_NEXT(rsm, r_next);
7138 		rsm = nrsm;
7139 		times = 0;
7140 		goto do_rest_ofb;
7141 	}
7142 	if (rsm->r_flags & BBR_ACKED) {
7143 		/* Been here done that */
7144 		goto out;
7145 	}
7146 	/* Ok we need to split off this one at the tail */
7147 	if (bbr_sack_mergable(rsm, start, end))
7148 		nrsm = bbr_alloc_full_limit(bbr);
7149 	else
7150 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7151 	if (nrsm == NULL) {
7152 		/* failed XXXrrs what can we do but loose the sack info? */
7153 		struct sackblk blk;
7154 
7155 		blk.start = start;
7156 		blk.end = end;
7157 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7158 		goto out;
7159 	}
7160 	/* Clone it */
7161 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7162 	/* The sack block does not cover this guy fully */
7163 	rsm->r_flags &= (~BBR_HAS_FIN);
7164 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7165 	if (rsm->r_in_tmap) {
7166 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7167 		nrsm->r_in_tmap = 1;
7168 	}
7169 	nrsm->r_dupack = 0;
7170 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7171 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7172 	changed += (rsm->r_end - rsm->r_start);
7173 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7174 	bbr_log_sack_passed(tp, bbr, rsm);
7175 	/* Is Reordering occuring? */
7176 	if (rsm->r_flags & BBR_MARKED_LOST) {
7177 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7178 	}
7179 	if (rsm->r_flags & BBR_SACK_PASSED) {
7180 		BBR_STAT_INC(bbr_reorder_seen);
7181 		bbr->r_ctl.rc_reorder_ts = cts;
7182 		if (rsm->r_flags & BBR_MARKED_LOST) {
7183 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7184 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7185 				/* LT sampling also needs adjustment */
7186 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7187 		}
7188 	}
7189 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7190 	rsm->r_flags |= BBR_ACKED;
7191 	if (rsm->r_in_tmap) {
7192 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7193 		rsm->r_in_tmap = 0;
7194 	}
7195 out:
7196 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7197 		/*
7198 		 * Now can we merge this newly acked
7199 		 * block with either the previous or
7200 		 * next block?
7201 		 */
7202 		nrsm = TAILQ_NEXT(rsm, r_next);
7203 		if (nrsm &&
7204 		    (nrsm->r_flags & BBR_ACKED)) {
7205 			/* yep this and next can be merged */
7206 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7207 		}
7208 		/* Now what about the previous? */
7209 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7210 		if (nrsm &&
7211 		    (nrsm->r_flags & BBR_ACKED)) {
7212 			/* yep the previous and this can be merged */
7213 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7214 		}
7215 	}
7216 	if (used_ref == 0) {
7217 		BBR_STAT_INC(bbr_sack_proc_all);
7218 	} else {
7219 		BBR_STAT_INC(bbr_sack_proc_short);
7220 	}
7221 	if (went_fwd && went_back) {
7222 		BBR_STAT_INC(bbr_sack_search_both);
7223 	} else if (went_fwd) {
7224 		BBR_STAT_INC(bbr_sack_search_fwd);
7225 	} else if (went_back) {
7226 		BBR_STAT_INC(bbr_sack_search_back);
7227 	}
7228 	/* Save off where the next seq is */
7229 	if (rsm)
7230 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7231 	else
7232 		bbr->r_ctl.rc_sacklast = NULL;
7233 	*prsm = rsm;
7234 	return (changed);
7235 }
7236 
7237 static void inline
7238 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7239 {
7240 	struct bbr_sendmap *tmap;
7241 
7242 	BBR_STAT_INC(bbr_reneges_seen);
7243 	tmap = NULL;
7244 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7245 		/* Its no longer sacked, mark it so */
7246 		uint32_t oflags;
7247 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7248 #ifdef BBR_INVARIANTS
7249 		if (rsm->r_in_tmap) {
7250 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7251 			    bbr, rsm, rsm->r_flags);
7252 		}
7253 #endif
7254 		oflags = rsm->r_flags;
7255 		if (rsm->r_flags & BBR_MARKED_LOST) {
7256 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7257 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7258 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7259 				/* LT sampling also needs adjustment */
7260 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7261 		}
7262 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7263 		rsm->r_flags |= BBR_WAS_RENEGED;
7264 		rsm->r_flags |= BBR_RXT_CLEARED;
7265 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7266 		/* Rebuild it into our tmap */
7267 		if (tmap == NULL) {
7268 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7269 			tmap = rsm;
7270 		} else {
7271 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7272 			tmap = rsm;
7273 		}
7274 		tmap->r_in_tmap = 1;
7275 		/*
7276 		 * XXXrrs Delivered? Should we do anything here?
7277 		 *
7278 		 * Of course we don't on a rxt timeout so maybe its ok that
7279 		 * we don't?
7280 		 *
7281 		 * For now lets not.
7282 		 */
7283 		rsm = TAILQ_NEXT(rsm, r_next);
7284 	}
7285 	/*
7286 	 * Now lets possibly clear the sack filter so we start recognizing
7287 	 * sacks that cover this area.
7288 	 */
7289 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7290 }
7291 
7292 static void
7293 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7294 {
7295 	struct tcp_bbr *bbr;
7296 	struct bbr_sendmap *rsm;
7297 	uint32_t cts;
7298 
7299 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7300 	cts = bbr->r_ctl.rc_rcvtime;
7301 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7302 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7303 		if ((rsm->r_end - rsm->r_start) <= 1) {
7304 			/* Log out the SYN completely */
7305 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7306 			rsm->r_rtr_bytes = 0;
7307 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7308 			if (rsm->r_in_tmap) {
7309 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7310 				rsm->r_in_tmap = 0;
7311 			}
7312 			if (bbr->r_ctl.rc_next == rsm) {
7313 				/* scoot along the marker */
7314 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7315 			}
7316 			if (to != NULL)
7317 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7318 			bbr_free(bbr, rsm);
7319 		} else {
7320 			/* There is more (Fast open)? strip out SYN. */
7321 			rsm->r_flags &= ~BBR_HAS_SYN;
7322 			rsm->r_start++;
7323 		}
7324 	}
7325 }
7326 
7327 /*
7328  * Returns the number of bytes that were
7329  * acknowledged by SACK blocks.
7330  */
7331 
7332 static uint32_t
7333 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7334     uint32_t *prev_acked)
7335 {
7336 	uint32_t changed, last_seq, entered_recovery = 0;
7337 	struct tcp_bbr *bbr;
7338 	struct bbr_sendmap *rsm;
7339 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7340 	register uint32_t th_ack;
7341 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7342 	uint32_t cts, acked, ack_point, sack_changed = 0;
7343 	uint32_t p_maxseg, maxseg, p_acked = 0;
7344 
7345 	INP_WLOCK_ASSERT(tp->t_inpcb);
7346 	if (th->th_flags & TH_RST) {
7347 		/* We don't log resets */
7348 		return (0);
7349 	}
7350 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7351 	cts = bbr->r_ctl.rc_rcvtime;
7352 
7353 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7354 	changed = 0;
7355 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7356 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7357 	th_ack = th->th_ack;
7358 	if (SEQ_GT(th_ack, tp->snd_una)) {
7359 		acked = th_ack - tp->snd_una;
7360 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7361 		bbr->rc_tp->t_acktime = ticks;
7362 	} else
7363 		acked = 0;
7364 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7365 		/* Only sent here for sack processing */
7366 		goto proc_sack;
7367 	}
7368 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7369 		changed = th_ack - rsm->r_start;
7370 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7371 		/*
7372 		 * For the SYN incoming case we will not have called
7373 		 * tcp_output for the sending of the SYN, so there will be
7374 		 * no map. All other cases should probably be a panic.
7375 		 */
7376 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7377 			/*
7378 			 * We have a timestamp that can be used to generate
7379 			 * an initial RTT.
7380 			 */
7381 			uint32_t ts, now, rtt;
7382 
7383 			ts = bbr_ts_convert(to->to_tsecr);
7384 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7385 			rtt = now - ts;
7386 			if (rtt < 1)
7387 				rtt = 1;
7388 			bbr_log_type_bbrrttprop(bbr, rtt,
7389 						tp->iss, 0, cts,
7390 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7391 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7392 			changed = 1;
7393 			bbr->r_wanted_output = 1;
7394 			goto out;
7395 		}
7396 		goto proc_sack;
7397 	} else if (rsm == NULL) {
7398 		goto out;
7399 	}
7400 	if (changed) {
7401 		/*
7402 		 * The ACK point is advancing to th_ack, we must drop off
7403 		 * the packets in the rack log and calculate any eligble
7404 		 * RTT's.
7405 		 */
7406 		bbr->r_wanted_output = 1;
7407 more:
7408 		if (rsm == NULL) {
7409 			if (tp->t_flags & TF_SENTFIN) {
7410 				/* if we send a FIN we will not hav a map */
7411 				goto proc_sack;
7412 			}
7413 #ifdef BBR_INVARIANTS
7414 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7415 			    tp,
7416 			    th, tp->t_state, bbr,
7417 			    tp->snd_una, tp->snd_max, changed);
7418 #endif
7419 			goto proc_sack;
7420 		}
7421 	}
7422 	if (SEQ_LT(th_ack, rsm->r_start)) {
7423 		/* Huh map is missing this */
7424 #ifdef BBR_INVARIANTS
7425 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7426 		    rsm->r_start,
7427 		    th_ack, tp->t_state,
7428 		    bbr->r_state, bbr);
7429 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7430 #endif
7431 		goto proc_sack;
7432 	} else if (th_ack == rsm->r_start) {
7433 		/* None here to ack */
7434 		goto proc_sack;
7435 	}
7436 	/*
7437 	 * Clear the dup ack counter, it will
7438 	 * either be freed or if there is some
7439 	 * remaining we need to start it at zero.
7440 	 */
7441 	rsm->r_dupack = 0;
7442 	/* Now do we consume the whole thing? */
7443 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7444 		/* Its all consumed. */
7445 		uint32_t left;
7446 
7447 		if (rsm->r_flags & BBR_ACKED) {
7448 			/*
7449 			 * It was acked on the scoreboard -- remove it from
7450 			 * total
7451 			 */
7452 			p_acked += (rsm->r_end - rsm->r_start);
7453 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7454 			if (bbr->r_ctl.rc_sacked == 0)
7455 				bbr->r_ctl.rc_sacklast = NULL;
7456 		} else {
7457 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7458 			if (rsm->r_flags & BBR_MARKED_LOST) {
7459 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7460 			}
7461 			if (rsm->r_flags & BBR_SACK_PASSED) {
7462 				/*
7463 				 * There are acked segments ACKED on the
7464 				 * scoreboard further up. We are seeing
7465 				 * reordering.
7466 				 */
7467 				BBR_STAT_INC(bbr_reorder_seen);
7468 				bbr->r_ctl.rc_reorder_ts = cts;
7469 				if (rsm->r_flags & BBR_MARKED_LOST) {
7470 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7471 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7472 						/* LT sampling also needs adjustment */
7473 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7474 				}
7475 			}
7476 			rsm->r_flags &= ~BBR_MARKED_LOST;
7477 		}
7478 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7479 		rsm->r_rtr_bytes = 0;
7480 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7481 		if (rsm->r_in_tmap) {
7482 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7483 			rsm->r_in_tmap = 0;
7484 		}
7485 		if (bbr->r_ctl.rc_next == rsm) {
7486 			/* scoot along the marker */
7487 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7488 		}
7489 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7490 		/* Adjust the packet counts */
7491 		left = th_ack - rsm->r_end;
7492 		/* Free back to zone */
7493 		bbr_free(bbr, rsm);
7494 		if (left) {
7495 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7496 			goto more;
7497 		}
7498 		goto proc_sack;
7499 	}
7500 	if (rsm->r_flags & BBR_ACKED) {
7501 		/*
7502 		 * It was acked on the scoreboard -- remove it from total
7503 		 * for the part being cum-acked.
7504 		 */
7505 		p_acked += (rsm->r_end - rsm->r_start);
7506 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7507 		if (bbr->r_ctl.rc_sacked == 0)
7508 			bbr->r_ctl.rc_sacklast = NULL;
7509 	} else {
7510 		/*
7511 		 * It was acked up to th_ack point for the first time
7512 		 */
7513 		struct bbr_sendmap lrsm;
7514 
7515 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7516 		lrsm.r_end = th_ack;
7517 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7518 	}
7519 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7520 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7521 		/*
7522 		 * It was marked lost and partly ack'd now
7523 		 * for the first time. We lower the rc_lost_bytes
7524 		 * and still leave it MARKED.
7525 		 */
7526 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7527 	}
7528 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7529 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7530 	rsm->r_rtr_bytes = 0;
7531 	/* adjust packet count */
7532 	rsm->r_start = th_ack;
7533 proc_sack:
7534 	/* Check for reneging */
7535 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7536 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7537 		/*
7538 		 * The peer has moved snd_una up to the edge of this send,
7539 		 * i.e. one that it had previously acked. The only way that
7540 		 * can be true if the peer threw away data (space issues)
7541 		 * that it had previously sacked (else it would have given
7542 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7543 		 * markings here.
7544 		 *
7545 		 * Note we have to look to make sure th_ack is our
7546 		 * rsm->r_start in case we get an old ack where th_ack is
7547 		 * behind snd_una.
7548 		 */
7549 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7550 	}
7551 	if ((to->to_flags & TOF_SACK) == 0) {
7552 		/* We are done nothing left to log */
7553 		goto out;
7554 	}
7555 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7556 	if (rsm) {
7557 		last_seq = rsm->r_end;
7558 	} else {
7559 		last_seq = tp->snd_max;
7560 	}
7561 	/* Sack block processing */
7562 	if (SEQ_GT(th_ack, tp->snd_una))
7563 		ack_point = th_ack;
7564 	else
7565 		ack_point = tp->snd_una;
7566 	for (i = 0; i < to->to_nsacks; i++) {
7567 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7568 		    &sack, sizeof(sack));
7569 		sack.start = ntohl(sack.start);
7570 		sack.end = ntohl(sack.end);
7571 		if (SEQ_GT(sack.end, sack.start) &&
7572 		    SEQ_GT(sack.start, ack_point) &&
7573 		    SEQ_LT(sack.start, tp->snd_max) &&
7574 		    SEQ_GT(sack.end, ack_point) &&
7575 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7576 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7577 			    (SEQ_LT(sack.end, last_seq)) &&
7578 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7579 				/*
7580 				 * Not the last piece and its smaller than
7581 				 * 1/8th of a p_maxseg. We ignore this.
7582 				 */
7583 				BBR_STAT_INC(bbr_runt_sacks);
7584 				continue;
7585 			}
7586 			sack_blocks[num_sack_blks] = sack;
7587 			num_sack_blks++;
7588 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7589 		    SEQ_LEQ(sack.end, th_ack)) {
7590 			/*
7591 			 * Its a D-SACK block.
7592 			 */
7593 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7594 		}
7595 	}
7596 	if (num_sack_blks == 0)
7597 		goto out;
7598 	/*
7599 	 * Sort the SACK blocks so we can update the rack scoreboard with
7600 	 * just one pass.
7601 	 */
7602 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7603 				  num_sack_blks, th->th_ack);
7604 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7605 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7606 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7607 	num_sack_blks = new_sb;
7608 	if (num_sack_blks < 2) {
7609 		goto do_sack_work;
7610 	}
7611 	/* Sort the sacks */
7612 	for (i = 0; i < num_sack_blks; i++) {
7613 		for (j = i + 1; j < num_sack_blks; j++) {
7614 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7615 				sack = sack_blocks[i];
7616 				sack_blocks[i] = sack_blocks[j];
7617 				sack_blocks[j] = sack;
7618 			}
7619 		}
7620 	}
7621 	/*
7622 	 * Now are any of the sack block ends the same (yes some
7623 	 * implememtations send these)?
7624 	 */
7625 again:
7626 	if (num_sack_blks > 1) {
7627 		for (i = 0; i < num_sack_blks; i++) {
7628 			for (j = i + 1; j < num_sack_blks; j++) {
7629 				if (sack_blocks[i].end == sack_blocks[j].end) {
7630 					/*
7631 					 * Ok these two have the same end we
7632 					 * want the smallest end and then
7633 					 * throw away the larger and start
7634 					 * again.
7635 					 */
7636 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7637 						/*
7638 						 * The second block covers
7639 						 * more area use that
7640 						 */
7641 						sack_blocks[i].start = sack_blocks[j].start;
7642 					}
7643 					/*
7644 					 * Now collapse out the dup-sack and
7645 					 * lower the count
7646 					 */
7647 					for (k = (j + 1); k < num_sack_blks; k++) {
7648 						sack_blocks[j].start = sack_blocks[k].start;
7649 						sack_blocks[j].end = sack_blocks[k].end;
7650 						j++;
7651 					}
7652 					num_sack_blks--;
7653 					goto again;
7654 				}
7655 			}
7656 		}
7657 	}
7658 do_sack_work:
7659 	rsm = bbr->r_ctl.rc_sacklast;
7660 	for (i = 0; i < num_sack_blks; i++) {
7661 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7662 		if (acked) {
7663 			bbr->r_wanted_output = 1;
7664 			changed += acked;
7665 			sack_changed += acked;
7666 		}
7667 	}
7668 out:
7669 	*prev_acked = p_acked;
7670 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7671 		/*
7672 		 * Ok we have a high probability that we need to go in to
7673 		 * recovery since we have data sack'd
7674 		 */
7675 		struct bbr_sendmap *rsm;
7676 
7677 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7678 		if (rsm) {
7679 			/* Enter recovery */
7680 			entered_recovery = 1;
7681 			bbr->r_wanted_output = 1;
7682 			/*
7683 			 * When we enter recovery we need to assure we send
7684 			 * one packet.
7685 			 */
7686 			if (bbr->r_ctl.rc_resend == NULL) {
7687 				bbr->r_ctl.rc_resend = rsm;
7688 			}
7689 		}
7690 	}
7691 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7692 		/*
7693 		 * See if we need to rack-retransmit anything if so set it
7694 		 * up as the thing to resend assuming something else is not
7695 		 * already in that position.
7696 		 */
7697 		if (bbr->r_ctl.rc_resend == NULL) {
7698 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7699 		}
7700 	}
7701 	/*
7702 	 * We return the amount that changed via sack, this is used by the
7703 	 * ack-received code to augment what was changed between th_ack <->
7704 	 * snd_una.
7705 	 */
7706 	return (sack_changed);
7707 }
7708 
7709 static void
7710 bbr_strike_dupack(struct tcp_bbr *bbr)
7711 {
7712 	struct bbr_sendmap *rsm;
7713 
7714 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7715 	if (rsm && (rsm->r_dupack < 0xff)) {
7716 		rsm->r_dupack++;
7717 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7718 			bbr->r_wanted_output = 1;
7719 	}
7720 }
7721 
7722 /*
7723  * Return value of 1, we do not need to call bbr_process_data().
7724  * return value of 0, bbr_process_data can be called.
7725  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7726  * its unlocked and probably unsafe to touch the TCB.
7727  */
7728 static int
7729 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7730     struct tcpcb *tp, struct tcpopt *to,
7731     uint32_t tiwin, int32_t tlen,
7732     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7733 {
7734 	int32_t ourfinisacked = 0;
7735 	int32_t acked_amount;
7736 	uint16_t nsegs;
7737 	int32_t acked;
7738 	uint32_t lost, sack_changed = 0;
7739 	struct mbuf *mfree;
7740 	struct tcp_bbr *bbr;
7741 	uint32_t prev_acked = 0;
7742 
7743 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7744 	lost = bbr->r_ctl.rc_lost;
7745 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7746 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7747 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7748 		bbr->r_wanted_output = 1;
7749 		return (1);
7750 	}
7751 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7752 		/* Process the ack */
7753 		if (bbr->rc_in_persist)
7754 			tp->t_rxtshift = 0;
7755 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7756 		        bbr_strike_dupack(bbr);
7757 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7758 	}
7759 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7760 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7761 		/*
7762 		 * Old ack, behind the last one rcv'd or a duplicate ack
7763 		 * with SACK info.
7764 		 */
7765 		if (th->th_ack == tp->snd_una) {
7766 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7767 			if (bbr->r_state == TCPS_SYN_SENT) {
7768 				/*
7769 				 * Special case on where we sent SYN. When
7770 				 * the SYN-ACK is processed in syn_sent
7771 				 * state it bumps the snd_una. This causes
7772 				 * us to hit here even though we did ack 1
7773 				 * byte.
7774 				 *
7775 				 * Go through the nothing left case so we
7776 				 * send data.
7777 				 */
7778 				goto nothing_left;
7779 			}
7780 		}
7781 		return (0);
7782 	}
7783 	/*
7784 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7785 	 * something we sent.
7786 	 */
7787 	if (tp->t_flags & TF_NEEDSYN) {
7788 		/*
7789 		 * T/TCP: Connection was half-synchronized, and our SYN has
7790 		 * been ACK'd (so connection is now fully synchronized).  Go
7791 		 * to non-starred state, increment snd_una for ACK of SYN,
7792 		 * and check if we can do window scaling.
7793 		 */
7794 		tp->t_flags &= ~TF_NEEDSYN;
7795 		tp->snd_una++;
7796 		/* Do window scaling? */
7797 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7798 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7799 			tp->rcv_scale = tp->request_r_scale;
7800 			/* Send window already scaled. */
7801 		}
7802 	}
7803 	INP_WLOCK_ASSERT(tp->t_inpcb);
7804 
7805 	acked = BYTES_THIS_ACK(tp, th);
7806 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7807 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7808 
7809 	/*
7810 	 * If we just performed our first retransmit, and the ACK arrives
7811 	 * within our recovery window, then it was a mistake to do the
7812 	 * retransmit in the first place.  Recover our original cwnd and
7813 	 * ssthresh, and proceed to transmit where we left off.
7814 	 */
7815 	if (tp->t_flags & TF_PREVVALID) {
7816 		tp->t_flags &= ~TF_PREVVALID;
7817 		if (tp->t_rxtshift == 1 &&
7818 		    (int)(ticks - tp->t_badrxtwin) < 0)
7819 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7820 	}
7821 	SOCKBUF_LOCK(&so->so_snd);
7822 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7823 	tp->snd_wnd -= acked_amount;
7824 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7825 	/* NB: sowwakeup_locked() does an implicit unlock. */
7826 	sowwakeup_locked(so);
7827 	m_freem(mfree);
7828 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7829 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7830 	}
7831 	tp->snd_una = th->th_ack;
7832 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7833 	if (IN_RECOVERY(tp->t_flags)) {
7834 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7835 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7836 			tcp_bbr_partialack(tp);
7837 		} else {
7838 			bbr_post_recovery(tp);
7839 		}
7840 	}
7841 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7842 		tp->snd_recover = tp->snd_una;
7843 	}
7844 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7845 		tp->snd_nxt = tp->snd_max;
7846 	}
7847 	if (tp->snd_una == tp->snd_max) {
7848 		/* Nothing left outstanding */
7849 nothing_left:
7850 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7851 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
7852 			bbr->rc_tp->t_acktime = 0;
7853 		if ((sbused(&so->so_snd) == 0) &&
7854 		    (tp->t_flags & TF_SENTFIN)) {
7855 			ourfinisacked = 1;
7856 		}
7857 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7858 		if (bbr->rc_in_persist == 0) {
7859 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7860 		}
7861 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7862 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7863 		/*
7864 		 * We invalidate the last ack here since we
7865 		 * don't want to transfer forward the time
7866 		 * for our sum's calculations.
7867 		 */
7868 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7869 		    (sbavail(&so->so_snd) == 0) &&
7870 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7871 			/*
7872 			 * The socket was gone and the peer sent data, time
7873 			 * to reset him.
7874 			 */
7875 			*ret_val = 1;
7876 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7877 			/* tcp_close will kill the inp pre-log the Reset */
7878 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7879 			tp = tcp_close(tp);
7880 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7881 			BBR_STAT_INC(bbr_dropped_af_data);
7882 			return (1);
7883 		}
7884 		/* Set need output so persist might get set */
7885 		bbr->r_wanted_output = 1;
7886 	}
7887 	if (ofia)
7888 		*ofia = ourfinisacked;
7889 	return (0);
7890 }
7891 
7892 static void
7893 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7894 {
7895 	if (bbr->rc_in_persist == 0) {
7896 		bbr_timer_cancel(bbr, __LINE__, cts);
7897 		bbr->r_ctl.rc_last_delay_val = 0;
7898 		tp->t_rxtshift = 0;
7899 		bbr->rc_in_persist = 1;
7900 		bbr->r_ctl.rc_went_idle_time = cts;
7901 		/* We should be capped when rw went to 0 but just in case */
7902 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7903 		/* Time freezes for the state, so do the accounting now */
7904 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7905 			uint32_t time_in;
7906 
7907 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7908 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7909 				int32_t idx;
7910 
7911 				idx = bbr_state_val(bbr);
7912 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7913 			} else {
7914 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7915 			}
7916 		}
7917 		bbr->r_ctl.rc_bbr_state_time = cts;
7918 	}
7919 }
7920 
7921 static void
7922 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7923 {
7924 	/*
7925 	 * Note that if idle time does not exceed our
7926 	 * threshold, we do nothing continuing the state
7927 	 * transitions we were last walking through.
7928 	 */
7929 	if (idle_time >= bbr_idle_restart_threshold) {
7930 		if (bbr->rc_use_idle_restart) {
7931 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7932 			/*
7933 			 * Set our target using BBR_UNIT, so
7934 			 * we increase at a dramatic rate but
7935 			 * we stop when we get the pipe
7936 			 * full again for our current b/w estimate.
7937 			 */
7938 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7939 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7940 			bbr_set_state_target(bbr, __LINE__);
7941 			/* Now setup our gains to ramp up */
7942 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7943 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7944 			bbr_log_type_statechange(bbr, cts, __LINE__);
7945 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7946 			bbr_substate_change(bbr, cts, __LINE__, 1);
7947 		}
7948 	}
7949 }
7950 
7951 static void
7952 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7953 {
7954 	uint32_t idle_time;
7955 
7956 	if (bbr->rc_in_persist == 0)
7957 		return;
7958 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7959 	bbr->rc_in_persist = 0;
7960 	bbr->rc_hit_state_1 = 0;
7961 	bbr->r_ctl.rc_del_time = cts;
7962 	/*
7963 	 * We invalidate the last ack here since we
7964 	 * don't want to transfer forward the time
7965 	 * for our sum's calculations.
7966 	 */
7967 	if (tcp_in_hpts(bbr->rc_inp)) {
7968 		tcp_hpts_remove(bbr->rc_inp);
7969 		bbr->rc_timer_first = 0;
7970 		bbr->r_ctl.rc_hpts_flags = 0;
7971 		bbr->r_ctl.rc_last_delay_val = 0;
7972 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7973 		bbr->r_agg_early_set = 0;
7974 		bbr->r_ctl.rc_agg_early = 0;
7975 	}
7976 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7977 	if (idle_time >= bbr_rtt_probe_time) {
7978 		/*
7979 		 * This qualifies as a RTT_PROBE session since we drop the
7980 		 * data outstanding to nothing and waited more than
7981 		 * bbr_rtt_probe_time.
7982 		 */
7983 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7984 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7985 	}
7986 	tp->t_rxtshift = 0;
7987 	/*
7988 	 * If in probeBW and we have persisted more than an RTT lets do
7989 	 * special handling.
7990 	 */
7991 	/* Force a time based epoch */
7992 	bbr_set_epoch(bbr, cts, __LINE__);
7993 	/*
7994 	 * Setup the lost so we don't count anything against the guy
7995 	 * we have been stuck with during persists.
7996 	 */
7997 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7998 	/* Time un-freezes for the state */
7999 	bbr->r_ctl.rc_bbr_state_time = cts;
8000 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8001 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8002 		/*
8003 		 * If we are going back to probe-bw
8004 		 * or probe_rtt, we may need to possibly
8005 		 * do a fast restart.
8006 		 */
8007 		bbr_restart_after_idle(bbr, cts, idle_time);
8008 	}
8009 }
8010 
8011 static void
8012 bbr_collapsed_window(struct tcp_bbr *bbr)
8013 {
8014 	/*
8015 	 * Now we must walk the
8016 	 * send map and divide the
8017 	 * ones left stranded. These
8018 	 * guys can't cause us to abort
8019 	 * the connection and are really
8020 	 * "unsent". However if a buggy
8021 	 * client actually did keep some
8022 	 * of the data i.e. collapsed the win
8023 	 * and refused to ack and then opened
8024 	 * the win and acked that data. We would
8025 	 * get into an ack war, the simplier
8026 	 * method then of just pretending we
8027 	 * did not send those segments something
8028 	 * won't work.
8029 	 */
8030 	struct bbr_sendmap *rsm, *nrsm;
8031 	tcp_seq max_seq;
8032 	uint32_t maxseg;
8033 	int can_split = 0;
8034 	int fnd = 0;
8035 
8036 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8037 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8038 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8039 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8040 		/* Find the first seq past or at maxseq */
8041 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8042 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8043 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8044 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8045 			fnd = 1;
8046 			break;
8047 		}
8048 	}
8049 	bbr->rc_has_collapsed = 0;
8050 	if (!fnd) {
8051 		/* Nothing to do strange */
8052 		return;
8053 	}
8054 	/*
8055 	 * Now can we split?
8056 	 *
8057 	 * We don't want to split if splitting
8058 	 * would generate too many small segments
8059 	 * less we let an attacker fragment our
8060 	 * send_map and leave us out of memory.
8061 	 */
8062 	if ((max_seq != rsm->r_start) &&
8063 	    (max_seq != rsm->r_end)){
8064 		/* can we split? */
8065 		int res1, res2;
8066 
8067 		res1 = max_seq - rsm->r_start;
8068 		res2 = rsm->r_end - max_seq;
8069 		if ((res1 >= (maxseg/8)) &&
8070 		    (res2 >= (maxseg/8))) {
8071 			/* No small pieces here */
8072 			can_split = 1;
8073 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8074 			/* We are under the limit */
8075 			can_split = 1;
8076 		}
8077 	}
8078 	/* Ok do we need to split this rsm? */
8079 	if (max_seq == rsm->r_start) {
8080 		/* It's this guy no split required */
8081 		nrsm = rsm;
8082 	} else if (max_seq == rsm->r_end) {
8083 		/* It's the next one no split required. */
8084 		nrsm = TAILQ_NEXT(rsm, r_next);
8085 		if (nrsm == NULL) {
8086 			/* Huh? */
8087 			return;
8088 		}
8089 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8090 		/* yep we need to split it */
8091 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8092 		if (nrsm == NULL) {
8093 			/* failed XXXrrs what can we do mark the whole? */
8094 			nrsm = rsm;
8095 			goto no_split;
8096 		}
8097 		/* Clone it */
8098 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8099 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8100 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8101 		if (rsm->r_in_tmap) {
8102 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8103 			nrsm->r_in_tmap = 1;
8104 		}
8105 	} else {
8106 		/*
8107 		 * Split not allowed just start here just
8108 		 * use this guy.
8109 		 */
8110 		nrsm = rsm;
8111 	}
8112 no_split:
8113 	BBR_STAT_INC(bbr_collapsed_win);
8114 	/* reuse fnd as a count */
8115 	fnd = 0;
8116 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8117 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8118 		fnd++;
8119 		bbr->rc_has_collapsed = 1;
8120 	}
8121 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8122 }
8123 
8124 static void
8125 bbr_un_collapse_window(struct tcp_bbr *bbr)
8126 {
8127 	struct bbr_sendmap *rsm;
8128 	int cleared = 0;
8129 
8130 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8131 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8132 			/* Clear the flag */
8133 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8134 			cleared++;
8135 		} else
8136 			break;
8137 	}
8138 	bbr_log_type_rwnd_collapse(bbr,
8139 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8140 	bbr->rc_has_collapsed = 0;
8141 }
8142 
8143 /*
8144  * Return value of 1, the TCB is unlocked and most
8145  * likely gone, return value of 0, the TCB is still
8146  * locked.
8147  */
8148 static int
8149 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8150     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8151     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8152 {
8153 	/*
8154 	 * Update window information. Don't look at window if no ACK: TAC's
8155 	 * send garbage on first SYN.
8156 	 */
8157 	uint16_t nsegs;
8158 	int32_t tfo_syn;
8159 	struct tcp_bbr *bbr;
8160 
8161 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8162 	INP_WLOCK_ASSERT(tp->t_inpcb);
8163 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8164 	if ((thflags & TH_ACK) &&
8165 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8166 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8167 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8168 		/* keep track of pure window updates */
8169 		if (tlen == 0 &&
8170 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8171 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8172 		tp->snd_wnd = tiwin;
8173 		tp->snd_wl1 = th->th_seq;
8174 		tp->snd_wl2 = th->th_ack;
8175 		if (tp->snd_wnd > tp->max_sndwnd)
8176 			tp->max_sndwnd = tp->snd_wnd;
8177 		bbr->r_wanted_output = 1;
8178 	} else if (thflags & TH_ACK) {
8179 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8180 			tp->snd_wnd = tiwin;
8181 			tp->snd_wl1 = th->th_seq;
8182 			tp->snd_wl2 = th->th_ack;
8183 		}
8184 	}
8185 	if (tp->snd_wnd < ctf_outstanding(tp))
8186 		/* The peer collapsed its window on us */
8187 		bbr_collapsed_window(bbr);
8188  	else if (bbr->rc_has_collapsed)
8189 		bbr_un_collapse_window(bbr);
8190 	/* Was persist timer active and now we have window space? */
8191 	if ((bbr->rc_in_persist != 0) &&
8192 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8193 				bbr_minseg(bbr)))) {
8194 		/*
8195 		 * Make the rate persist at end of persist mode if idle long
8196 		 * enough
8197 		 */
8198 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8199 
8200 		/* Make sure we output to start the timer */
8201 		bbr->r_wanted_output = 1;
8202 	}
8203 	/* Do we need to enter persist? */
8204 	if ((bbr->rc_in_persist == 0) &&
8205 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8206 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8207 	    (tp->snd_max == tp->snd_una) &&
8208 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8209 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8210 		/* No send window.. we must enter persist */
8211 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8212 	}
8213 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8214 		m_freem(m);
8215 		return (0);
8216 	}
8217 	/*
8218 	 * We don't support urgent data but
8219 	 * drag along the up just to make sure
8220 	 * if there is a stack switch no one
8221 	 * is surprised.
8222 	 */
8223 	tp->rcv_up = tp->rcv_nxt;
8224 	INP_WLOCK_ASSERT(tp->t_inpcb);
8225 
8226 	/*
8227 	 * Process the segment text, merging it into the TCP sequencing
8228 	 * queue, and arranging for acknowledgment of receipt if necessary.
8229 	 * This process logically involves adjusting tp->rcv_wnd as data is
8230 	 * presented to the user (this happens in tcp_usrreq.c, case
8231 	 * PRU_RCVD).  If a FIN has already been received on this connection
8232 	 * then we just ignore the text.
8233 	 */
8234 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8235 		   IS_FASTOPEN(tp->t_flags));
8236 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8237 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8238 		tcp_seq save_start = th->th_seq;
8239 		tcp_seq save_rnxt  = tp->rcv_nxt;
8240 		int     save_tlen  = tlen;
8241 
8242 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8243 		/*
8244 		 * Insert segment which includes th into TCP reassembly
8245 		 * queue with control block tp.  Set thflags to whether
8246 		 * reassembly now includes a segment with FIN.  This handles
8247 		 * the common case inline (segment is the next to be
8248 		 * received on an established connection, and the queue is
8249 		 * empty), avoiding linkage into and removal from the queue
8250 		 * and repetition of various conversions. Set DELACK for
8251 		 * segments received in order, but ack immediately when
8252 		 * segments are out of order (so fast retransmit can work).
8253 		 */
8254 		if (th->th_seq == tp->rcv_nxt &&
8255 		    SEGQ_EMPTY(tp) &&
8256 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8257 		    tfo_syn)) {
8258 #ifdef NETFLIX_SB_LIMITS
8259 			u_int mcnt, appended;
8260 
8261 			if (so->so_rcv.sb_shlim) {
8262 				mcnt = m_memcnt(m);
8263 				appended = 0;
8264 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8265 				    CFO_NOSLEEP, NULL) == false) {
8266 					counter_u64_add(tcp_sb_shlim_fails, 1);
8267 					m_freem(m);
8268 					return (0);
8269 				}
8270 			}
8271 
8272 #endif
8273 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8274 				bbr->bbr_segs_rcvd += max(1, nsegs);
8275 				tp->t_flags |= TF_DELACK;
8276 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8277 			} else {
8278 				bbr->r_wanted_output = 1;
8279 				tp->t_flags |= TF_ACKNOW;
8280 			}
8281 			tp->rcv_nxt += tlen;
8282 			if (tlen &&
8283 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8284 			    (tp->t_fbyte_in == 0)) {
8285 				tp->t_fbyte_in = ticks;
8286 				if (tp->t_fbyte_in == 0)
8287 					tp->t_fbyte_in = 1;
8288 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8289 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8290 			}
8291 			thflags = th->th_flags & TH_FIN;
8292 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8293 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8294 			SOCKBUF_LOCK(&so->so_rcv);
8295 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8296 				m_freem(m);
8297 			else
8298 #ifdef NETFLIX_SB_LIMITS
8299 				appended =
8300 #endif
8301 					sbappendstream_locked(&so->so_rcv, m, 0);
8302 			/* NB: sorwakeup_locked() does an implicit unlock. */
8303 			sorwakeup_locked(so);
8304 #ifdef NETFLIX_SB_LIMITS
8305 			if (so->so_rcv.sb_shlim && appended != mcnt)
8306 				counter_fo_release(so->so_rcv.sb_shlim,
8307 				    mcnt - appended);
8308 #endif
8309 
8310 		} else {
8311 			/*
8312 			 * XXX: Due to the header drop above "th" is
8313 			 * theoretically invalid by now.  Fortunately
8314 			 * m_adj() doesn't actually frees any mbufs when
8315 			 * trimming from the head.
8316 			 */
8317 			tcp_seq temp = save_start;
8318 
8319 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8320 			tp->t_flags |= TF_ACKNOW;
8321 			if (tp->t_flags & TF_WAKESOR) {
8322 				tp->t_flags &= ~TF_WAKESOR;
8323 				/* NB: sorwakeup_locked() does an implicit unlock. */
8324 				sorwakeup_locked(so);
8325 			}
8326 		}
8327 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8328 		    (save_tlen > 0) &&
8329 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8330 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8331 				/*
8332 				 * DSACK actually handled in the fastpath
8333 				 * above.
8334 				 */
8335 				tcp_update_sack_list(tp, save_start,
8336 				    save_start + save_tlen);
8337 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8338 				if ((tp->rcv_numsacks >= 1) &&
8339 				    (tp->sackblks[0].end == save_start)) {
8340 					/*
8341 					 * Partial overlap, recorded at todrop
8342 					 * above.
8343 					 */
8344 					tcp_update_sack_list(tp,
8345 					    tp->sackblks[0].start,
8346 					    tp->sackblks[0].end);
8347 				} else {
8348 					tcp_update_dsack_list(tp, save_start,
8349 					    save_start + save_tlen);
8350 				}
8351 			} else if (tlen >= save_tlen) {
8352 				/* Update of sackblks. */
8353 				tcp_update_dsack_list(tp, save_start,
8354 				    save_start + save_tlen);
8355 			} else if (tlen > 0) {
8356 				tcp_update_dsack_list(tp, save_start,
8357 				    save_start + tlen);
8358 			}
8359 		}
8360 	} else {
8361 		m_freem(m);
8362 		thflags &= ~TH_FIN;
8363 	}
8364 
8365 	/*
8366 	 * If FIN is received ACK the FIN and let the user know that the
8367 	 * connection is closing.
8368 	 */
8369 	if (thflags & TH_FIN) {
8370 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8371 			/* The socket upcall is handled by socantrcvmore. */
8372 			socantrcvmore(so);
8373 			/*
8374 			 * If connection is half-synchronized (ie NEEDSYN
8375 			 * flag on) then delay ACK, so it may be piggybacked
8376 			 * when SYN is sent. Otherwise, since we received a
8377 			 * FIN then no more input can be expected, send ACK
8378 			 * now.
8379 			 */
8380 			if (tp->t_flags & TF_NEEDSYN) {
8381 				tp->t_flags |= TF_DELACK;
8382 				bbr_timer_cancel(bbr,
8383 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8384 			} else {
8385 				tp->t_flags |= TF_ACKNOW;
8386 			}
8387 			tp->rcv_nxt++;
8388 		}
8389 		switch (tp->t_state) {
8390 			/*
8391 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8392 			 * CLOSE_WAIT state.
8393 			 */
8394 		case TCPS_SYN_RECEIVED:
8395 			tp->t_starttime = ticks;
8396 			/* FALLTHROUGH */
8397 		case TCPS_ESTABLISHED:
8398 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8399 			break;
8400 
8401 			/*
8402 			 * If still in FIN_WAIT_1 STATE FIN has not been
8403 			 * acked so enter the CLOSING state.
8404 			 */
8405 		case TCPS_FIN_WAIT_1:
8406 			tcp_state_change(tp, TCPS_CLOSING);
8407 			break;
8408 
8409 			/*
8410 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8411 			 * starting the time-wait timer, turning off the
8412 			 * other standard timers.
8413 			 */
8414 		case TCPS_FIN_WAIT_2:
8415 			bbr->rc_timer_first = 1;
8416 			bbr_timer_cancel(bbr,
8417 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8418 			INP_WLOCK_ASSERT(tp->t_inpcb);
8419 			tcp_twstart(tp);
8420 			return (1);
8421 		}
8422 	}
8423 	/*
8424 	 * Return any desired output.
8425 	 */
8426 	if ((tp->t_flags & TF_ACKNOW) ||
8427 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8428 		bbr->r_wanted_output = 1;
8429 	}
8430 	INP_WLOCK_ASSERT(tp->t_inpcb);
8431 	return (0);
8432 }
8433 
8434 /*
8435  * Here nothing is really faster, its just that we
8436  * have broken out the fast-data path also just like
8437  * the fast-ack. Return 1 if we processed the packet
8438  * return 0 if you need to take the "slow-path".
8439  */
8440 static int
8441 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8442     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8443     uint32_t tiwin, int32_t nxt_pkt)
8444 {
8445 	uint16_t nsegs;
8446 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8447 	struct tcp_bbr *bbr;
8448 #ifdef NETFLIX_SB_LIMITS
8449 	u_int mcnt, appended;
8450 #endif
8451 #ifdef TCPDEBUG
8452 	/*
8453 	 * The size of tcp_saveipgen must be the size of the max ip header,
8454 	 * now IPv6.
8455 	 */
8456 	u_char tcp_saveipgen[IP6_HDR_LEN];
8457 	struct tcphdr tcp_savetcp;
8458 	short ostate = 0;
8459 
8460 #endif
8461 	/* On the hpts and we would have called output */
8462 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8463 
8464 	/*
8465 	 * If last ACK falls within this segment's sequence numbers, record
8466 	 * the timestamp. NOTE that the test is modified according to the
8467 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8468 	 */
8469 	if (bbr->r_ctl.rc_resend != NULL) {
8470 		return (0);
8471 	}
8472 	if (tiwin && tiwin != tp->snd_wnd) {
8473 		return (0);
8474 	}
8475 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8476 		return (0);
8477 	}
8478 	if (__predict_false((to->to_flags & TOF_TS) &&
8479 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8480 		return (0);
8481 	}
8482 	if (__predict_false((th->th_ack != tp->snd_una))) {
8483 		return (0);
8484 	}
8485 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8486 		return (0);
8487 	}
8488 	if ((to->to_flags & TOF_TS) != 0 &&
8489 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8490 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8491 		tp->ts_recent = to->to_tsval;
8492 	}
8493 	/*
8494 	 * This is a pure, in-sequence data packet with nothing on the
8495 	 * reassembly queue and we have enough buffer space to take it.
8496 	 */
8497 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8498 
8499 #ifdef NETFLIX_SB_LIMITS
8500 	if (so->so_rcv.sb_shlim) {
8501 		mcnt = m_memcnt(m);
8502 		appended = 0;
8503 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8504 		    CFO_NOSLEEP, NULL) == false) {
8505 			counter_u64_add(tcp_sb_shlim_fails, 1);
8506 			m_freem(m);
8507 			return (1);
8508 		}
8509 	}
8510 #endif
8511 	/* Clean receiver SACK report if present */
8512 	if (tp->rcv_numsacks)
8513 		tcp_clean_sackreport(tp);
8514 	KMOD_TCPSTAT_INC(tcps_preddat);
8515 	tp->rcv_nxt += tlen;
8516 	if (tlen &&
8517 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8518 	    (tp->t_fbyte_in == 0)) {
8519 		tp->t_fbyte_in = ticks;
8520 		if (tp->t_fbyte_in == 0)
8521 			tp->t_fbyte_in = 1;
8522 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8523 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8524 	}
8525 	/*
8526 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8527 	 */
8528 	tp->snd_wl1 = th->th_seq;
8529 	/*
8530 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8531 	 */
8532 	tp->rcv_up = tp->rcv_nxt;
8533 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8534 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8535 #ifdef TCPDEBUG
8536 	if (so->so_options & SO_DEBUG)
8537 		tcp_trace(TA_INPUT, ostate, tp,
8538 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8539 #endif
8540 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8541 
8542 	/* Add data to socket buffer. */
8543 	SOCKBUF_LOCK(&so->so_rcv);
8544 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8545 		m_freem(m);
8546 	} else {
8547 		/*
8548 		 * Set new socket buffer size. Give up when limit is
8549 		 * reached.
8550 		 */
8551 		if (newsize)
8552 			if (!sbreserve_locked(&so->so_rcv,
8553 			    newsize, so, NULL))
8554 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8555 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8556 
8557 #ifdef NETFLIX_SB_LIMITS
8558 		appended =
8559 #endif
8560 			sbappendstream_locked(&so->so_rcv, m, 0);
8561 		ctf_calc_rwin(so, tp);
8562 	}
8563 	/* NB: sorwakeup_locked() does an implicit unlock. */
8564 	sorwakeup_locked(so);
8565 #ifdef NETFLIX_SB_LIMITS
8566 	if (so->so_rcv.sb_shlim && mcnt != appended)
8567 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8568 #endif
8569 	if (DELAY_ACK(tp, bbr, nsegs)) {
8570 		bbr->bbr_segs_rcvd += max(1, nsegs);
8571 		tp->t_flags |= TF_DELACK;
8572 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8573 	} else {
8574 		bbr->r_wanted_output = 1;
8575 		tp->t_flags |= TF_ACKNOW;
8576 	}
8577 	return (1);
8578 }
8579 
8580 /*
8581  * This subfunction is used to try to highly optimize the
8582  * fast path. We again allow window updates that are
8583  * in sequence to remain in the fast-path. We also add
8584  * in the __predict's to attempt to help the compiler.
8585  * Note that if we return a 0, then we can *not* process
8586  * it and the caller should push the packet into the
8587  * slow-path. If we return 1, then all is well and
8588  * the packet is fully processed.
8589  */
8590 static int
8591 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8592     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8593     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8594 {
8595 	int32_t acked;
8596 	uint16_t nsegs;
8597 	uint32_t sack_changed;
8598 #ifdef TCPDEBUG
8599 	/*
8600 	 * The size of tcp_saveipgen must be the size of the max ip header,
8601 	 * now IPv6.
8602 	 */
8603 	u_char tcp_saveipgen[IP6_HDR_LEN];
8604 	struct tcphdr tcp_savetcp;
8605 	short ostate = 0;
8606 
8607 #endif
8608 	uint32_t prev_acked = 0;
8609 	struct tcp_bbr *bbr;
8610 
8611 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8612 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8613 		return (0);
8614 	}
8615 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8616 		/* Above what we have sent? */
8617 		return (0);
8618 	}
8619 	if (__predict_false(tiwin == 0)) {
8620 		/* zero window */
8621 		return (0);
8622 	}
8623 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8624 		/* We need a SYN or a FIN, unlikely.. */
8625 		return (0);
8626 	}
8627 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8628 		/* Timestamp is behind .. old ack with seq wrap? */
8629 		return (0);
8630 	}
8631 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8632 		/* Still recovering */
8633 		return (0);
8634 	}
8635 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8636 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8637 		/* We are retransmitting */
8638 		return (0);
8639 	}
8640 	if (__predict_false(bbr->rc_in_persist != 0)) {
8641 		/* In persist mode */
8642 		return (0);
8643 	}
8644 	if (bbr->r_ctl.rc_sacked) {
8645 		/* We have sack holes on our scoreboard */
8646 		return (0);
8647 	}
8648 	/* Ok if we reach here, we can process a fast-ack */
8649 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8650 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8651 	/*
8652 	 * We never detect loss in fast ack [we can't
8653 	 * have a sack and can't be in recovery so
8654 	 * we always pass 0 (nothing detected)].
8655 	 */
8656 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8657 	/* Did the window get updated? */
8658 	if (tiwin != tp->snd_wnd) {
8659 		tp->snd_wnd = tiwin;
8660 		tp->snd_wl1 = th->th_seq;
8661 		if (tp->snd_wnd > tp->max_sndwnd)
8662 			tp->max_sndwnd = tp->snd_wnd;
8663 	}
8664 	/* Do we need to exit persists? */
8665 	if ((bbr->rc_in_persist != 0) &&
8666 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8667 			       bbr_minseg(bbr)))) {
8668 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8669 		bbr->r_wanted_output = 1;
8670 	}
8671 	/* Do we need to enter persists? */
8672 	if ((bbr->rc_in_persist == 0) &&
8673 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8674 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8675 	    (tp->snd_max == tp->snd_una) &&
8676 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8677 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8678 		/* No send window.. we must enter persist */
8679 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8680 	}
8681 	/*
8682 	 * If last ACK falls within this segment's sequence numbers, record
8683 	 * the timestamp. NOTE that the test is modified according to the
8684 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8685 	 */
8686 	if ((to->to_flags & TOF_TS) != 0 &&
8687 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8688 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8689 		tp->ts_recent = to->to_tsval;
8690 	}
8691 	/*
8692 	 * This is a pure ack for outstanding data.
8693 	 */
8694 	KMOD_TCPSTAT_INC(tcps_predack);
8695 
8696 	/*
8697 	 * "bad retransmit" recovery.
8698 	 */
8699 	if (tp->t_flags & TF_PREVVALID) {
8700 		tp->t_flags &= ~TF_PREVVALID;
8701 		if (tp->t_rxtshift == 1 &&
8702 		    (int)(ticks - tp->t_badrxtwin) < 0)
8703 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8704 	}
8705 	/*
8706 	 * Recalculate the transmit timer / rtt.
8707 	 *
8708 	 * Some boxes send broken timestamp replies during the SYN+ACK
8709 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8710 	 * and blow up the retransmit timer.
8711 	 */
8712 	acked = BYTES_THIS_ACK(tp, th);
8713 
8714 #ifdef TCP_HHOOK
8715 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8716 	hhook_run_tcp_est_in(tp, th, to);
8717 #endif
8718 
8719 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8720 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8721 	sbdrop(&so->so_snd, acked);
8722 
8723 	if (SEQ_GT(th->th_ack, tp->snd_una))
8724 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8725 	tp->snd_una = th->th_ack;
8726 	if (tp->snd_wnd < ctf_outstanding(tp))
8727 		/* The peer collapsed its window on us */
8728 		bbr_collapsed_window(bbr);
8729 	else if (bbr->rc_has_collapsed)
8730 		bbr_un_collapse_window(bbr);
8731 
8732 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8733 		tp->snd_recover = tp->snd_una;
8734 	}
8735 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8736 	/*
8737 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8738 	 */
8739 	tp->snd_wl2 = th->th_ack;
8740 	m_freem(m);
8741 	/*
8742 	 * If all outstanding data are acked, stop retransmit timer,
8743 	 * otherwise restart timer using current (possibly backed-off)
8744 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8745 	 * If data are ready to send, let tcp_output decide between more
8746 	 * output or persist.
8747 	 */
8748 #ifdef TCPDEBUG
8749 	if (so->so_options & SO_DEBUG)
8750 		tcp_trace(TA_INPUT, ostate, tp,
8751 		    (void *)tcp_saveipgen,
8752 		    &tcp_savetcp, 0);
8753 #endif
8754 	/* Wake up the socket if we have room to write more */
8755 	sowwakeup(so);
8756 	if (tp->snd_una == tp->snd_max) {
8757 		/* Nothing left outstanding */
8758 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8759 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8760 			bbr->rc_tp->t_acktime = 0;
8761 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8762 		if (bbr->rc_in_persist == 0) {
8763 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8764 		}
8765 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8766 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8767 		/*
8768 		 * We invalidate the last ack here since we
8769 		 * don't want to transfer forward the time
8770 		 * for our sum's calculations.
8771 		 */
8772 		bbr->r_wanted_output = 1;
8773 	}
8774 	if (sbavail(&so->so_snd)) {
8775 		bbr->r_wanted_output = 1;
8776 	}
8777 	return (1);
8778 }
8779 
8780 /*
8781  * Return value of 1, the TCB is unlocked and most
8782  * likely gone, return value of 0, the TCB is still
8783  * locked.
8784  */
8785 static int
8786 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8787     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8788     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8789 {
8790 	int32_t todrop;
8791 	int32_t ourfinisacked = 0;
8792 	struct tcp_bbr *bbr;
8793 	int32_t ret_val = 0;
8794 
8795 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8796 	ctf_calc_rwin(so, tp);
8797 	/*
8798 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8799 	 * SYN, drop the input. if seg contains a RST, then drop the
8800 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8801 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8802 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8803 	 * not support ECN so we will not say we are capable. if SYN has
8804 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8805 	 * segment to be acked (eventually) continue processing rest of
8806 	 * data/controls, beginning with URG
8807 	 */
8808 	if ((thflags & TH_ACK) &&
8809 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8810 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8811 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8812 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8813 		return (1);
8814 	}
8815 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8816 		TCP_PROBE5(connect__refused, NULL, tp,
8817 		    mtod(m, const char *), tp, th);
8818 		tp = tcp_drop(tp, ECONNREFUSED);
8819 		ctf_do_drop(m, tp);
8820 		return (1);
8821 	}
8822 	if (thflags & TH_RST) {
8823 		ctf_do_drop(m, tp);
8824 		return (1);
8825 	}
8826 	if (!(thflags & TH_SYN)) {
8827 		ctf_do_drop(m, tp);
8828 		return (1);
8829 	}
8830 	tp->irs = th->th_seq;
8831 	tcp_rcvseqinit(tp);
8832 	if (thflags & TH_ACK) {
8833 		int tfo_partial = 0;
8834 
8835 		KMOD_TCPSTAT_INC(tcps_connects);
8836 		soisconnected(so);
8837 #ifdef MAC
8838 		mac_socketpeer_set_from_mbuf(m, so);
8839 #endif
8840 		/* Do window scaling on this connection? */
8841 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8842 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8843 			tp->rcv_scale = tp->request_r_scale;
8844 		}
8845 		tp->rcv_adv += min(tp->rcv_wnd,
8846 		    TCP_MAXWIN << tp->rcv_scale);
8847 		/*
8848 		 * If not all the data that was sent in the TFO SYN
8849 		 * has been acked, resend the remainder right away.
8850 		 */
8851 		if (IS_FASTOPEN(tp->t_flags) &&
8852 		    (tp->snd_una != tp->snd_max)) {
8853 			tp->snd_nxt = th->th_ack;
8854 			tfo_partial = 1;
8855 		}
8856 		/*
8857 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8858 		 * will be turned on later.
8859 		 */
8860 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8861 			bbr->bbr_segs_rcvd += 1;
8862 			tp->t_flags |= TF_DELACK;
8863 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8864 		} else {
8865 			bbr->r_wanted_output = 1;
8866 			tp->t_flags |= TF_ACKNOW;
8867 		}
8868 		if (SEQ_GT(th->th_ack, tp->iss)) {
8869 			/*
8870 			 * The SYN is acked
8871 			 * handle it specially.
8872 			 */
8873 			bbr_log_syn(tp, to);
8874 		}
8875 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8876 			/*
8877 			 * We advance snd_una for the
8878 			 * fast open case. If th_ack is
8879 			 * acknowledging data beyond
8880 			 * snd_una we can't just call
8881 			 * ack-processing since the
8882 			 * data stream in our send-map
8883 			 * will start at snd_una + 1 (one
8884 			 * beyond the SYN). If its just
8885 			 * equal we don't need to do that
8886 			 * and there is no send_map.
8887 			 */
8888 			tp->snd_una++;
8889 		}
8890 		/*
8891 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8892 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8893 		 */
8894 		tp->t_starttime = ticks;
8895 		if (tp->t_flags & TF_NEEDFIN) {
8896 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8897 			tp->t_flags &= ~TF_NEEDFIN;
8898 			thflags &= ~TH_SYN;
8899 		} else {
8900 			tcp_state_change(tp, TCPS_ESTABLISHED);
8901 			TCP_PROBE5(connect__established, NULL, tp,
8902 			    mtod(m, const char *), tp, th);
8903 			cc_conn_init(tp);
8904 		}
8905 	} else {
8906 		/*
8907 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8908 		 * open.  If segment contains CC option and there is a
8909 		 * cached CC, apply TAO test. If it succeeds, connection is *
8910 		 * half-synchronized. Otherwise, do 3-way handshake:
8911 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8912 		 * there was no CC option, clear cached CC value.
8913 		 */
8914 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
8915 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8916 	}
8917 	INP_WLOCK_ASSERT(tp->t_inpcb);
8918 	/*
8919 	 * Advance th->th_seq to correspond to first data byte. If data,
8920 	 * trim to stay within window, dropping FIN if necessary.
8921 	 */
8922 	th->th_seq++;
8923 	if (tlen > tp->rcv_wnd) {
8924 		todrop = tlen - tp->rcv_wnd;
8925 		m_adj(m, -todrop);
8926 		tlen = tp->rcv_wnd;
8927 		thflags &= ~TH_FIN;
8928 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8929 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8930 	}
8931 	tp->snd_wl1 = th->th_seq - 1;
8932 	tp->rcv_up = th->th_seq;
8933 	/*
8934 	 * Client side of transaction: already sent SYN and data. If the
8935 	 * remote host used T/TCP to validate the SYN, our data will be
8936 	 * ACK'd; if so, enter normal data segment processing in the middle
8937 	 * of step 5, ack processing. Otherwise, goto step 6.
8938 	 */
8939 	if (thflags & TH_ACK) {
8940 		if ((to->to_flags & TOF_TS) != 0) {
8941 			uint32_t t, rtt;
8942 
8943 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8944 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8945 				rtt = t - to->to_tsecr;
8946 				if (rtt == 0) {
8947 					rtt = 1;
8948 				}
8949 				rtt *= MS_IN_USEC;
8950 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8951 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8952 						       rtt, bbr->r_ctl.rc_rcvtime);
8953 			}
8954 		}
8955 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8956 			return (ret_val);
8957 		/* We may have changed to FIN_WAIT_1 above */
8958 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8959 			/*
8960 			 * In FIN_WAIT_1 STATE in addition to the processing
8961 			 * for the ESTABLISHED state if our FIN is now
8962 			 * acknowledged then enter FIN_WAIT_2.
8963 			 */
8964 			if (ourfinisacked) {
8965 				/*
8966 				 * If we can't receive any more data, then
8967 				 * closing user can proceed. Starting the
8968 				 * timer is contrary to the specification,
8969 				 * but if we don't get a FIN we'll hang
8970 				 * forever.
8971 				 *
8972 				 * XXXjl: we should release the tp also, and
8973 				 * use a compressed state.
8974 				 */
8975 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8976 					soisdisconnected(so);
8977 					tcp_timer_activate(tp, TT_2MSL,
8978 					    (tcp_fast_finwait2_recycle ?
8979 					    tcp_finwait2_timeout :
8980 					    TP_MAXIDLE(tp)));
8981 				}
8982 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8983 			}
8984 		}
8985 	}
8986 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8987 	    tiwin, thflags, nxt_pkt));
8988 }
8989 
8990 /*
8991  * Return value of 1, the TCB is unlocked and most
8992  * likely gone, return value of 0, the TCB is still
8993  * locked.
8994  */
8995 static int
8996 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8997 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8998 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8999 {
9000 	int32_t ourfinisacked = 0;
9001 	int32_t ret_val;
9002 	struct tcp_bbr *bbr;
9003 
9004 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9005 	ctf_calc_rwin(so, tp);
9006 	if ((thflags & TH_ACK) &&
9007 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9008 	     SEQ_GT(th->th_ack, tp->snd_max))) {
9009 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9010 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9011 		return (1);
9012 	}
9013 	if (IS_FASTOPEN(tp->t_flags)) {
9014 		/*
9015 		 * When a TFO connection is in SYN_RECEIVED, the only valid
9016 		 * packets are the initial SYN, a retransmit/copy of the
9017 		 * initial SYN (possibly with a subset of the original
9018 		 * data), a valid ACK, a FIN, or a RST.
9019 		 */
9020 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9021 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9022 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9023 			return (1);
9024 		} else if (thflags & TH_SYN) {
9025 			/* non-initial SYN is ignored */
9026 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9027 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9028 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9029 				ctf_do_drop(m, NULL);
9030 				return (0);
9031 			}
9032 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9033 			ctf_do_drop(m, NULL);
9034 			return (0);
9035 		}
9036 	}
9037 	if ((thflags & TH_RST) ||
9038 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9039 		return (ctf_process_rst(m, th, so, tp));
9040 	/*
9041 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9042 	 * it's less than ts_recent, drop it.
9043 	 */
9044 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9045 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9046 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9047 			return (ret_val);
9048 	}
9049 	/*
9050 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9051 	 * this connection before trimming the data to fit the receive
9052 	 * window.  Check the sequence number versus IRS since we know the
9053 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9054 	 * "LAND" DoS attack.
9055 	 */
9056 	if (SEQ_LT(th->th_seq, tp->irs)) {
9057 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9058 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9059 		return (1);
9060 	}
9061 	INP_WLOCK_ASSERT(tp->t_inpcb);
9062 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9063 		return (ret_val);
9064 	}
9065 	/*
9066 	 * If last ACK falls within this segment's sequence numbers, record
9067 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9068 	 * from the latest proposal of the tcplw@cray.com list (Braden
9069 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9070 	 * with our earlier PAWS tests, so this check should be solely
9071 	 * predicated on the sequence space of this segment. 3) That we
9072 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9073 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9074 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9075 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9076 	 * p.869. In such cases, we can still calculate the RTT correctly
9077 	 * when RCV.NXT == Last.ACK.Sent.
9078 	 */
9079 	if ((to->to_flags & TOF_TS) != 0 &&
9080 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9081 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9082 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9083 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9084 		tp->ts_recent = to->to_tsval;
9085 	}
9086 	tp->snd_wnd = tiwin;
9087 	/*
9088 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9089 	 * is on (half-synchronized state), then queue data for later
9090 	 * processing; else drop segment and return.
9091 	 */
9092 	if ((thflags & TH_ACK) == 0) {
9093 		if (IS_FASTOPEN(tp->t_flags)) {
9094 			cc_conn_init(tp);
9095 		}
9096 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9097 					 tiwin, thflags, nxt_pkt));
9098 	}
9099 	KMOD_TCPSTAT_INC(tcps_connects);
9100 	soisconnected(so);
9101 	/* Do window scaling? */
9102 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9103 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9104 		tp->rcv_scale = tp->request_r_scale;
9105 	}
9106 	/*
9107 	 * ok for the first time in lets see if we can use the ts to figure
9108 	 * out what the initial RTT was.
9109 	 */
9110 	if ((to->to_flags & TOF_TS) != 0) {
9111 		uint32_t t, rtt;
9112 
9113 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9114 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9115 			rtt = t - to->to_tsecr;
9116 			if (rtt == 0) {
9117 				rtt = 1;
9118 			}
9119 			rtt *= MS_IN_USEC;
9120 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9121 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9122 		}
9123 	}
9124 	/* Drop off any SYN in the send map (probably not there)  */
9125 	if (thflags & TH_ACK)
9126 		bbr_log_syn(tp, to);
9127 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9128 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9129 		tp->t_tfo_pending = NULL;
9130 	}
9131 	/*
9132 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9133 	 * FIN-WAIT-1
9134 	 */
9135 	tp->t_starttime = ticks;
9136 	if (tp->t_flags & TF_NEEDFIN) {
9137 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9138 		tp->t_flags &= ~TF_NEEDFIN;
9139 	} else {
9140 		tcp_state_change(tp, TCPS_ESTABLISHED);
9141 		TCP_PROBE5(accept__established, NULL, tp,
9142 			   mtod(m, const char *), tp, th);
9143 		/*
9144 		 * TFO connections call cc_conn_init() during SYN
9145 		 * processing.  Calling it again here for such connections
9146 		 * is not harmless as it would undo the snd_cwnd reduction
9147 		 * that occurs when a TFO SYN|ACK is retransmitted.
9148 		 */
9149 		if (!IS_FASTOPEN(tp->t_flags))
9150 			cc_conn_init(tp);
9151 	}
9152 	/*
9153 	 * Account for the ACK of our SYN prior to
9154 	 * regular ACK processing below, except for
9155 	 * simultaneous SYN, which is handled later.
9156 	 */
9157 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9158 		tp->snd_una++;
9159 	/*
9160 	 * If segment contains data or ACK, will call tcp_reass() later; if
9161 	 * not, do so now to pass queued data to user.
9162 	 */
9163 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9164 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9165 			(struct mbuf *)0);
9166 		if (tp->t_flags & TF_WAKESOR) {
9167 			tp->t_flags &= ~TF_WAKESOR;
9168 			/* NB: sorwakeup_locked() does an implicit unlock. */
9169 			sorwakeup_locked(so);
9170 		}
9171 	}
9172 	tp->snd_wl1 = th->th_seq - 1;
9173 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9174 		return (ret_val);
9175 	}
9176 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9177 		/* We could have went to FIN_WAIT_1 (or EST) above */
9178 		/*
9179 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9180 		 * ESTABLISHED state if our FIN is now acknowledged then
9181 		 * enter FIN_WAIT_2.
9182 		 */
9183 		if (ourfinisacked) {
9184 			/*
9185 			 * If we can't receive any more data, then closing
9186 			 * user can proceed. Starting the timer is contrary
9187 			 * to the specification, but if we don't get a FIN
9188 			 * we'll hang forever.
9189 			 *
9190 			 * XXXjl: we should release the tp also, and use a
9191 			 * compressed state.
9192 			 */
9193 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9194 				soisdisconnected(so);
9195 				tcp_timer_activate(tp, TT_2MSL,
9196 						   (tcp_fast_finwait2_recycle ?
9197 						    tcp_finwait2_timeout :
9198 						    TP_MAXIDLE(tp)));
9199 			}
9200 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9201 		}
9202 	}
9203 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9204 				 tiwin, thflags, nxt_pkt));
9205 }
9206 
9207 /*
9208  * Return value of 1, the TCB is unlocked and most
9209  * likely gone, return value of 0, the TCB is still
9210  * locked.
9211  */
9212 static int
9213 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9214     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9215     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9216 {
9217 	struct tcp_bbr *bbr;
9218 	int32_t ret_val;
9219 
9220 	/*
9221 	 * Header prediction: check for the two common cases of a
9222 	 * uni-directional data xfer.  If the packet has no control flags,
9223 	 * is in-sequence, the window didn't change and we're not
9224 	 * retransmitting, it's a candidate.  If the length is zero and the
9225 	 * ack moved forward, we're the sender side of the xfer.  Just free
9226 	 * the data acked & wake any higher level process that was blocked
9227 	 * waiting for space.  If the length is non-zero and the ack didn't
9228 	 * move, we're the receiver side.  If we're getting packets in-order
9229 	 * (the reassembly queue is empty), add the data toc The socket
9230 	 * buffer and note that we need a delayed ack. Make sure that the
9231 	 * hidden state-flags are also off. Since we check for
9232 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9233 	 */
9234 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9235 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9236 		/*
9237 		 * If we have delived under 4 segments increase the initial
9238 		 * window if raised by the peer. We use this to determine
9239 		 * dynamic and static rwnd's at the end of a connection.
9240 		 */
9241 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9242 	}
9243 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9244 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9245 	    __predict_true(SEGQ_EMPTY(tp)) &&
9246 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9247 		if (tlen == 0) {
9248 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9249 			    tiwin, nxt_pkt, iptos)) {
9250 				return (0);
9251 			}
9252 		} else {
9253 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9254 			    tiwin, nxt_pkt)) {
9255 				return (0);
9256 			}
9257 		}
9258 	}
9259 	ctf_calc_rwin(so, tp);
9260 
9261 	if ((thflags & TH_RST) ||
9262 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9263 		return (ctf_process_rst(m, th, so, tp));
9264 	/*
9265 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9266 	 * synchronized state.
9267 	 */
9268 	if (thflags & TH_SYN) {
9269 		ctf_challenge_ack(m, th, tp, &ret_val);
9270 		return (ret_val);
9271 	}
9272 	/*
9273 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9274 	 * it's less than ts_recent, drop it.
9275 	 */
9276 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9277 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9278 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9279 			return (ret_val);
9280 	}
9281 	INP_WLOCK_ASSERT(tp->t_inpcb);
9282 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9283 		return (ret_val);
9284 	}
9285 	/*
9286 	 * If last ACK falls within this segment's sequence numbers, record
9287 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9288 	 * from the latest proposal of the tcplw@cray.com list (Braden
9289 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9290 	 * with our earlier PAWS tests, so this check should be solely
9291 	 * predicated on the sequence space of this segment. 3) That we
9292 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9293 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9294 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9295 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9296 	 * p.869. In such cases, we can still calculate the RTT correctly
9297 	 * when RCV.NXT == Last.ACK.Sent.
9298 	 */
9299 	if ((to->to_flags & TOF_TS) != 0 &&
9300 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9301 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9302 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9303 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9304 		tp->ts_recent = to->to_tsval;
9305 	}
9306 	/*
9307 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9308 	 * is on (half-synchronized state), then queue data for later
9309 	 * processing; else drop segment and return.
9310 	 */
9311 	if ((thflags & TH_ACK) == 0) {
9312 		if (tp->t_flags & TF_NEEDSYN) {
9313 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9314 			    tiwin, thflags, nxt_pkt));
9315 		} else if (tp->t_flags & TF_ACKNOW) {
9316 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9317 			bbr->r_wanted_output = 1;
9318 			return (ret_val);
9319 		} else {
9320 			ctf_do_drop(m, NULL);
9321 			return (0);
9322 		}
9323 	}
9324 	/*
9325 	 * Ack processing.
9326 	 */
9327 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9328 		return (ret_val);
9329 	}
9330 	if (sbavail(&so->so_snd)) {
9331 		if (ctf_progress_timeout_check(tp, true)) {
9332 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9333 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9334 			return (1);
9335 		}
9336 	}
9337 	/* State changes only happen in bbr_process_data() */
9338 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9339 	    tiwin, thflags, nxt_pkt));
9340 }
9341 
9342 /*
9343  * Return value of 1, the TCB is unlocked and most
9344  * likely gone, return value of 0, the TCB is still
9345  * locked.
9346  */
9347 static int
9348 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9349     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9350     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9351 {
9352 	struct tcp_bbr *bbr;
9353 	int32_t ret_val;
9354 
9355 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9356 	ctf_calc_rwin(so, tp);
9357 	if ((thflags & TH_RST) ||
9358 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9359 		return (ctf_process_rst(m, th, so, tp));
9360 	/*
9361 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9362 	 * synchronized state.
9363 	 */
9364 	if (thflags & TH_SYN) {
9365 		ctf_challenge_ack(m, th, tp, &ret_val);
9366 		return (ret_val);
9367 	}
9368 	/*
9369 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9370 	 * it's less than ts_recent, drop it.
9371 	 */
9372 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9373 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9374 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9375 			return (ret_val);
9376 	}
9377 	INP_WLOCK_ASSERT(tp->t_inpcb);
9378 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9379 		return (ret_val);
9380 	}
9381 	/*
9382 	 * If last ACK falls within this segment's sequence numbers, record
9383 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9384 	 * from the latest proposal of the tcplw@cray.com list (Braden
9385 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9386 	 * with our earlier PAWS tests, so this check should be solely
9387 	 * predicated on the sequence space of this segment. 3) That we
9388 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9389 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9390 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9391 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9392 	 * p.869. In such cases, we can still calculate the RTT correctly
9393 	 * when RCV.NXT == Last.ACK.Sent.
9394 	 */
9395 	if ((to->to_flags & TOF_TS) != 0 &&
9396 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9397 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9398 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9399 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9400 		tp->ts_recent = to->to_tsval;
9401 	}
9402 	/*
9403 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9404 	 * is on (half-synchronized state), then queue data for later
9405 	 * processing; else drop segment and return.
9406 	 */
9407 	if ((thflags & TH_ACK) == 0) {
9408 		if (tp->t_flags & TF_NEEDSYN) {
9409 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9410 			    tiwin, thflags, nxt_pkt));
9411 		} else if (tp->t_flags & TF_ACKNOW) {
9412 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9413 			bbr->r_wanted_output = 1;
9414 			return (ret_val);
9415 		} else {
9416 			ctf_do_drop(m, NULL);
9417 			return (0);
9418 		}
9419 	}
9420 	/*
9421 	 * Ack processing.
9422 	 */
9423 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9424 		return (ret_val);
9425 	}
9426 	if (sbavail(&so->so_snd)) {
9427 		if (ctf_progress_timeout_check(tp, true)) {
9428 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9429 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9430 			return (1);
9431 		}
9432 	}
9433 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9434 	    tiwin, thflags, nxt_pkt));
9435 }
9436 
9437 static int
9438 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9439     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9440 {
9441 
9442 	if (bbr->rc_allow_data_af_clo == 0) {
9443 close_now:
9444 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9445 		/* tcp_close will kill the inp pre-log the Reset */
9446 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9447 		tp = tcp_close(tp);
9448 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9449 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9450 		return (1);
9451 	}
9452 	if (sbavail(&so->so_snd) == 0)
9453 		goto close_now;
9454 	/* Ok we allow data that is ignored and a followup reset */
9455 	tp->rcv_nxt = th->th_seq + *tlen;
9456 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9457 	bbr->r_wanted_output = 1;
9458 	*tlen = 0;
9459 	return (0);
9460 }
9461 
9462 /*
9463  * Return value of 1, the TCB is unlocked and most
9464  * likely gone, return value of 0, the TCB is still
9465  * locked.
9466  */
9467 static int
9468 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9469     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9470     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9471 {
9472 	int32_t ourfinisacked = 0;
9473 	int32_t ret_val;
9474 	struct tcp_bbr *bbr;
9475 
9476 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9477 	ctf_calc_rwin(so, tp);
9478 	if ((thflags & TH_RST) ||
9479 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9480 		return (ctf_process_rst(m, th, so, tp));
9481 	/*
9482 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9483 	 * synchronized state.
9484 	 */
9485 	if (thflags & TH_SYN) {
9486 		ctf_challenge_ack(m, th, tp, &ret_val);
9487 		return (ret_val);
9488 	}
9489 	/*
9490 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9491 	 * it's less than ts_recent, drop it.
9492 	 */
9493 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9494 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9495 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9496 			return (ret_val);
9497 	}
9498 	INP_WLOCK_ASSERT(tp->t_inpcb);
9499 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9500 		return (ret_val);
9501 	}
9502 	/*
9503 	 * If new data are received on a connection after the user processes
9504 	 * are gone, then RST the other end.
9505 	 */
9506 	if ((so->so_state & SS_NOFDREF) && tlen) {
9507 		/*
9508 		 * We call a new function now so we might continue and setup
9509 		 * to reset at all data being ack'd.
9510 		 */
9511 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9512 			return (1);
9513 	}
9514 	/*
9515 	 * If last ACK falls within this segment's sequence numbers, record
9516 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9517 	 * from the latest proposal of the tcplw@cray.com list (Braden
9518 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9519 	 * with our earlier PAWS tests, so this check should be solely
9520 	 * predicated on the sequence space of this segment. 3) That we
9521 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9522 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9523 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9524 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9525 	 * p.869. In such cases, we can still calculate the RTT correctly
9526 	 * when RCV.NXT == Last.ACK.Sent.
9527 	 */
9528 	if ((to->to_flags & TOF_TS) != 0 &&
9529 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9530 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9531 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9532 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9533 		tp->ts_recent = to->to_tsval;
9534 	}
9535 	/*
9536 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9537 	 * is on (half-synchronized state), then queue data for later
9538 	 * processing; else drop segment and return.
9539 	 */
9540 	if ((thflags & TH_ACK) == 0) {
9541 		if (tp->t_flags & TF_NEEDSYN) {
9542 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9543 			    tiwin, thflags, nxt_pkt));
9544 		} else if (tp->t_flags & TF_ACKNOW) {
9545 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9546 			bbr->r_wanted_output = 1;
9547 			return (ret_val);
9548 		} else {
9549 			ctf_do_drop(m, NULL);
9550 			return (0);
9551 		}
9552 	}
9553 	/*
9554 	 * Ack processing.
9555 	 */
9556 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9557 		return (ret_val);
9558 	}
9559 	if (ourfinisacked) {
9560 		/*
9561 		 * If we can't receive any more data, then closing user can
9562 		 * proceed. Starting the timer is contrary to the
9563 		 * specification, but if we don't get a FIN we'll hang
9564 		 * forever.
9565 		 *
9566 		 * XXXjl: we should release the tp also, and use a
9567 		 * compressed state.
9568 		 */
9569 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9570 			soisdisconnected(so);
9571 			tcp_timer_activate(tp, TT_2MSL,
9572 			    (tcp_fast_finwait2_recycle ?
9573 			    tcp_finwait2_timeout :
9574 			    TP_MAXIDLE(tp)));
9575 		}
9576 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9577 	}
9578 	if (sbavail(&so->so_snd)) {
9579 		if (ctf_progress_timeout_check(tp, true)) {
9580 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9581 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9582 			return (1);
9583 		}
9584 	}
9585 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9586 	    tiwin, thflags, nxt_pkt));
9587 }
9588 
9589 /*
9590  * Return value of 1, the TCB is unlocked and most
9591  * likely gone, return value of 0, the TCB is still
9592  * locked.
9593  */
9594 static int
9595 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9596     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9597     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9598 {
9599 	int32_t ourfinisacked = 0;
9600 	int32_t ret_val;
9601 	struct tcp_bbr *bbr;
9602 
9603 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9604 	ctf_calc_rwin(so, tp);
9605 	if ((thflags & TH_RST) ||
9606 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9607 		return (ctf_process_rst(m, th, so, tp));
9608 	/*
9609 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9610 	 * synchronized state.
9611 	 */
9612 	if (thflags & TH_SYN) {
9613 		ctf_challenge_ack(m, th, tp, &ret_val);
9614 		return (ret_val);
9615 	}
9616 	/*
9617 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9618 	 * it's less than ts_recent, drop it.
9619 	 */
9620 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9621 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9622 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9623 			return (ret_val);
9624 	}
9625 	INP_WLOCK_ASSERT(tp->t_inpcb);
9626 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9627 		return (ret_val);
9628 	}
9629 	/*
9630 	 * If new data are received on a connection after the user processes
9631 	 * are gone, then RST the other end.
9632 	 */
9633 	if ((so->so_state & SS_NOFDREF) && tlen) {
9634 		/*
9635 		 * We call a new function now so we might continue and setup
9636 		 * to reset at all data being ack'd.
9637 		 */
9638 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9639 			return (1);
9640 	}
9641 	/*
9642 	 * If last ACK falls within this segment's sequence numbers, record
9643 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9644 	 * from the latest proposal of the tcplw@cray.com list (Braden
9645 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9646 	 * with our earlier PAWS tests, so this check should be solely
9647 	 * predicated on the sequence space of this segment. 3) That we
9648 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9649 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9650 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9651 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9652 	 * p.869. In such cases, we can still calculate the RTT correctly
9653 	 * when RCV.NXT == Last.ACK.Sent.
9654 	 */
9655 	if ((to->to_flags & TOF_TS) != 0 &&
9656 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9657 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9658 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9659 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9660 		tp->ts_recent = to->to_tsval;
9661 	}
9662 	/*
9663 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9664 	 * is on (half-synchronized state), then queue data for later
9665 	 * processing; else drop segment and return.
9666 	 */
9667 	if ((thflags & TH_ACK) == 0) {
9668 		if (tp->t_flags & TF_NEEDSYN) {
9669 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9670 			    tiwin, thflags, nxt_pkt));
9671 		} else if (tp->t_flags & TF_ACKNOW) {
9672 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9673 			bbr->r_wanted_output = 1;
9674 			return (ret_val);
9675 		} else {
9676 			ctf_do_drop(m, NULL);
9677 			return (0);
9678 		}
9679 	}
9680 	/*
9681 	 * Ack processing.
9682 	 */
9683 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9684 		return (ret_val);
9685 	}
9686 	if (ourfinisacked) {
9687 		tcp_twstart(tp);
9688 		m_freem(m);
9689 		return (1);
9690 	}
9691 	if (sbavail(&so->so_snd)) {
9692 		if (ctf_progress_timeout_check(tp, true)) {
9693 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9694 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9695 			return (1);
9696 		}
9697 	}
9698 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9699 	    tiwin, thflags, nxt_pkt));
9700 }
9701 
9702 /*
9703  * Return value of 1, the TCB is unlocked and most
9704  * likely gone, return value of 0, the TCB is still
9705  * locked.
9706  */
9707 static int
9708 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9709     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9710     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9711 {
9712 	int32_t ourfinisacked = 0;
9713 	int32_t ret_val;
9714 	struct tcp_bbr *bbr;
9715 
9716 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9717 	ctf_calc_rwin(so, tp);
9718 	if ((thflags & TH_RST) ||
9719 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9720 		return (ctf_process_rst(m, th, so, tp));
9721 	/*
9722 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9723 	 * synchronized state.
9724 	 */
9725 	if (thflags & TH_SYN) {
9726 		ctf_challenge_ack(m, th, tp, &ret_val);
9727 		return (ret_val);
9728 	}
9729 	/*
9730 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9731 	 * it's less than ts_recent, drop it.
9732 	 */
9733 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9734 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9735 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9736 			return (ret_val);
9737 	}
9738 	INP_WLOCK_ASSERT(tp->t_inpcb);
9739 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9740 		return (ret_val);
9741 	}
9742 	/*
9743 	 * If new data are received on a connection after the user processes
9744 	 * are gone, then RST the other end.
9745 	 */
9746 	if ((so->so_state & SS_NOFDREF) && tlen) {
9747 		/*
9748 		 * We call a new function now so we might continue and setup
9749 		 * to reset at all data being ack'd.
9750 		 */
9751 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9752 			return (1);
9753 	}
9754 	/*
9755 	 * If last ACK falls within this segment's sequence numbers, record
9756 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9757 	 * from the latest proposal of the tcplw@cray.com list (Braden
9758 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9759 	 * with our earlier PAWS tests, so this check should be solely
9760 	 * predicated on the sequence space of this segment. 3) That we
9761 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9762 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9763 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9764 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9765 	 * p.869. In such cases, we can still calculate the RTT correctly
9766 	 * when RCV.NXT == Last.ACK.Sent.
9767 	 */
9768 	if ((to->to_flags & TOF_TS) != 0 &&
9769 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9770 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9771 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9772 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9773 		tp->ts_recent = to->to_tsval;
9774 	}
9775 	/*
9776 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9777 	 * is on (half-synchronized state), then queue data for later
9778 	 * processing; else drop segment and return.
9779 	 */
9780 	if ((thflags & TH_ACK) == 0) {
9781 		if (tp->t_flags & TF_NEEDSYN) {
9782 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9783 			    tiwin, thflags, nxt_pkt));
9784 		} else if (tp->t_flags & TF_ACKNOW) {
9785 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9786 			bbr->r_wanted_output = 1;
9787 			return (ret_val);
9788 		} else {
9789 			ctf_do_drop(m, NULL);
9790 			return (0);
9791 		}
9792 	}
9793 	/*
9794 	 * case TCPS_LAST_ACK: Ack processing.
9795 	 */
9796 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9797 		return (ret_val);
9798 	}
9799 	if (ourfinisacked) {
9800 		tp = tcp_close(tp);
9801 		ctf_do_drop(m, tp);
9802 		return (1);
9803 	}
9804 	if (sbavail(&so->so_snd)) {
9805 		if (ctf_progress_timeout_check(tp, true)) {
9806 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9807 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9808 			return (1);
9809 		}
9810 	}
9811 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9812 	    tiwin, thflags, nxt_pkt));
9813 }
9814 
9815 /*
9816  * Return value of 1, the TCB is unlocked and most
9817  * likely gone, return value of 0, the TCB is still
9818  * locked.
9819  */
9820 static int
9821 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9822     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9823     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9824 {
9825 	int32_t ourfinisacked = 0;
9826 	int32_t ret_val;
9827 	struct tcp_bbr *bbr;
9828 
9829 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9830 	ctf_calc_rwin(so, tp);
9831 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9832 	if ((thflags & TH_RST) ||
9833 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9834 		return (ctf_process_rst(m, th, so, tp));
9835 
9836 	/*
9837 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9838 	 * synchronized state.
9839 	 */
9840 	if (thflags & TH_SYN) {
9841 		ctf_challenge_ack(m, th, tp, &ret_val);
9842 		return (ret_val);
9843 	}
9844 	INP_WLOCK_ASSERT(tp->t_inpcb);
9845 	/*
9846 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9847 	 * it's less than ts_recent, drop it.
9848 	 */
9849 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9850 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9851 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9852 			return (ret_val);
9853 	}
9854 	INP_WLOCK_ASSERT(tp->t_inpcb);
9855 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9856 		return (ret_val);
9857 	}
9858 	/*
9859 	 * If new data are received on a connection after the user processes
9860 	 * are gone, then we may RST the other end depending on the outcome
9861 	 * of bbr_check_data_after_close.
9862 	 */
9863 	if ((so->so_state & SS_NOFDREF) &&
9864 	    tlen) {
9865 		/*
9866 		 * We call a new function now so we might continue and setup
9867 		 * to reset at all data being ack'd.
9868 		 */
9869 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9870 			return (1);
9871 	}
9872 	INP_WLOCK_ASSERT(tp->t_inpcb);
9873 	/*
9874 	 * If last ACK falls within this segment's sequence numbers, record
9875 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9876 	 * from the latest proposal of the tcplw@cray.com list (Braden
9877 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9878 	 * with our earlier PAWS tests, so this check should be solely
9879 	 * predicated on the sequence space of this segment. 3) That we
9880 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9881 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9882 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9883 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9884 	 * p.869. In such cases, we can still calculate the RTT correctly
9885 	 * when RCV.NXT == Last.ACK.Sent.
9886 	 */
9887 	INP_WLOCK_ASSERT(tp->t_inpcb);
9888 	if ((to->to_flags & TOF_TS) != 0 &&
9889 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9890 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9891 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9892 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9893 		tp->ts_recent = to->to_tsval;
9894 	}
9895 	/*
9896 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9897 	 * is on (half-synchronized state), then queue data for later
9898 	 * processing; else drop segment and return.
9899 	 */
9900 	if ((thflags & TH_ACK) == 0) {
9901 		if (tp->t_flags & TF_NEEDSYN) {
9902 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9903 			    tiwin, thflags, nxt_pkt));
9904 		} else if (tp->t_flags & TF_ACKNOW) {
9905 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9906 			bbr->r_wanted_output = 1;
9907 			return (ret_val);
9908 		} else {
9909 			ctf_do_drop(m, NULL);
9910 			return (0);
9911 		}
9912 	}
9913 	/*
9914 	 * Ack processing.
9915 	 */
9916 	INP_WLOCK_ASSERT(tp->t_inpcb);
9917 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9918 		return (ret_val);
9919 	}
9920 	if (sbavail(&so->so_snd)) {
9921 		if (ctf_progress_timeout_check(tp, true)) {
9922 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9923 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9924 			return (1);
9925 		}
9926 	}
9927 	INP_WLOCK_ASSERT(tp->t_inpcb);
9928 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9929 	    tiwin, thflags, nxt_pkt));
9930 }
9931 
9932 static void
9933 bbr_stop_all_timers(struct tcpcb *tp)
9934 {
9935 	struct tcp_bbr *bbr;
9936 
9937 	/*
9938 	 * Assure no timers are running.
9939 	 */
9940 	if (tcp_timer_active(tp, TT_PERSIST)) {
9941 		/* We enter in persists, set the flag appropriately */
9942 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9943 		bbr->rc_in_persist = 1;
9944 	}
9945 	tcp_timer_suspend(tp, TT_PERSIST);
9946 	tcp_timer_suspend(tp, TT_REXMT);
9947 	tcp_timer_suspend(tp, TT_KEEP);
9948 	tcp_timer_suspend(tp, TT_DELACK);
9949 }
9950 
9951 static void
9952 bbr_google_mode_on(struct tcp_bbr *bbr)
9953 {
9954 	bbr->rc_use_google = 1;
9955 	bbr->rc_no_pacing = 0;
9956 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9957 	bbr->r_use_policer = bbr_policer_detection_enabled;
9958 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9959 	bbr->bbr_use_rack_cheat = 0;
9960 	bbr->r_ctl.rc_incr_tmrs = 0;
9961 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9962 	bbr->r_ctl.rc_inc_ip_oh = 0;
9963 	bbr->r_ctl.rc_inc_enet_oh = 0;
9964 	reset_time(&bbr->r_ctl.rc_delrate,
9965 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9966 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9967 			 (11 * USECS_IN_SECOND));
9968 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9969 }
9970 
9971 static void
9972 bbr_google_mode_off(struct tcp_bbr *bbr)
9973 {
9974 	bbr->rc_use_google = 0;
9975 	bbr->r_ctl.bbr_google_discount = 0;
9976 	bbr->no_pacing_until = bbr_no_pacing_until;
9977 	bbr->r_use_policer = 0;
9978 	if (bbr->no_pacing_until)
9979 		bbr->rc_no_pacing = 1;
9980 	else
9981 		bbr->rc_no_pacing = 0;
9982 	if (bbr_use_rack_resend_cheat)
9983 		bbr->bbr_use_rack_cheat = 1;
9984 	else
9985 		bbr->bbr_use_rack_cheat = 0;
9986 	if (bbr_incr_timers)
9987 		bbr->r_ctl.rc_incr_tmrs = 1;
9988 	else
9989 		bbr->r_ctl.rc_incr_tmrs = 0;
9990 	if (bbr_include_tcp_oh)
9991 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9992 	else
9993 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9994 	if (bbr_include_ip_oh)
9995 		bbr->r_ctl.rc_inc_ip_oh = 1;
9996 	else
9997 		bbr->r_ctl.rc_inc_ip_oh = 0;
9998 	if (bbr_include_enet_oh)
9999 		bbr->r_ctl.rc_inc_enet_oh = 1;
10000 	else
10001 		bbr->r_ctl.rc_inc_enet_oh = 0;
10002 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10003 	reset_time(&bbr->r_ctl.rc_delrate,
10004 		   bbr_num_pktepo_for_del_limit);
10005 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10006 			 (bbr_filter_len_sec * USECS_IN_SECOND));
10007 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10008 }
10009 /*
10010  * Return 0 on success, non-zero on failure
10011  * which indicates the error (usually no memory).
10012  */
10013 static int
10014 bbr_init(struct tcpcb *tp)
10015 {
10016 	struct tcp_bbr *bbr = NULL;
10017 	struct inpcb *inp;
10018 	uint32_t cts;
10019 
10020 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10021 	if (tp->t_fb_ptr == NULL) {
10022 		/*
10023 		 * We need to allocate memory but cant. The INP and INP_INFO
10024 		 * locks and they are recusive (happens during setup. So a
10025 		 * scheme to drop the locks fails :(
10026 		 *
10027 		 */
10028 		return (ENOMEM);
10029 	}
10030 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10031 	bbr->rtt_valid = 0;
10032 	inp = tp->t_inpcb;
10033 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10034 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10035 	TAILQ_INIT(&bbr->r_ctl.rc_map);
10036 	TAILQ_INIT(&bbr->r_ctl.rc_free);
10037 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10038 	bbr->rc_tp = tp;
10039 	if (tp->t_inpcb) {
10040 		bbr->rc_inp = tp->t_inpcb;
10041 	}
10042 	cts = tcp_get_usecs(&bbr->rc_tv);
10043 	tp->t_acktime = 0;
10044 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10045 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10046 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
10047 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10048 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10049 	bbr->r_ctl.rc_min_to = bbr_min_to;
10050 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
10051 	bbr->r_ctl.bbr_lost_at_state = 0;
10052 	bbr->r_ctl.rc_lost_at_startup = 0;
10053 	bbr->rc_all_timers_stopped = 0;
10054 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10055 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10056 	bbr->r_ctl.rc_pkt_epoch = 0;
10057 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10058 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10059 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10060 	bbr->r_ctl.rc_went_idle_time = cts;
10061 	bbr->rc_pacer_started = cts;
10062 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10063 	bbr->r_ctl.rc_rcvtime = cts;
10064 	bbr->r_ctl.rc_bbr_state_time = cts;
10065 	bbr->r_ctl.rc_del_time = cts;
10066 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10067 	bbr->r_ctl.last_in_probertt = cts;
10068 	bbr->skip_gain = 0;
10069 	bbr->gain_is_limited = 0;
10070 	bbr->no_pacing_until = bbr_no_pacing_until;
10071 	if (bbr->no_pacing_until)
10072 		bbr->rc_no_pacing = 1;
10073 	if (bbr_use_google_algo) {
10074 		bbr->rc_no_pacing = 0;
10075 		bbr->rc_use_google = 1;
10076 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10077 		bbr->r_use_policer = bbr_policer_detection_enabled;
10078 	} else {
10079 		bbr->rc_use_google = 0;
10080 		bbr->r_ctl.bbr_google_discount = 0;
10081 		bbr->r_use_policer = 0;
10082 	}
10083 	if (bbr_ts_limiting)
10084 		bbr->rc_use_ts_limit = 1;
10085 	else
10086 		bbr->rc_use_ts_limit = 0;
10087 	if (bbr_ts_can_raise)
10088 		bbr->ts_can_raise = 1;
10089 	else
10090 		bbr->ts_can_raise = 0;
10091 	if (V_tcp_delack_enabled == 1)
10092 		tp->t_delayed_ack = 2;
10093 	else if (V_tcp_delack_enabled == 0)
10094 		tp->t_delayed_ack = 0;
10095 	else if (V_tcp_delack_enabled < 100)
10096 		tp->t_delayed_ack = V_tcp_delack_enabled;
10097 	else
10098 		tp->t_delayed_ack = 2;
10099 	if (bbr->rc_use_google == 0)
10100 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10101 	else
10102 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10103 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10104 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10105 	bbr->rc_init_win = bbr_def_init_win;
10106 	if (tp->t_flags & TF_REQ_TSTMP)
10107 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10108 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10109 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10110 	bbr->r_init_rtt = 1;
10111 
10112 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10113 	if (bbr_allow_hdwr_pacing)
10114 		bbr->bbr_hdw_pace_ena = 1;
10115 	else
10116 		bbr->bbr_hdw_pace_ena = 0;
10117 	if (bbr_sends_full_iwnd)
10118 		bbr->bbr_init_win_cheat = 1;
10119 	else
10120 		bbr->bbr_init_win_cheat = 0;
10121 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10122 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10123 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10124 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10125 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10126 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10127 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10128 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10129 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10130 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10131 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10132 	bbr->r_ctl.rc_rtt_shrinks = cts;
10133 	if (bbr->rc_use_google) {
10134 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10135 				  FILTER_TYPE_MAX,
10136 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10137 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10138 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10139 	} else {
10140 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10141 				  FILTER_TYPE_MAX,
10142 				  bbr_num_pktepo_for_del_limit);
10143 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10144 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10145 	}
10146 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10147 	if (bbr_uses_idle_restart)
10148 		bbr->rc_use_idle_restart = 1;
10149 	else
10150 		bbr->rc_use_idle_restart = 0;
10151 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10152 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10153 	if (bbr_resends_use_tso)
10154 		bbr->rc_resends_use_tso = 1;
10155 #ifdef NETFLIX_PEAKRATE
10156 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10157 #endif
10158 	if (tp->snd_una != tp->snd_max) {
10159 		/* Create a send map for the current outstanding data */
10160 		struct bbr_sendmap *rsm;
10161 
10162 		rsm = bbr_alloc(bbr);
10163 		if (rsm == NULL) {
10164 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10165 			tp->t_fb_ptr = NULL;
10166 			return (ENOMEM);
10167 		}
10168 		rsm->r_rtt_not_allowed = 1;
10169 		rsm->r_tim_lastsent[0] = cts;
10170 		rsm->r_rtr_cnt = 1;
10171 		rsm->r_rtr_bytes = 0;
10172 		rsm->r_start = tp->snd_una;
10173 		rsm->r_end = tp->snd_max;
10174 		rsm->r_dupack = 0;
10175 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10176 		rsm->r_ts_valid = 0;
10177 		rsm->r_del_ack_ts = tp->ts_recent;
10178 		rsm->r_del_time = cts;
10179 		if (bbr->r_ctl.r_app_limited_until)
10180 			rsm->r_app_limited = 1;
10181 		else
10182 			rsm->r_app_limited = 0;
10183 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10184 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10185 		rsm->r_in_tmap = 1;
10186 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10187 			rsm->r_bbr_state = bbr_state_val(bbr);
10188 		else
10189 			rsm->r_bbr_state = 8;
10190 	}
10191 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10192 		bbr->bbr_use_rack_cheat = 1;
10193 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10194 		bbr->r_ctl.rc_incr_tmrs = 1;
10195 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10196 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10197 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10198 		bbr->r_ctl.rc_inc_ip_oh = 1;
10199 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10200 		bbr->r_ctl.rc_inc_enet_oh = 1;
10201 
10202 	bbr_log_type_statechange(bbr, cts, __LINE__);
10203 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10204 	    (tp->t_srtt)) {
10205 		uint32_t rtt;
10206 
10207 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10208 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10209 	}
10210 	/* announce the settings and state */
10211 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10212 	tcp_bbr_tso_size_check(bbr, cts);
10213 	/*
10214 	 * Now call the generic function to start a timer. This will place
10215 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10216 	 * flags.
10217 	 */
10218 	bbr_stop_all_timers(tp);
10219 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10220 	return (0);
10221 }
10222 
10223 /*
10224  * Return 0 if we can accept the connection. Return
10225  * non-zero if we can't handle the connection. A EAGAIN
10226  * means you need to wait until the connection is up.
10227  * a EADDRNOTAVAIL means we can never handle the connection
10228  * (no SACK).
10229  */
10230 static int
10231 bbr_handoff_ok(struct tcpcb *tp)
10232 {
10233 	if ((tp->t_state == TCPS_CLOSED) ||
10234 	    (tp->t_state == TCPS_LISTEN)) {
10235 		/* Sure no problem though it may not stick */
10236 		return (0);
10237 	}
10238 	if ((tp->t_state == TCPS_SYN_SENT) ||
10239 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10240 		/*
10241 		 * We really don't know you have to get to ESTAB or beyond
10242 		 * to tell.
10243 		 */
10244 		return (EAGAIN);
10245 	}
10246 	if (tp->t_flags & TF_SENTFIN)
10247 		return (EINVAL);
10248 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10249 		return (0);
10250 	}
10251 	/*
10252 	 * If we reach here we don't do SACK on this connection so we can
10253 	 * never do rack.
10254 	 */
10255 	return (EINVAL);
10256 }
10257 
10258 static void
10259 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10260 {
10261 	if (tp->t_fb_ptr) {
10262 		uint32_t calc;
10263 		struct tcp_bbr *bbr;
10264 		struct bbr_sendmap *rsm;
10265 
10266 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10267 		if (bbr->r_ctl.crte)
10268 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10269 		bbr_log_flowend(bbr);
10270 		bbr->rc_tp = NULL;
10271 		if (tp->t_inpcb) {
10272 			/* Backout any flags2 we applied */
10273 			tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10274 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10275 			tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10276 		}
10277 		if (bbr->bbr_hdrw_pacing)
10278 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10279 		else
10280 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10281 		if (bbr->r_ctl.crte != NULL) {
10282 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10283 			bbr->r_ctl.crte = NULL;
10284 		}
10285 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10286 		while (rsm) {
10287 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10288 			uma_zfree(bbr_zone, rsm);
10289 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10290 		}
10291 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10292 		while (rsm) {
10293 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10294 			uma_zfree(bbr_zone, rsm);
10295 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10296 		}
10297 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10298 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10299 			BBR_STAT_INC(bbr_dynamic_rwnd);
10300 		else
10301 			BBR_STAT_INC(bbr_static_rwnd);
10302 		bbr->r_ctl.rc_free_cnt = 0;
10303 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10304 		tp->t_fb_ptr = NULL;
10305 	}
10306 	/* Make sure snd_nxt is correctly set */
10307 	tp->snd_nxt = tp->snd_max;
10308 }
10309 
10310 static void
10311 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10312 {
10313 	switch (tp->t_state) {
10314 	case TCPS_SYN_SENT:
10315 		bbr->r_state = TCPS_SYN_SENT;
10316 		bbr->r_substate = bbr_do_syn_sent;
10317 		break;
10318 	case TCPS_SYN_RECEIVED:
10319 		bbr->r_state = TCPS_SYN_RECEIVED;
10320 		bbr->r_substate = bbr_do_syn_recv;
10321 		break;
10322 	case TCPS_ESTABLISHED:
10323 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10324 		bbr->r_state = TCPS_ESTABLISHED;
10325 		bbr->r_substate = bbr_do_established;
10326 		break;
10327 	case TCPS_CLOSE_WAIT:
10328 		bbr->r_state = TCPS_CLOSE_WAIT;
10329 		bbr->r_substate = bbr_do_close_wait;
10330 		break;
10331 	case TCPS_FIN_WAIT_1:
10332 		bbr->r_state = TCPS_FIN_WAIT_1;
10333 		bbr->r_substate = bbr_do_fin_wait_1;
10334 		break;
10335 	case TCPS_CLOSING:
10336 		bbr->r_state = TCPS_CLOSING;
10337 		bbr->r_substate = bbr_do_closing;
10338 		break;
10339 	case TCPS_LAST_ACK:
10340 		bbr->r_state = TCPS_LAST_ACK;
10341 		bbr->r_substate = bbr_do_lastack;
10342 		break;
10343 	case TCPS_FIN_WAIT_2:
10344 		bbr->r_state = TCPS_FIN_WAIT_2;
10345 		bbr->r_substate = bbr_do_fin_wait_2;
10346 		break;
10347 	case TCPS_LISTEN:
10348 	case TCPS_CLOSED:
10349 	case TCPS_TIME_WAIT:
10350 	default:
10351 		break;
10352 	};
10353 }
10354 
10355 static void
10356 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10357 {
10358 	/*
10359 	 * Now what state are we going into now? Is there adjustments
10360 	 * needed?
10361 	 */
10362 	int32_t old_state, old_gain;
10363 
10364 	old_state = bbr_state_val(bbr);
10365 	old_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
10366 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10367 		/* Save the lowest srtt we saw in our end of the sub-state */
10368 		bbr->rc_hit_state_1 = 0;
10369 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10370 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10371 	}
10372 	bbr->rc_bbr_substate++;
10373 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10374 		/* Cycle back to first state-> gain */
10375 		bbr->rc_bbr_substate = 0;
10376 	}
10377 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10378 		/*
10379 		 * We enter the gain(5/4) cycle (possibly less if
10380 		 * shallow buffer detection is enabled)
10381 		 */
10382 		if (bbr->skip_gain) {
10383 			/*
10384 			 * Hardware pacing has set our rate to
10385 			 * the max and limited our b/w just
10386 			 * do level i.e. no gain.
10387 			 */
10388 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10389 		} else if (bbr->gain_is_limited &&
10390 			   bbr->bbr_hdrw_pacing &&
10391 			   bbr->r_ctl.crte) {
10392 			/*
10393 			 * We can't gain above the hardware pacing
10394 			 * rate which is less than our rate + the gain
10395 			 * calculate the gain needed to reach the hardware
10396 			 * pacing rate..
10397 			 */
10398 			uint64_t bw, rate, gain_calc;
10399 
10400 			bw = bbr_get_bw(bbr);
10401 			rate = bbr->r_ctl.crte->rate;
10402 			if ((rate > bw) &&
10403 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10404 				gain_calc = (rate * BBR_UNIT) / bw;
10405 				if (gain_calc < BBR_UNIT)
10406 					gain_calc = BBR_UNIT;
10407 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10408 			} else {
10409 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10410 			}
10411 		} else
10412 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10413 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10414 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10415 		} else
10416 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10417 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10418 		bbr->rc_hit_state_1 = 1;
10419 		bbr->r_ctl.rc_exta_time_gd = 0;
10420 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10421 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10422 		if (bbr_state_drain_2_tar) {
10423 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10424 		} else
10425 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10426 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10427 	} else {
10428 		/* All other cycles hit here 2-7 */
10429 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10430 			if (bbr_sub_drain_slam_cwnd &&
10431 			    (bbr->rc_use_google == 0) &&
10432 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10433 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10434 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10435 			}
10436 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10437 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10438 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10439 			else
10440 				bbr->r_ctl.rc_exta_time_gd = 0;
10441 			if (bbr->r_ctl.rc_exta_time_gd) {
10442 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10443 				/* Now chop up the time for each state (div by 7) */
10444 				bbr->r_ctl.rc_level_state_extra /= 7;
10445 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10446 					/* Add a randomization */
10447 					bbr_randomize_extra_state_time(bbr);
10448 				}
10449 			}
10450 		}
10451 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10452 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10453 	}
10454 	if (bbr->rc_use_google) {
10455 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10456 	}
10457 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10458 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10459 	if (dolog)
10460 		bbr_log_type_statechange(bbr, cts, line);
10461 
10462 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10463 		uint32_t time_in;
10464 
10465 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10466 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10467 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10468 		} else {
10469 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10470 		}
10471 	}
10472 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10473 	bbr_set_state_target(bbr, __LINE__);
10474 	if (bbr_sub_drain_slam_cwnd &&
10475 	    (bbr->rc_use_google == 0) &&
10476 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10477 		/* Slam down the cwnd */
10478 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10479 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10480 		if (bbr_sub_drain_app_limit) {
10481 			/* Go app limited if we are on a long drain */
10482 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10483 							  ctf_flight_size(bbr->rc_tp,
10484 							      (bbr->r_ctl.rc_sacked +
10485 							       bbr->r_ctl.rc_lost_bytes)));
10486 		}
10487 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10488 	}
10489 	if (bbr->rc_lt_use_bw) {
10490 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10491 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10492 	}
10493 	/* Google changes TSO size every cycle */
10494 	if (bbr->rc_use_google)
10495 		tcp_bbr_tso_size_check(bbr, cts);
10496 	bbr->r_ctl.gain_epoch = cts;
10497 	bbr->r_ctl.rc_bbr_state_time = cts;
10498 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10499 }
10500 
10501 static void
10502 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10503 {
10504 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10505 	    (google_allow_early_out == 1) &&
10506 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10507 		/* We have reached out target flight size possibly early */
10508 		goto change_state;
10509 	}
10510 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10511 		return;
10512 	}
10513 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10514 		/*
10515 		 * Must be a rttProp movement forward before
10516 		 * we can change states.
10517 		 */
10518 		return;
10519 	}
10520 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10521 		/*
10522 		 * The needed time has passed but for
10523 		 * the gain cycle extra rules apply:
10524 		 * 1) If we have seen loss, we exit
10525 		 * 2) If we have not reached the target
10526 		 *    we stay in GAIN (gain-to-target).
10527 		 */
10528 		if (google_consider_lost && losses)
10529 			goto change_state;
10530 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10531 			return;
10532 		}
10533 	}
10534 change_state:
10535 	/* For gain we must reach our target, all others last 1 rttProp */
10536 	bbr_substate_change(bbr, cts, __LINE__, 1);
10537 }
10538 
10539 static void
10540 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10541 {
10542 	uint32_t flight, bbr_cur_cycle_time;
10543 
10544 	if (bbr->rc_use_google) {
10545 		bbr_set_probebw_google_gains(bbr, cts, losses);
10546 		return;
10547 	}
10548 	if (cts == 0) {
10549 		/*
10550 		 * Never alow cts to be 0 we
10551 		 * do this so we can judge if
10552 		 * we have set a timestamp.
10553 		 */
10554 		cts = 1;
10555 	}
10556 	if (bbr_state_is_pkt_epoch)
10557 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10558 	else
10559 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10560 
10561 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10562 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10563 			flight = ctf_flight_size(bbr->rc_tp,
10564 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10565 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10566 				/* Keep it slam down */
10567 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10568 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10569 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10570 				}
10571 				if (bbr_sub_drain_app_limit) {
10572 					/* Go app limited if we are on a long drain */
10573 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10574 				}
10575 			}
10576 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10577 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10578 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10579 				/*
10580 				 * Still here after the same time as
10581 				 * the gain. We need to drain harder
10582 				 * for the next srtt. Reduce by a set amount
10583 				 * the gain drop is capped at DRAIN states
10584 				 * value (88).
10585 				 */
10586 				bbr->r_ctl.flightsize_at_drain = flight;
10587 				if (bbr_drain_drop_mul &&
10588 				    bbr_drain_drop_div &&
10589 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10590 					/* Use your specific drop value (def 4/5 = 20%) */
10591 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10592 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10593 				} else {
10594 					/* You get drop of 20% */
10595 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10596 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10597 				}
10598 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10599 					/* Reduce our gain again to the bottom  */
10600 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10601 				}
10602 				bbr_log_exit_gain(bbr, cts, 4);
10603 				/*
10604 				 * Extend out so we wait another
10605 				 * epoch before dropping again.
10606 				 */
10607 				bbr->r_ctl.gain_epoch = cts;
10608 			}
10609 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10610 				if (bbr_sub_drain_slam_cwnd &&
10611 				    (bbr->rc_use_google == 0) &&
10612 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10613 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10614 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10615 				}
10616 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10617 				bbr_log_exit_gain(bbr, cts, 3);
10618 			}
10619 		} else {
10620 			/* Its a gain  */
10621 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10622 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10623 				goto change_state;
10624 			}
10625 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10626 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10627 			     bbr->rc_tp->snd_wnd)) {
10628 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10629 				bbr_log_exit_gain(bbr, cts, 2);
10630 			}
10631 		}
10632 		/**
10633 		 * We fall through and return always one of two things has
10634 		 * occurred.
10635 		 * 1) We are still not at target
10636 		 *    <or>
10637 		 * 2) We reached the target and set rc_bbr_state_atflight
10638 		 *    which means we no longer hit this block
10639 		 *    next time we are called.
10640 		 */
10641 		return;
10642 	}
10643 change_state:
10644 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10645 		return;
10646 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10647 		/* Less than a full time-period has passed */
10648 		return;
10649 	}
10650 	if (bbr->r_ctl.rc_level_state_extra &&
10651 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10652 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10653 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10654 		/* Less than a full time-period + extra has passed */
10655 		return;
10656 	}
10657 	if (bbr_gain_gets_extra_too &&
10658 	    bbr->r_ctl.rc_level_state_extra &&
10659 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10660 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10661 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10662 		/* Less than a full time-period + extra has passed */
10663 		return;
10664 	}
10665 	bbr_substate_change(bbr, cts, __LINE__, 1);
10666 }
10667 
10668 static uint32_t
10669 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10670 {
10671 	uint32_t mss, tar;
10672 
10673 	if (bbr->rc_use_google) {
10674 		/* Google just uses the cwnd target */
10675 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10676 	} else {
10677 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10678 			  bbr->r_ctl.rc_pace_max_segs);
10679 		/* Get the base cwnd with gain rounded to a mss */
10680 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10681 						      gain), mss);
10682 		/* Make sure it is within our min */
10683 		if (tar < get_min_cwnd(bbr))
10684 			return (get_min_cwnd(bbr));
10685 	}
10686 	return (tar);
10687 }
10688 
10689 static void
10690 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10691 {
10692 	uint32_t tar, meth;
10693 
10694 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10695 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10696 		/* Special case using old probe-rtt method */
10697 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10698 		meth = 1;
10699 	} else {
10700 		/* Non-probe-rtt case and reduced probe-rtt  */
10701 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10702 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10703 			/* For gain cycle we use the hptsi gain */
10704 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10705 			meth = 2;
10706 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10707 			/*
10708 			 * If configured, or for google all other states
10709 			 * get BBR_UNIT.
10710 			 */
10711 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10712 			meth = 3;
10713 		} else {
10714 			/*
10715 			 * Or we set a target based on the pacing gain
10716 			 * for non-google mode and default (non-configured).
10717 			 * Note we don't set a target goal below drain (192).
10718 			 */
10719 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10720 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10721 				meth = 4;
10722 			} else {
10723 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10724 				meth = 5;
10725 			}
10726 		}
10727 	}
10728 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10729 	bbr->r_ctl.rc_target_at_state = tar;
10730 }
10731 
10732 static void
10733 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10734 {
10735 	/* Change to probe_rtt */
10736 	uint32_t time_in;
10737 
10738 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10739 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10740 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10741 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10742 					  + bbr->r_ctl.rc_delivered);
10743 	/* Setup so we force feed the filter */
10744 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10745 		bbr->rc_prtt_set_ts = 1;
10746 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10747 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10748 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10749 	}
10750 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10751 	bbr->r_ctl.rc_rtt_shrinks = cts;
10752 	bbr->r_ctl.last_in_probertt = cts;
10753 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10754 	bbr->r_ctl.rc_bbr_state_time = cts;
10755 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10756 	/* We need to force the filter to update */
10757 
10758 	if ((bbr_sub_drain_slam_cwnd) &&
10759 	    bbr->rc_hit_state_1 &&
10760 	    (bbr->rc_use_google == 0) &&
10761 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10762 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10763 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10764 	} else
10765 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10766 	/* Update the lost */
10767 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10768 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10769 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10770 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10771 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10772 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10773 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10774 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10775 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10776 	} else {
10777 		/*
10778 		 * We bring it down slowly by using a hptsi gain that is
10779 		 * probably 75%. This will slowly float down our outstanding
10780 		 * without tampering with the cwnd.
10781 		 */
10782 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10783 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10784 		bbr_set_state_target(bbr, __LINE__);
10785 		if (bbr_prtt_slam_cwnd &&
10786 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10787 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10788 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10789 		}
10790 	}
10791 	if (ctf_flight_size(bbr->rc_tp,
10792 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10793 	    bbr->r_ctl.rc_target_at_state) {
10794 		/* We are at target */
10795 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10796 	} else {
10797 		/* We need to come down to reach target before our time begins */
10798 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10799 	}
10800 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10801 	BBR_STAT_INC(bbr_enter_probertt);
10802 	bbr_log_exit_gain(bbr, cts, 0);
10803 	bbr_log_type_statechange(bbr, cts, line);
10804 }
10805 
10806 static void
10807 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10808 {
10809 	/*
10810 	 * Sanity check on probe-rtt intervals.
10811 	 * In crazy situations where we are competing
10812 	 * against new-reno flows with huge buffers
10813 	 * our rtt-prop interval could come to dominate
10814 	 * things if we can't get through a full set
10815 	 * of cycles, we need to adjust it.
10816 	 */
10817 	if (bbr_can_adjust_probertt &&
10818 	    (bbr->rc_use_google == 0)) {
10819 		uint16_t val = 0;
10820 		uint32_t cur_rttp, fval, newval, baseval;
10821 
10822 		/* Are we to small and go into probe-rtt to often? */
10823 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10824 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10825 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10826 		if (bbr_is_ratio == 0) {
10827 			if (fval > bbr_rtt_probe_limit)
10828 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10829 			else
10830 				newval = cur_rttp;
10831 		} else {
10832 			int mul;
10833 
10834 			mul = fval / bbr_rtt_probe_limit;
10835 			newval = cur_rttp * mul;
10836 		}
10837 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10838 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10839 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10840 			val = 1;
10841 		} else {
10842 			/*
10843 			 * No adjustments were made
10844 			 * do we need to shrink it?
10845 			 */
10846 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10847 				if (cur_rttp <= bbr_rtt_probe_limit) {
10848 					/*
10849 					 * Things have calmed down lets
10850 					 * shrink all the way to default
10851 					 */
10852 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10853 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10854 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10855 					cur_rttp = bbr_rtt_probe_limit;
10856 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10857 					val = 2;
10858 				} else {
10859 					/*
10860 					 * Well does some adjustment make sense?
10861 					 */
10862 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10863 						/* We can reduce interval time some */
10864 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10865 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10866 						val = 3;
10867 					}
10868 				}
10869 			}
10870 		}
10871 		if (val)
10872 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10873 	}
10874 }
10875 
10876 static void
10877 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10878 {
10879 	/* Exit probe-rtt */
10880 
10881 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10882 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10883 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10884 	}
10885 	bbr_log_exit_gain(bbr, cts, 1);
10886 	bbr->rc_hit_state_1 = 0;
10887 	bbr->r_ctl.rc_rtt_shrinks = cts;
10888 	bbr->r_ctl.last_in_probertt = cts;
10889 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10890 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10891 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10892 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10893 					  bbr->r_ctl.rc_delivered);
10894 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10895 		uint32_t time_in;
10896 
10897 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10898 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10899 	}
10900 	if (bbr->rc_filled_pipe) {
10901 		/* Switch to probe_bw */
10902 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10903 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10904 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10905 		bbr_substate_change(bbr, cts, __LINE__, 0);
10906 		bbr_log_type_statechange(bbr, cts, __LINE__);
10907 	} else {
10908 		/* Back to startup */
10909 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10910 		bbr->r_ctl.rc_bbr_state_time = cts;
10911 		/*
10912 		 * We don't want to give a complete free 3
10913 		 * measurements until we exit, so we use
10914 		 * the number of pe's we were in probe-rtt
10915 		 * to add to the startup_epoch. That way
10916 		 * we will still retain the old state.
10917 		 */
10918 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10919 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10920 		/* Make sure to use the lower pg when shifting back in */
10921 		if (bbr->r_ctl.rc_lost &&
10922 		    bbr_use_lower_gain_in_startup &&
10923 		    (bbr->rc_use_google == 0))
10924 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10925 		else
10926 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10927 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10928 		/* Probably not needed but set it anyway */
10929 		bbr_set_state_target(bbr, __LINE__);
10930 		bbr_log_type_statechange(bbr, cts, __LINE__);
10931 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10932 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10933 	}
10934 	bbr_check_probe_rtt_limits(bbr, cts);
10935 }
10936 
10937 static int32_t inline
10938 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10939 {
10940 	if ((bbr->rc_past_init_win == 1) &&
10941 	    (bbr->rc_in_persist == 0) &&
10942 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10943 		return (1);
10944 	}
10945 	if (bbr_can_force_probertt &&
10946 	    (bbr->rc_in_persist == 0) &&
10947 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10948 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10949 		return (1);
10950 	}
10951 	return (0);
10952 }
10953 
10954 static int32_t
10955 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10956 {
10957 	uint64_t btlbw, gain;
10958 	if (pkt_epoch == 0) {
10959 		/*
10960 		 * Need to be on a pkt-epoch to continue.
10961 		 */
10962 		return (0);
10963 	}
10964 	btlbw = bbr_get_full_bw(bbr);
10965 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10966 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10967 	if (btlbw >= gain) {
10968 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
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, 3);
10971 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10972 	}
10973 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10974 		return (1);
10975 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10976 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10977 	return(0);
10978 }
10979 
10980 static int32_t inline
10981 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10982 {
10983 	/* Have we gained 25% in the last 3 packet based epoch's? */
10984 	uint64_t btlbw, gain;
10985 	int do_exit;
10986 	int delta, rtt_gain;
10987 
10988 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10989 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10990 		/*
10991 		 * This qualifies as a RTT_PROBE session since we drop the
10992 		 * data outstanding to nothing and waited more than
10993 		 * bbr_rtt_probe_time.
10994 		 */
10995 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10996 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10997 	}
10998 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10999 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
11000 		return (0);
11001 	}
11002 	if (bbr->rc_use_google)
11003 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
11004 
11005 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11006 	    (bbr_use_lower_gain_in_startup)) {
11007 		/* Drop to a lower gain 1.5 x since we saw loss */
11008 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11009 	}
11010 	if (pkt_epoch == 0) {
11011 		/*
11012 		 * Need to be on a pkt-epoch to continue.
11013 		 */
11014 		return (0);
11015 	}
11016 	if (bbr_rtt_gain_thresh) {
11017 		/*
11018 		 * Do we allow a flow to stay
11019 		 * in startup with no loss and no
11020 		 * gain in rtt over a set threshold?
11021 		 */
11022 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11023 		    bbr->r_ctl.startup_last_srtt &&
11024 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11025 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11026 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11027 		} else
11028 			rtt_gain = 0;
11029 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11030 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11031 			/* First time or new lower value */
11032 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11033 
11034 		if ((bbr->r_ctl.rc_lost == 0) &&
11035 		    (rtt_gain < bbr_rtt_gain_thresh)) {
11036 			/*
11037 			 * No loss, and we are under
11038 			 * our gain threhold for
11039 			 * increasing RTT.
11040 			 */
11041 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11042 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
11043 			bbr_log_startup_event(bbr, cts, rtt_gain,
11044 					      delta, bbr->r_ctl.startup_last_srtt, 10);
11045 			return (0);
11046 		}
11047 	}
11048 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11049 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11050 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11051 		/*
11052 		 * We only assess if we have a new measurment when
11053 		 * we have no loss and are not in recovery.
11054 		 * Drag up by one our last_startup epoch so we will hold
11055 		 * the number of non-gain we have already accumulated.
11056 		 */
11057 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11058 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11059 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11060 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11061 		return (0);
11062 	}
11063 	/* Case where we reduced the lost (bad retransmit) */
11064 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11065 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11066 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11067 	btlbw = bbr_get_full_bw(bbr);
11068 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11069 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11070 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11071 	else
11072 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11073 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11074 	do_exit = 0;
11075 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11076 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11077 	if (btlbw >= gain) {
11078 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11079 		/* Update the lost so we won't exit in next set of tests */
11080 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11081 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11082 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11083 	}
11084 	if ((bbr->rc_loss_exit &&
11085 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11086 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11087 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11088 		/*
11089 		 * If we had no gain,  we had loss and that loss was above
11090 		 * our threshould, the rwnd is not constrained, and we have
11091 		 * had at least 3 packet epochs exit. Note that this is
11092 		 * switched off by sysctl. Google does not do this by the
11093 		 * way.
11094 		 */
11095 		if ((ctf_flight_size(bbr->rc_tp,
11096 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11097 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11098 			do_exit = 1;
11099 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11100 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11101 		} else {
11102 			/* Just record an updated loss value */
11103 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11104 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11105 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11106 		}
11107 	} else
11108 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11109 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11110 	    do_exit) {
11111 		/* Return 1 to exit the startup state. */
11112 		return (1);
11113 	}
11114 	/* Stay in startup */
11115 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11116 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11117 	return (0);
11118 }
11119 
11120 static void
11121 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11122 {
11123 	/*
11124 	 * A tick occurred in the rtt epoch do we need to do anything?
11125 	 */
11126 #ifdef BBR_INVARIANTS
11127 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11128 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11129 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11130 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11131 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11132 		/* Debug code? */
11133 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11134 	}
11135 #endif
11136 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11137 		/* Do we exit the startup state? */
11138 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11139 			uint32_t time_in;
11140 
11141 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11142 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11143 			bbr->rc_filled_pipe = 1;
11144 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11145 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11146 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11147 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11148 			} else
11149 				time_in = 0;
11150 			if (bbr->rc_no_pacing)
11151 				bbr->rc_no_pacing = 0;
11152 			bbr->r_ctl.rc_bbr_state_time = cts;
11153 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11154 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11155 			bbr_set_state_target(bbr, __LINE__);
11156 			if ((bbr->rc_use_google == 0) &&
11157 			    bbr_slam_cwnd_in_main_drain) {
11158 				/* Here we don't have to worry about probe-rtt */
11159 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11160 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11161 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11162 			}
11163 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11164 			bbr_log_type_statechange(bbr, cts, __LINE__);
11165 			if (ctf_flight_size(bbr->rc_tp,
11166 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11167 			    bbr->r_ctl.rc_target_at_state) {
11168 				/*
11169 				 * Switch to probe_bw if we are already
11170 				 * there
11171 				 */
11172 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11173 				bbr_substate_change(bbr, cts, __LINE__, 0);
11174 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11175 				bbr_log_type_statechange(bbr, cts, __LINE__);
11176 			}
11177 		}
11178 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11179 		uint32_t inflight;
11180 		struct tcpcb *tp;
11181 
11182 		tp = bbr->rc_tp;
11183 		inflight = ctf_flight_size(tp,
11184 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11185 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11186 			/* We have reached a flight of the cwnd target */
11187 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11188 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11189 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11190 			bbr_set_state_target(bbr, __LINE__);
11191 			/*
11192 			 * Rig it so we don't do anything crazy and
11193 			 * start fresh with a new randomization.
11194 			 */
11195 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11196 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11197 			bbr_substate_change(bbr, cts, __LINE__, 1);
11198 		}
11199 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11200 		/* Has in-flight reached the bdp (or less)? */
11201 		uint32_t inflight;
11202 		struct tcpcb *tp;
11203 
11204 		tp = bbr->rc_tp;
11205 		inflight = ctf_flight_size(tp,
11206 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11207 		if ((bbr->rc_use_google == 0) &&
11208 		    bbr_slam_cwnd_in_main_drain &&
11209 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11210 			/*
11211 			 * Here we don't have to worry about probe-rtt
11212 			 * re-slam it, but keep it slammed down.
11213 			 */
11214 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11215 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11216 		}
11217 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11218 			/* We have drained */
11219 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11220 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11221 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11222 				uint32_t time_in;
11223 
11224 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11225 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11226 			}
11227 			if ((bbr->rc_use_google == 0) &&
11228 			    bbr_slam_cwnd_in_main_drain &&
11229 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11230 				/* Restore the cwnd */
11231 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11232 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11233 			}
11234 			/* Setup probe-rtt has being done now RRS-HERE */
11235 			bbr->r_ctl.rc_rtt_shrinks = cts;
11236 			bbr->r_ctl.last_in_probertt = cts;
11237 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11238 			/* Randomly pick a sub-state */
11239 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11240 			bbr_substate_change(bbr, cts, __LINE__, 0);
11241 			bbr_log_type_statechange(bbr, cts, __LINE__);
11242 		}
11243 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11244 		uint32_t flight;
11245 
11246 		flight = ctf_flight_size(bbr->rc_tp,
11247 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11248 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11249 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11250 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11251 			/*
11252 			 * We must keep cwnd at the desired MSS.
11253 			 */
11254 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11255 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11256 		} else if ((bbr_prtt_slam_cwnd) &&
11257 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11258 			/* Re-slam it */
11259 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11260 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11261 		}
11262 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11263 			/* Has outstanding reached our target? */
11264 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11265 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11266 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11267 				/* If time is exactly 0, be 1usec off */
11268 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11269 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11270 				if (bbr->rc_use_google == 0) {
11271 					/*
11272 					 * Restore any lowering that as occurred to
11273 					 * reach here
11274 					 */
11275 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11276 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11277 					else
11278 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11279 				}
11280 			}
11281 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11282 			    (bbr->rc_use_google == 0) &&
11283 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11284 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11285 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11286 				/*
11287 				 * We have doddled with our current hptsi
11288 				 * gain an srtt and have still not made it
11289 				 * to target, or we have increased our flight.
11290 				 * Lets reduce the gain by xx%
11291 				 * flooring the reduce at DRAIN (based on
11292 				 * mul/div)
11293 				 */
11294 				int red;
11295 
11296 				bbr->r_ctl.flightsize_at_drain = flight;
11297 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11298 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11299 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11300 					/* Reduce our gain again */
11301 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11302 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11303 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11304 					/* one more chance before we give up */
11305 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11306 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11307 				} else {
11308 					/* At the very bottom */
11309 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11310 				}
11311 			}
11312 		}
11313 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11314 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11315 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11316 			/* Time to exit probe RTT normally */
11317 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11318 		}
11319 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11320 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11321 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11322 			/*
11323 			 * This qualifies as a RTT_PROBE session since we
11324 			 * drop the data outstanding to nothing and waited
11325 			 * more than bbr_rtt_probe_time.
11326 			 */
11327 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11328 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11329 		}
11330 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11331 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11332 		} else {
11333 			bbr_set_probebw_gains(bbr, cts, losses);
11334 		}
11335 	}
11336 }
11337 
11338 static void
11339 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11340 {
11341 	int32_t epoch = 0;
11342 
11343 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11344 		bbr_set_epoch(bbr, cts, line);
11345 		/* At each epoch doe lt bw sampling */
11346 		epoch = 1;
11347 	}
11348 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11349 }
11350 
11351 static int
11352 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11353     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11354     int32_t nxt_pkt, struct timeval *tv)
11355 {
11356 	int32_t thflags, retval;
11357 	uint32_t cts, lcts;
11358 	uint32_t tiwin;
11359 	struct tcpopt to;
11360 	struct tcp_bbr *bbr;
11361 	struct bbr_sendmap *rsm;
11362 	struct timeval ltv;
11363 	int32_t did_out = 0;
11364 	int32_t in_recovery;
11365 	uint16_t nsegs;
11366 	int32_t prev_state;
11367 	uint32_t lost;
11368 
11369 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11370 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11371 	/* add in our stats */
11372 	kern_prefetch(bbr, &prev_state);
11373 	prev_state = 0;
11374 	thflags = th->th_flags;
11375 	/*
11376 	 * If this is either a state-changing packet or current state isn't
11377 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11378 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11379 	 * caller may have unnecessarily acquired a write lock due to a
11380 	 * race.
11381 	 */
11382 	INP_WLOCK_ASSERT(tp->t_inpcb);
11383 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11384 	    __func__));
11385 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11386 	    __func__));
11387 
11388 	tp->t_rcvtime = ticks;
11389 	/*
11390 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11391 	 * the scale is zero.
11392 	 */
11393 	tiwin = th->th_win << tp->snd_scale;
11394 #ifdef STATS
11395 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11396 #endif
11397 
11398 	if (m->m_flags & M_TSTMP) {
11399 		/* Prefer the hardware timestamp if present */
11400 		struct timespec ts;
11401 
11402 		mbuf_tstmp2timespec(m, &ts);
11403 		bbr->rc_tv.tv_sec = ts.tv_sec;
11404 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11405 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11406 	} else if (m->m_flags & M_TSTMP_LRO) {
11407 		/* Next the arrival timestamp */
11408 		struct timespec ts;
11409 
11410 		mbuf_tstmp2timespec(m, &ts);
11411 		bbr->rc_tv.tv_sec = ts.tv_sec;
11412 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11413 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11414 	} else {
11415 		/*
11416 		 * Ok just get the current time.
11417 		 */
11418 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11419 	}
11420 	/*
11421 	 * Parse options on any incoming segment.
11422 	 */
11423 	tcp_dooptions(&to, (u_char *)(th + 1),
11424 	    (th->th_off << 2) - sizeof(struct tcphdr),
11425 	    (thflags & TH_SYN) ? TO_SYN : 0);
11426 
11427 	/*
11428 	 * If timestamps were negotiated during SYN/ACK and a
11429 	 * segment without a timestamp is received, silently drop
11430 	 * the segment, unless it is a RST segment or missing timestamps are
11431 	 * tolerated.
11432 	 * See section 3.2 of RFC 7323.
11433 	 */
11434 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11435 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11436 		retval = 0;
11437 		m_freem(m);
11438 		goto done_with_input;
11439 	}
11440 	/*
11441 	 * If echoed timestamp is later than the current time, fall back to
11442 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11443 	 * were used when this connection was established.
11444 	 */
11445 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11446 		to.to_tsecr -= tp->ts_offset;
11447 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11448 			to.to_tsecr = 0;
11449 	}
11450 	/*
11451 	 * If its the first time in we need to take care of options and
11452 	 * verify we can do SACK for rack!
11453 	 */
11454 	if (bbr->r_state == 0) {
11455 		/*
11456 		 * Process options only when we get SYN/ACK back. The SYN
11457 		 * case for incoming connections is handled in tcp_syncache.
11458 		 * According to RFC1323 the window field in a SYN (i.e., a
11459 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11460 		 * this is traditional behavior, may need to be cleaned up.
11461 		 */
11462 		if (bbr->rc_inp == NULL) {
11463 			bbr->rc_inp = tp->t_inpcb;
11464 		}
11465 		/*
11466 		 * We need to init rc_inp here since its not init'd when
11467 		 * bbr_init is called
11468 		 */
11469 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11470 			if ((to.to_flags & TOF_SCALE) &&
11471 			    (tp->t_flags & TF_REQ_SCALE)) {
11472 				tp->t_flags |= TF_RCVD_SCALE;
11473 				tp->snd_scale = to.to_wscale;
11474 			} else
11475 				tp->t_flags &= ~TF_REQ_SCALE;
11476 			/*
11477 			 * Initial send window.  It will be updated with the
11478 			 * next incoming segment to the scaled value.
11479 			 */
11480 			tp->snd_wnd = th->th_win;
11481 			if ((to.to_flags & TOF_TS) &&
11482 			    (tp->t_flags & TF_REQ_TSTMP)) {
11483 				tp->t_flags |= TF_RCVD_TSTMP;
11484 				tp->ts_recent = to.to_tsval;
11485 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11486 			} else
11487 			    tp->t_flags &= ~TF_REQ_TSTMP;
11488 			if (to.to_flags & TOF_MSS)
11489 				tcp_mss(tp, to.to_mss);
11490 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11491 			    (to.to_flags & TOF_SACKPERM) == 0)
11492 				tp->t_flags &= ~TF_SACK_PERMIT;
11493 			if (IS_FASTOPEN(tp->t_flags)) {
11494 				if (to.to_flags & TOF_FASTOPEN) {
11495 					uint16_t mss;
11496 
11497 					if (to.to_flags & TOF_MSS)
11498 						mss = to.to_mss;
11499 					else
11500 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11501 							mss = TCP6_MSS;
11502 						else
11503 							mss = TCP_MSS;
11504 					tcp_fastopen_update_cache(tp, mss,
11505 					    to.to_tfo_len, to.to_tfo_cookie);
11506 				} else
11507 					tcp_fastopen_disable_path(tp);
11508 			}
11509 		}
11510 		/*
11511 		 * At this point we are at the initial call. Here we decide
11512 		 * if we are doing RACK or not. We do this by seeing if
11513 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11514 		 * we switch to the default code.
11515 		 */
11516 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11517 			/* Bail */
11518 			tcp_switch_back_to_default(tp);
11519 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11520 			    tlen, iptos);
11521 			return (1);
11522 		}
11523 		/* Set the flag */
11524 		bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11525 		tcp_set_hpts(tp->t_inpcb);
11526 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11527 	}
11528 	if (thflags & TH_ACK) {
11529 		/* Track ack types */
11530 		if (to.to_flags & TOF_SACK)
11531 			BBR_STAT_INC(bbr_acks_with_sacks);
11532 		else
11533 			BBR_STAT_INC(bbr_plain_acks);
11534 	}
11535 	/*
11536 	 * This is the one exception case where we set the rack state
11537 	 * always. All other times (timers etc) we must have a rack-state
11538 	 * set (so we assure we have done the checks above for SACK).
11539 	 */
11540 	if (thflags & TH_FIN)
11541 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11542 	if (bbr->r_state != tp->t_state)
11543 		bbr_set_state(tp, bbr, tiwin);
11544 
11545 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11546 		kern_prefetch(rsm, &prev_state);
11547 	prev_state = bbr->r_state;
11548 	bbr->rc_ack_was_delayed = 0;
11549 	lost = bbr->r_ctl.rc_lost;
11550 	bbr->rc_is_pkt_epoch_now = 0;
11551 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11552 		/* Get the real time into lcts and figure the real delay */
11553 		lcts = tcp_get_usecs(&ltv);
11554 		if (TSTMP_GT(lcts, cts)) {
11555 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11556 			bbr->rc_ack_was_delayed = 1;
11557 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11558 				     bbr->r_ctl.highest_hdwr_delay))
11559 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11560 		} else {
11561 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11562 			bbr->rc_ack_was_delayed = 0;
11563 		}
11564 	} else {
11565 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11566 		bbr->rc_ack_was_delayed = 0;
11567 	}
11568 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11569 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11570 		retval = 0;
11571 		m_freem(m);
11572 		goto done_with_input;
11573 	}
11574 	/*
11575 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11576 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11577 	 */
11578 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11579 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11580 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11581 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11582 		return (1);
11583 	}
11584 	in_recovery = IN_RECOVERY(tp->t_flags);
11585 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11586 		bbr->r_ctl.rc_high_rwnd = tiwin;
11587 #ifdef BBR_INVARIANTS
11588 	if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11589 	    (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11590 		panic("tp:%p bbr:%p given a dropped inp:%p",
11591 		    tp, bbr, tp->t_inpcb);
11592 	}
11593 #endif
11594 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11595 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11596 	bbr->rtt_valid = 0;
11597 	if (to.to_flags & TOF_TS) {
11598 		bbr->rc_ts_valid = 1;
11599 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11600 	} else {
11601 		bbr->rc_ts_valid = 0;
11602 		bbr->r_ctl.last_inbound_ts = 0;
11603 	}
11604 	retval = (*bbr->r_substate) (m, th, so,
11605 	    tp, &to, drop_hdrlen,
11606 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11607 #ifdef BBR_INVARIANTS
11608 	if ((retval == 0) &&
11609 	    (tp->t_inpcb == NULL)) {
11610 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11611 		    retval, tp, prev_state);
11612 	}
11613 #endif
11614 	if (nxt_pkt == 0)
11615 		BBR_STAT_INC(bbr_rlock_left_ret0);
11616 	else
11617 		BBR_STAT_INC(bbr_rlock_left_ret1);
11618 	if (retval == 0) {
11619 		/*
11620 		 * If retval is 1 the tcb is unlocked and most likely the tp
11621 		 * is gone.
11622 		 */
11623 		INP_WLOCK_ASSERT(tp->t_inpcb);
11624 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11625 		if (bbr->rc_is_pkt_epoch_now)
11626 			bbr_set_pktepoch(bbr, cts, __LINE__);
11627 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11628 		if (nxt_pkt == 0) {
11629 			if (bbr->r_wanted_output != 0) {
11630 				bbr->rc_output_starts_timer = 0;
11631 				did_out = 1;
11632 				if (tcp_output(tp) < 0)
11633 					return (1);
11634 			} else
11635 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11636 		}
11637 		if ((nxt_pkt == 0) &&
11638 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11639 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11640 		     (tp->t_flags & TF_DELACK) ||
11641 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11642 		      (tp->t_state <= TCPS_CLOSING)))) {
11643 			/*
11644 			 * We could not send (probably in the hpts but
11645 			 * stopped the timer)?
11646 			 */
11647 			if ((tp->snd_max == tp->snd_una) &&
11648 			    ((tp->t_flags & TF_DELACK) == 0) &&
11649 			    (tcp_in_hpts(bbr->rc_inp)) &&
11650 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11651 				/*
11652 				 * keep alive not needed if we are hptsi
11653 				 * output yet
11654 				 */
11655 				;
11656 			} else {
11657 				if (tcp_in_hpts(bbr->rc_inp)) {
11658 					tcp_hpts_remove(bbr->rc_inp);
11659 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11660 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11661 						uint32_t del;
11662 
11663 						del = lcts - bbr->rc_pacer_started;
11664 						if (bbr->r_ctl.rc_last_delay_val > del) {
11665 							BBR_STAT_INC(bbr_force_timer_start);
11666 							bbr->r_ctl.rc_last_delay_val -= del;
11667 							bbr->rc_pacer_started = lcts;
11668 						} else {
11669 							/* We are late */
11670 							bbr->r_ctl.rc_last_delay_val = 0;
11671 							BBR_STAT_INC(bbr_force_output);
11672 							if (tcp_output(tp) < 0)
11673 								return (1);
11674 						}
11675 					}
11676 				}
11677 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11678 				    0);
11679 			}
11680 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11681 			/* Do we have the correct timer running? */
11682 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11683 		}
11684 		/* Do we have a new state */
11685 		if (bbr->r_state != tp->t_state)
11686 			bbr_set_state(tp, bbr, tiwin);
11687 done_with_input:
11688 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11689 		if (did_out)
11690 			bbr->r_wanted_output = 0;
11691 #ifdef BBR_INVARIANTS
11692 		if (tp->t_inpcb == NULL) {
11693 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11694 			    did_out,
11695 			    retval, tp, prev_state);
11696 		}
11697 #endif
11698 	}
11699 	return (retval);
11700 }
11701 
11702 static void
11703 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11704     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11705 {
11706 	struct timeval tv;
11707 	int retval;
11708 
11709 	/* First lets see if we have old packets */
11710 	if (tp->t_in_pkt) {
11711 		if (ctf_do_queued_segments(so, tp, 1)) {
11712 			m_freem(m);
11713 			return;
11714 		}
11715 	}
11716 	if (m->m_flags & M_TSTMP_LRO) {
11717 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11718 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11719 	} else {
11720 		/* Should not be should we kassert instead? */
11721 		tcp_get_usecs(&tv);
11722 	}
11723 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11724 					 drop_hdrlen, tlen, iptos, 0, &tv);
11725 	if (retval == 0) {
11726 		INP_WUNLOCK(tp->t_inpcb);
11727 	}
11728 }
11729 
11730 /*
11731  * Return how much data can be sent without violating the
11732  * cwnd or rwnd.
11733  */
11734 
11735 static inline uint32_t
11736 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11737     uint32_t avail, int32_t sb_offset, uint32_t cts)
11738 {
11739 	uint32_t len;
11740 
11741 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11742 		/* We never want to go over our peers rcv-window */
11743 		len = 0;
11744 	} else {
11745 		uint32_t flight;
11746 
11747 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11748 		if (flight >= sendwin) {
11749 			/*
11750 			 * We have in flight what we are allowed by cwnd (if
11751 			 * it was rwnd blocking it would have hit above out
11752 			 * >= tp->snd_wnd).
11753 			 */
11754 			return (0);
11755 		}
11756 		len = sendwin - flight;
11757 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11758 			/* We would send too much (beyond the rwnd) */
11759 			len = tp->snd_wnd - ctf_outstanding(tp);
11760 		}
11761 		if ((len + sb_offset) > avail) {
11762 			/*
11763 			 * We don't have that much in the SB, how much is
11764 			 * there?
11765 			 */
11766 			len = avail - sb_offset;
11767 		}
11768 	}
11769 	return (len);
11770 }
11771 
11772 static inline void
11773 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11774 {
11775 #ifdef NETFLIX_STATS
11776 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11777 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11778 #endif
11779 }
11780 
11781 static inline void
11782 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11783 {
11784 	if (error) {
11785 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11786 		return;
11787 	}
11788 	if (rsm) {
11789 		if (rsm->r_flags & BBR_TLP) {
11790 			/*
11791 			 * TLP should not count in retran count, but in its
11792 			 * own bin
11793 			 */
11794 #ifdef NETFLIX_STATS
11795 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11796 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11797 #endif
11798 		} else {
11799 			/* Retransmit */
11800 			tp->t_sndrexmitpack++;
11801 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11802 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11803 #ifdef STATS
11804 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11805 			    len);
11806 #endif
11807 		}
11808 		/*
11809 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11810 		 * sub-state
11811 		 */
11812 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11813 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11814 			/* Non probe_bw log in 1, 2, or 4. */
11815 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11816 		} else {
11817 			/*
11818 			 * Log our probe state 3, and log also 5-13 to show
11819 			 * us the recovery sub-state for the send. This
11820 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11821 			 */
11822 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11823 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11824 		}
11825 		/* Place in both 16's the totals of retransmitted */
11826 		counter_u64_add(bbr_state_lost[16], len);
11827 		counter_u64_add(bbr_state_resend[16], 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 
11832 	} else {
11833 		/* New sends */
11834 		KMOD_TCPSTAT_INC(tcps_sndpack);
11835 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11836 		/* Place in 17's the total sent */
11837 		counter_u64_add(bbr_state_resend[17], len);
11838 		counter_u64_add(bbr_state_lost[17], len);
11839 #ifdef STATS
11840 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11841 		    len);
11842 #endif
11843 	}
11844 }
11845 
11846 static void
11847 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11848 {
11849 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11850 		/*
11851 		 * Limit the cwnd to not be above N x the target plus whats
11852 		 * is outstanding. The target is based on the current b/w
11853 		 * estimate.
11854 		 */
11855 		uint32_t target;
11856 
11857 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11858 		target += ctf_outstanding(tp);
11859 		target *= bbr_target_cwnd_mult_limit;
11860 		if (tp->snd_cwnd > target)
11861 			tp->snd_cwnd = target;
11862 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11863 	}
11864 }
11865 
11866 static int
11867 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11868 {
11869 	/*
11870 	 * "adv" is the amount we could increase the window, taking into
11871 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11872 	 */
11873 	int32_t adv;
11874 	int32_t oldwin;
11875 
11876 	adv = recwin;
11877 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11878 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11879 		if (adv > oldwin)
11880 			adv -= oldwin;
11881 		else {
11882 			/* We can't increase the window */
11883 			adv = 0;
11884 		}
11885 	} else
11886 		oldwin = 0;
11887 
11888 	/*
11889 	 * If the new window size ends up being the same as or less
11890 	 * than the old size when it is scaled, then don't force
11891 	 * a window update.
11892 	 */
11893 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11894 		return (0);
11895 
11896 	if (adv >= (2 * maxseg) &&
11897 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11898 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11899 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11900 		return (1);
11901 	}
11902 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11903 		return (1);
11904 	return (0);
11905 }
11906 
11907 /*
11908  * Return 0 on success and a errno on failure to send.
11909  * Note that a 0 return may not mean we sent anything
11910  * if the TCB was on the hpts. A non-zero return
11911  * does indicate the error we got from ip[6]_output.
11912  */
11913 static int
11914 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11915 {
11916 	struct socket *so;
11917 	int32_t len;
11918 	uint32_t cts;
11919 	uint32_t recwin, sendwin;
11920 	int32_t sb_offset;
11921 	int32_t flags, abandon, error = 0;
11922 	struct tcp_log_buffer *lgb = NULL;
11923 	struct mbuf *m;
11924 	struct mbuf *mb;
11925 	uint32_t if_hw_tsomaxsegcount = 0;
11926 	uint32_t if_hw_tsomaxsegsize = 0;
11927 	uint32_t if_hw_tsomax = 0;
11928 	struct ip *ip = NULL;
11929 #ifdef TCPDEBUG
11930 	struct ipovly *ipov = NULL;
11931 #endif
11932 	struct tcp_bbr *bbr;
11933 	struct tcphdr *th;
11934 	struct udphdr *udp = NULL;
11935 	u_char opt[TCP_MAXOLEN];
11936 	unsigned ipoptlen, optlen, hdrlen;
11937 	unsigned ulen;
11938 	uint32_t bbr_seq;
11939 	uint32_t delay_calc=0;
11940 	uint8_t doing_tlp = 0;
11941 	uint8_t local_options;
11942 #ifdef BBR_INVARIANTS
11943 	uint8_t doing_retran_from = 0;
11944 	uint8_t picked_up_retran = 0;
11945 #endif
11946 	uint8_t wanted_cookie = 0;
11947 	uint8_t more_to_rxt=0;
11948 	int32_t prefetch_so_done = 0;
11949 	int32_t prefetch_rsm = 0;
11950  	uint32_t what_we_can = 0;
11951 	uint32_t tot_len = 0;
11952 	uint32_t rtr_cnt = 0;
11953 	uint32_t maxseg, pace_max_segs, p_maxseg;
11954 	int32_t csum_flags = 0;
11955  	int32_t hw_tls;
11956 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11957 	unsigned ipsec_optlen = 0;
11958 
11959 #endif
11960 	volatile int32_t sack_rxmit;
11961 	struct bbr_sendmap *rsm = NULL;
11962 	int32_t tso, mtu;
11963 	struct tcpopt to;
11964 	int32_t slot = 0;
11965 	struct inpcb *inp;
11966 	struct sockbuf *sb;
11967 	uint32_t hpts_calling;
11968 #ifdef INET6
11969 	struct ip6_hdr *ip6 = NULL;
11970 	int32_t isipv6;
11971 #endif
11972 	uint8_t app_limited = BBR_JR_SENT_DATA;
11973 	uint8_t filled_all = 0;
11974 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11975 	/* We take a cache hit here */
11976 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11977 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11978 	inp = bbr->rc_inp;
11979 	so = inp->inp_socket;
11980 	sb = &so->so_snd;
11981  	if (sb->sb_flags & SB_TLS_IFNET)
11982  		hw_tls = 1;
11983  	else
11984  		hw_tls = 0;
11985 	kern_prefetch(sb, &maxseg);
11986 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11987 	if (bbr_minseg(bbr) < maxseg) {
11988 		tcp_bbr_tso_size_check(bbr, cts);
11989 	}
11990 	/* Remove any flags that indicate we are pacing on the inp  */
11991 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11992 	p_maxseg = min(maxseg, pace_max_segs);
11993 	INP_WLOCK_ASSERT(inp);
11994 #ifdef TCP_OFFLOAD
11995 	if (tp->t_flags & TF_TOE)
11996 		return (tcp_offload_output(tp));
11997 #endif
11998 
11999 #ifdef INET6
12000 	if (bbr->r_state) {
12001 		/* Use the cache line loaded if possible */
12002 		isipv6 = bbr->r_is_v6;
12003 	} else {
12004 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
12005 	}
12006 #endif
12007 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
12008 	    tcp_in_hpts(inp)) {
12009 		/*
12010 		 * We are on the hpts for some timer but not hptsi output.
12011 		 * Possibly remove from the hpts so we can send/recv etc.
12012 		 */
12013 		if ((tp->t_flags & TF_ACKNOW) == 0) {
12014 			/*
12015 			 * No immediate demand right now to send an ack, but
12016 			 * the user may have read, making room for new data
12017 			 * (a window update). If so we may want to cancel
12018 			 * whatever timer is running (KEEP/DEL-ACK?) and
12019 			 * continue to send out a window update. Or we may
12020 			 * have gotten more data into the socket buffer to
12021 			 * send.
12022 			 */
12023 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12024 				      (long)TCP_MAXWIN << tp->rcv_scale);
12025 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12026 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
12027 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12028 			    (tp->snd_max - tp->snd_una))) {
12029 				/*
12030 				 * Nothing new to send and no window update
12031 				 * is needed to send. Lets just return and
12032 				 * let the timer-run off.
12033 				 */
12034 				return (0);
12035 			}
12036 		}
12037 		tcp_hpts_remove(inp);
12038 		bbr_timer_cancel(bbr, __LINE__, cts);
12039 	}
12040 	if (bbr->r_ctl.rc_last_delay_val) {
12041 		/* Calculate a rough delay for early escape to sending  */
12042 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12043 			delay_calc = cts - bbr->rc_pacer_started;
12044 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12045 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12046 		else
12047 			delay_calc = 0;
12048 	}
12049 	/* Mark that we have called bbr_output(). */
12050 	if ((bbr->r_timer_override) ||
12051 	    (tp->t_state < TCPS_ESTABLISHED)) {
12052 		/* Timeouts or early states are exempt */
12053 		if (tcp_in_hpts(inp))
12054 			tcp_hpts_remove(inp);
12055 	} else if (tcp_in_hpts(inp)) {
12056 		if ((bbr->r_ctl.rc_last_delay_val) &&
12057 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12058 		    delay_calc) {
12059 			/*
12060 			 * We were being paced for output and the delay has
12061 			 * already exceeded when we were supposed to be
12062 			 * called, lets go ahead and pull out of the hpts
12063 			 * and call output.
12064 			 */
12065 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12066 			bbr->r_ctl.rc_last_delay_val = 0;
12067 			tcp_hpts_remove(inp);
12068 		} else if (tp->t_state == TCPS_CLOSED) {
12069 			bbr->r_ctl.rc_last_delay_val = 0;
12070 			tcp_hpts_remove(inp);
12071 		} else {
12072 			/*
12073 			 * On the hpts, you shall not pass! even if ACKNOW
12074 			 * is on, we will when the hpts fires, unless of
12075 			 * course we are overdue.
12076 			 */
12077 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12078 			return (0);
12079 		}
12080 	}
12081 	bbr->rc_cwnd_limited = 0;
12082 	if (bbr->r_ctl.rc_last_delay_val) {
12083 		/* recalculate the real delay and deal with over/under  */
12084 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12085 			delay_calc = cts - bbr->rc_pacer_started;
12086 		else
12087 			delay_calc = 0;
12088 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12089 			/* Setup the delay which will be added in */
12090 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12091 		else {
12092 			/*
12093 			 * We are early setup to adjust
12094 			 * our slot time.
12095 			 */
12096 			uint64_t merged_val;
12097 
12098 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12099 			bbr->r_agg_early_set = 1;
12100 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12101 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12102 					/* Nope our previous late cancels out the early */
12103 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12104 					bbr->r_agg_early_set = 0;
12105 					bbr->r_ctl.rc_agg_early = 0;
12106 				} else {
12107 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12108 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12109 				}
12110 			}
12111 			merged_val = bbr->rc_pacer_started;
12112 			merged_val <<= 32;
12113 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12114 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12115 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12116 						 bbr->r_agg_early_set, 3);
12117 			bbr->r_ctl.rc_last_delay_val = 0;
12118 			BBR_STAT_INC(bbr_early);
12119 			delay_calc = 0;
12120 		}
12121 	} else {
12122 		/* We were not delayed due to hptsi */
12123 		if (bbr->r_agg_early_set)
12124 			bbr->r_ctl.rc_agg_early = 0;
12125 		bbr->r_agg_early_set = 0;
12126 		delay_calc = 0;
12127 	}
12128 	if (delay_calc) {
12129 		/*
12130 		 * We had a hptsi delay which means we are falling behind on
12131 		 * sending at the expected rate. Calculate an extra amount
12132 		 * of data we can send, if any, to put us back on track.
12133 		 */
12134 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12135 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12136 		else
12137 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12138 	}
12139 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12140 	if ((tp->snd_una == tp->snd_max) &&
12141 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12142 	    (sbavail(sb))) {
12143 		/*
12144 		 * Ok we have been idle with nothing outstanding
12145 		 * we possibly need to start fresh with either a new
12146 		 * suite of states or a fast-ramp up.
12147 		 */
12148 		bbr_restart_after_idle(bbr,
12149 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12150 	}
12151 	/*
12152 	 * Now was there a hptsi delay where we are behind? We only count
12153 	 * being behind if: a) We are not in recovery. b) There was a delay.
12154 	 * <and> c) We had room to send something.
12155 	 *
12156 	 */
12157 	hpts_calling = inp->inp_hpts_calls;
12158 	inp->inp_hpts_calls = 0;
12159 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12160 		int retval;
12161 
12162 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12163 		if (retval != 0) {
12164 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12165 			/*
12166 			 * If timers want tcp_drop(), then pass error out,
12167 			 * otherwise suppress it.
12168 			 */
12169 			return (retval < 0 ? retval : 0);
12170 		}
12171 	}
12172 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12173 	if (hpts_calling &&
12174 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12175 		bbr->r_ctl.rc_last_delay_val = 0;
12176 	}
12177 	bbr->r_timer_override = 0;
12178 	bbr->r_wanted_output = 0;
12179 	/*
12180 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12181 	 * SYN|ACK and those sent by the retransmit timer.
12182 	 */
12183 	if (IS_FASTOPEN(tp->t_flags) &&
12184 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12185 	     (tp->t_state == TCPS_SYN_SENT)) &&
12186 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12187 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12188 		len = 0;
12189 		goto just_return_nolock;
12190 	}
12191 	/*
12192 	 * Before sending anything check for a state update. For hpts
12193 	 * calling without input this is important. If its input calling
12194 	 * then this was already done.
12195 	 */
12196 	if (bbr->rc_use_google == 0)
12197 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12198 again:
12199 	/*
12200 	 * If we've recently taken a timeout, snd_max will be greater than
12201 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12202 	 * for historic reasons the persist timer still uses it. This means
12203 	 * we have to look at it. All retransmissions that are not persits
12204 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12205 	 * end of this routine we pull snd_nxt always up to snd_max.
12206 	 */
12207 	doing_tlp = 0;
12208 #ifdef BBR_INVARIANTS
12209 	doing_retran_from = picked_up_retran = 0;
12210 #endif
12211 	error = 0;
12212 	tso = 0;
12213 	slot = 0;
12214 	mtu = 0;
12215 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12216 	sb_offset = tp->snd_max - tp->snd_una;
12217 	flags = tcp_outflags[tp->t_state];
12218 	sack_rxmit = 0;
12219 	len = 0;
12220 	rsm = NULL;
12221 	if (flags & TH_RST) {
12222 		SOCKBUF_LOCK(sb);
12223 		goto send;
12224 	}
12225 recheck_resend:
12226 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12227 		/* We need to always have one in reserve */
12228 		rsm = bbr_alloc(bbr);
12229 		if (rsm == NULL) {
12230 			error = ENOMEM;
12231 			/* Lie to get on the hpts */
12232 			tot_len = tp->t_maxseg;
12233 			if (hpts_calling)
12234 				/* Retry in a ms */
12235 				slot = 1001;
12236 			goto just_return_nolock;
12237 		}
12238 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12239 		bbr->r_ctl.rc_free_cnt++;
12240 		rsm = NULL;
12241 	}
12242 	/* What do we send, a resend? */
12243 	if (bbr->r_ctl.rc_resend == NULL) {
12244 		/* Check for rack timeout */
12245 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12246 		if (bbr->r_ctl.rc_resend) {
12247 #ifdef BBR_INVARIANTS
12248 			picked_up_retran = 1;
12249 #endif
12250 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12251 		}
12252 	}
12253 	if (bbr->r_ctl.rc_resend) {
12254 		rsm = bbr->r_ctl.rc_resend;
12255 #ifdef BBR_INVARIANTS
12256 		doing_retran_from = 1;
12257 #endif
12258 		/* Remove any TLP flags its a RACK or T-O */
12259 		rsm->r_flags &= ~BBR_TLP;
12260 		bbr->r_ctl.rc_resend = NULL;
12261 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12262 #ifdef BBR_INVARIANTS
12263 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12264 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12265 			goto recheck_resend;
12266 #else
12267 			/* TSNH */
12268 			rsm = NULL;
12269 			goto recheck_resend;
12270 #endif
12271 		}
12272 		rtr_cnt++;
12273 		if (rsm->r_flags & BBR_HAS_SYN) {
12274 			/* Only retransmit a SYN by itself */
12275 			len = 0;
12276 			if ((flags & TH_SYN) == 0) {
12277 				/* Huh something is wrong */
12278 				rsm->r_start++;
12279 				if (rsm->r_start == rsm->r_end) {
12280 					/* Clean it up, somehow we missed the ack? */
12281 					bbr_log_syn(tp, NULL);
12282 				} else {
12283 					/* TFO with data? */
12284 					rsm->r_flags &= ~BBR_HAS_SYN;
12285 					len = rsm->r_end - rsm->r_start;
12286 				}
12287 			} else {
12288 				/* Retransmitting SYN */
12289 				rsm = NULL;
12290 				SOCKBUF_LOCK(sb);
12291 				goto send;
12292 			}
12293 		} else
12294 			len = rsm->r_end - rsm->r_start;
12295 		if ((bbr->rc_resends_use_tso == 0) &&
12296 		    (len > maxseg)) {
12297 			len = maxseg;
12298 			more_to_rxt = 1;
12299 		}
12300 		sb_offset = rsm->r_start - tp->snd_una;
12301 		if (len > 0) {
12302 			sack_rxmit = 1;
12303 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12304 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12305 			    min(len, maxseg));
12306 		} else {
12307 			/* I dont think this can happen */
12308 			rsm = NULL;
12309 			goto recheck_resend;
12310 		}
12311 		BBR_STAT_INC(bbr_resends_set);
12312 	} else if (bbr->r_ctl.rc_tlp_send) {
12313 		/*
12314 		 * Tail loss probe
12315 		 */
12316 		doing_tlp = 1;
12317 		rsm = bbr->r_ctl.rc_tlp_send;
12318 		bbr->r_ctl.rc_tlp_send = NULL;
12319 		sack_rxmit = 1;
12320 		len = rsm->r_end - rsm->r_start;
12321 		rtr_cnt++;
12322 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12323 			len = maxseg;
12324 
12325 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12326 #ifdef BBR_INVARIANTS
12327 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12328 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12329 #else
12330 			/* TSNH */
12331 			rsm = NULL;
12332 			goto recheck_resend;
12333 #endif
12334 		}
12335 		sb_offset = rsm->r_start - tp->snd_una;
12336 		BBR_STAT_INC(bbr_tlp_set);
12337 	}
12338 	/*
12339 	 * Enforce a connection sendmap count limit if set
12340 	 * as long as we are not retransmiting.
12341 	 */
12342 	if ((rsm == NULL) &&
12343 	    (V_tcp_map_entries_limit > 0) &&
12344 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12345 		BBR_STAT_INC(bbr_alloc_limited);
12346 		if (!bbr->alloc_limit_reported) {
12347 			bbr->alloc_limit_reported = 1;
12348 			BBR_STAT_INC(bbr_alloc_limited_conns);
12349 		}
12350 		goto just_return_nolock;
12351 	}
12352 #ifdef BBR_INVARIANTS
12353 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12354 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12355 		    tp, bbr, rsm, sb_offset, len);
12356 	}
12357 #endif
12358 	/*
12359 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12360 	 * state flags.
12361 	 */
12362 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12363 		flags |= TH_FIN;
12364 	if (tp->t_flags & TF_NEEDSYN)
12365 		flags |= TH_SYN;
12366 
12367 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12368 		/* we are retransmitting the fin */
12369 		len--;
12370 		if (len) {
12371 			/*
12372 			 * When retransmitting data do *not* include the
12373 			 * FIN. This could happen from a TLP probe if we
12374 			 * allowed data with a FIN.
12375 			 */
12376 			flags &= ~TH_FIN;
12377 		}
12378 	} else if (rsm) {
12379 		if (flags & TH_FIN)
12380 			flags &= ~TH_FIN;
12381 	}
12382 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12383 		void *end_rsm;
12384 
12385 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12386 		if (end_rsm)
12387 			kern_prefetch(end_rsm, &prefetch_rsm);
12388 		prefetch_rsm = 1;
12389 	}
12390 	SOCKBUF_LOCK(sb);
12391 	/*
12392 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12393 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12394 	 * negative length.  This can also occur when TCP opens up its
12395 	 * congestion window while receiving additional duplicate acks after
12396 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12397 	 * the fast-retransmit.
12398 	 *
12399 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12400 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12401 	 * up 0.
12402 	 *
12403 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12404 	 * in which case len is already set.
12405 	 */
12406 	if (sack_rxmit == 0) {
12407 		uint32_t avail;
12408 
12409 		avail = sbavail(sb);
12410 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12411 			sb_offset = tp->snd_max - tp->snd_una;
12412 		else
12413 			sb_offset = 0;
12414 		if (bbr->rc_tlp_new_data) {
12415 			/* TLP is forcing out new data */
12416 			uint32_t tlplen;
12417 
12418 			doing_tlp = 1;
12419 			tlplen = maxseg;
12420 
12421 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12422 				tlplen = (uint32_t)(avail - sb_offset);
12423 			}
12424 			if (tlplen > tp->snd_wnd) {
12425 				len = tp->snd_wnd;
12426 			} else {
12427 				len = tlplen;
12428 			}
12429 			bbr->rc_tlp_new_data = 0;
12430 		} else {
12431 			what_we_can = len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12432 			if ((len < p_maxseg) &&
12433 			    (bbr->rc_in_persist == 0) &&
12434 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12435 			    ((avail - sb_offset) >= p_maxseg)) {
12436 				/*
12437 				 * We are not completing whats in the socket
12438 				 * buffer (i.e. there is at least a segment
12439 				 * waiting to send) and we have 2 or more
12440 				 * segments outstanding. There is no sense
12441 				 * of sending a little piece. Lets defer and
12442 				 * and wait until we can send a whole
12443 				 * segment.
12444 				 */
12445 				len = 0;
12446 			}
12447 			if (bbr->rc_in_persist) {
12448 				/*
12449 				 * We are in persists, figure out if
12450 				 * a retransmit is available (maybe the previous
12451 				 * persists we sent) or if we have to send new
12452 				 * data.
12453 				 */
12454 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12455 				if (rsm) {
12456 					len = rsm->r_end - rsm->r_start;
12457 					if (rsm->r_flags & BBR_HAS_FIN)
12458 						len--;
12459 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12460 						len = maxseg;
12461 					if (len > 1)
12462 						BBR_STAT_INC(bbr_persist_reneg);
12463 					/*
12464 					 * XXXrrs we could force the len to
12465 					 * 1 byte here to cause the chunk to
12466 					 * split apart.. but that would then
12467 					 * mean we always retransmit it as
12468 					 * one byte even after the window
12469 					 * opens.
12470 					 */
12471 					sack_rxmit = 1;
12472 					sb_offset = rsm->r_start - tp->snd_una;
12473 				} else {
12474 					/*
12475 					 * First time through in persists or peer
12476 					 * acked our one byte. Though we do have
12477 					 * to have something in the sb.
12478 					 */
12479 					len = 1;
12480 					sb_offset = 0;
12481 					if (avail == 0)
12482 					    len = 0;
12483 				}
12484 			}
12485 		}
12486 	}
12487 	if (prefetch_so_done == 0) {
12488 		kern_prefetch(so, &prefetch_so_done);
12489 		prefetch_so_done = 1;
12490 	}
12491 	/*
12492 	 * Lop off SYN bit if it has already been sent.  However, if this is
12493 	 * SYN-SENT state and if segment contains data and if we don't know
12494 	 * that foreign host supports TAO, suppress sending segment.
12495 	 */
12496 	if ((flags & TH_SYN) && (rsm == NULL) &&
12497 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12498 		if (tp->t_state != TCPS_SYN_RECEIVED)
12499 			flags &= ~TH_SYN;
12500 		/*
12501 		 * When sending additional segments following a TFO SYN|ACK,
12502 		 * do not include the SYN bit.
12503 		 */
12504 		if (IS_FASTOPEN(tp->t_flags) &&
12505 		    (tp->t_state == TCPS_SYN_RECEIVED))
12506 			flags &= ~TH_SYN;
12507 		sb_offset--, len++;
12508 		if (sbavail(sb) == 0)
12509 			len = 0;
12510 	} else if ((flags & TH_SYN) && rsm) {
12511 		/*
12512 		 * Subtract one from the len for the SYN being
12513 		 * retransmitted.
12514 		 */
12515 		len--;
12516 	}
12517 	/*
12518 	 * Be careful not to send data and/or FIN on SYN segments. This
12519 	 * measure is needed to prevent interoperability problems with not
12520 	 * fully conformant TCP implementations.
12521 	 */
12522 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12523 		len = 0;
12524 		flags &= ~TH_FIN;
12525 	}
12526 	/*
12527 	 * On TFO sockets, ensure no data is sent in the following cases:
12528 	 *
12529 	 *  - When retransmitting SYN|ACK on a passively-created socket
12530 	 *  - When retransmitting SYN on an actively created socket
12531 	 *  - When sending a zero-length cookie (cookie request) on an
12532 	 *    actively created socket
12533 	 *  - When the socket is in the CLOSED state (RST is being sent)
12534 	 */
12535 	if (IS_FASTOPEN(tp->t_flags) &&
12536 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12537 	     ((tp->t_state == TCPS_SYN_SENT) &&
12538 	      (tp->t_tfo_client_cookie_len == 0)) ||
12539 	     (flags & TH_RST))) {
12540 		len = 0;
12541 		sack_rxmit = 0;
12542 		rsm = NULL;
12543 	}
12544 	/* Without fast-open there should never be data sent on a SYN */
12545 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12546 		len = 0;
12547 	if (len <= 0) {
12548 		/*
12549 		 * If FIN has been sent but not acked, but we haven't been
12550 		 * called to retransmit, len will be < 0.  Otherwise, window
12551 		 * shrank after we sent into it.  If window shrank to 0,
12552 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12553 		 * window, and set the persist timer if it isn't already
12554 		 * going.  If the window didn't close completely, just wait
12555 		 * for an ACK.
12556 		 *
12557 		 * We also do a general check here to ensure that we will
12558 		 * set the persist timer when we have data to send, but a
12559 		 * 0-byte window. This makes sure the persist timer is set
12560 		 * even if the packet hits one of the "goto send" lines
12561 		 * below.
12562 		 */
12563 		len = 0;
12564 		if ((tp->snd_wnd == 0) &&
12565 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12566 		    (tp->snd_una == tp->snd_max) &&
12567 		    (sb_offset < (int)sbavail(sb))) {
12568 			/*
12569 			 * Not enough room in the rwnd to send
12570 			 * a paced segment out.
12571 			 */
12572 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12573 		}
12574 	} else if ((rsm == NULL) &&
12575 		   (doing_tlp == 0) &&
12576 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12577 		/*
12578 		 * We are not sending a full segment for
12579 		 * some reason. Should we not send anything (think
12580 		 * sws or persists)?
12581 		 */
12582 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12583 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12584 		    (len < (int)(sbavail(sb) - sb_offset))) {
12585 			/*
12586 			 * Here the rwnd is less than
12587 			 * the pacing size, this is not a retransmit,
12588 			 * we are established and
12589 			 * the send is not the last in the socket buffer
12590 			 * lets not send, and possibly enter persists.
12591 			 */
12592 			len = 0;
12593 			if (tp->snd_max == tp->snd_una)
12594 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12595 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12596 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12597 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12598 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12599 			   (len < bbr_minseg(bbr))) {
12600 			/*
12601 			 * Here we are not retransmitting, and
12602 			 * the cwnd is not so small that we could
12603 			 * not send at least a min size (rxt timer
12604 			 * not having gone off), We have 2 segments or
12605 			 * more already in flight, its not the tail end
12606 			 * of the socket buffer  and the cwnd is blocking
12607 			 * us from sending out minimum pacing segment size.
12608 			 * Lets not send anything.
12609 			 */
12610 			bbr->rc_cwnd_limited = 1;
12611 			len = 0;
12612 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12613 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12614 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12615 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12616 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12617 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12618 			/*
12619 			 * Here we have a send window but we have
12620 			 * filled it up and we can't send another pacing segment.
12621 			 * We also have in flight more than 2 segments
12622 			 * and we are not completing the sb i.e. we allow
12623 			 * the last bytes of the sb to go out even if
12624 			 * its not a full pacing segment.
12625 			 */
12626 			len = 0;
12627 		}
12628 	}
12629 	/* len will be >= 0 after this point. */
12630 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12631 	tcp_sndbuf_autoscale(tp, so, sendwin);
12632 	/*
12633 	 *
12634 	 */
12635 	if (bbr->rc_in_persist &&
12636 	    len &&
12637 	    (rsm == NULL) &&
12638 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12639 		/*
12640 		 * We are in persist, not doing a retransmit and don't have enough space
12641 		 * yet to send a full TSO. So is it at the end of the sb
12642 		 * if so we need to send else nuke to 0 and don't send.
12643 		 */
12644 		int sbleft;
12645 		if (sbavail(sb) > sb_offset)
12646 			sbleft = sbavail(sb) - sb_offset;
12647 		else
12648 			sbleft = 0;
12649 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12650 			/* not at end of sb lets not send */
12651 			len = 0;
12652 		}
12653 	}
12654 	/*
12655 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12656 	 * hardware).
12657 	 *
12658 	 * TSO may only be used if we are in a pure bulk sending state.  The
12659 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12660 	 * options prevent using TSO.  With TSO the TCP header is the same
12661 	 * (except for the sequence number) for all generated packets.  This
12662 	 * makes it impossible to transmit any options which vary per
12663 	 * generated segment or packet.
12664 	 *
12665 	 * IPv4 handling has a clear separation of ip options and ip header
12666 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12667 	 * does the right thing below to provide length of just ip options
12668 	 * and thus checking for ipoptlen is enough to decide if ip options
12669 	 * are present.
12670 	 */
12671 #ifdef INET6
12672 	if (isipv6)
12673 		ipoptlen = ip6_optlen(inp);
12674 	else
12675 #endif
12676 	if (inp->inp_options)
12677 		ipoptlen = inp->inp_options->m_len -
12678 		    offsetof(struct ipoption, ipopt_list);
12679 	else
12680 		ipoptlen = 0;
12681 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12682 	/*
12683 	 * Pre-calculate here as we save another lookup into the darknesses
12684 	 * of IPsec that way and can actually decide if TSO is ok.
12685 	 */
12686 #ifdef INET6
12687 	if (isipv6 && IPSEC_ENABLED(ipv6))
12688 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12689 #ifdef INET
12690 	else
12691 #endif
12692 #endif				/* INET6 */
12693 #ifdef INET
12694 	if (IPSEC_ENABLED(ipv4))
12695 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12696 #endif				/* INET */
12697 #endif				/* IPSEC */
12698 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12699 	ipoptlen += ipsec_optlen;
12700 #endif
12701 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12702 	    (len > maxseg) &&
12703 	    (tp->t_port == 0) &&
12704 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12705 	    tp->rcv_numsacks == 0 &&
12706 	    ipoptlen == 0)
12707 		tso = 1;
12708 
12709 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12710 	    (long)TCP_MAXWIN << tp->rcv_scale);
12711 	/*
12712 	 * Sender silly window avoidance.   We transmit under the following
12713 	 * conditions when len is non-zero:
12714 	 *
12715 	 * - We have a full segment (or more with TSO) - This is the last
12716 	 * buffer in a write()/send() and we are either idle or running
12717 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12718 	 * then 1/2 the maximum send window's worth of data (receiver may be
12719 	 * limited the window size) - we need to retransmit
12720 	 */
12721 	if (rsm)
12722 		goto send;
12723 	if (len) {
12724 		if (sack_rxmit)
12725 			goto send;
12726 		if (len >= p_maxseg)
12727 			goto send;
12728 		/*
12729 		 * NOTE! on localhost connections an 'ack' from the remote
12730 		 * end may occur synchronously with the output and cause us
12731 		 * to flush a buffer queued with moretocome.  XXX
12732 		 *
12733 		 */
12734 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12735 		    ((tp->t_flags & TF_NODELAY) ||
12736 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12737 		    (tp->t_flags & TF_NOPUSH) == 0) {
12738 			goto send;
12739 		}
12740 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12741 			goto send;
12742 		}
12743 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12744 			goto send;
12745 		}
12746 	}
12747 	/*
12748 	 * Sending of standalone window updates.
12749 	 *
12750 	 * Window updates are important when we close our window due to a
12751 	 * full socket buffer and are opening it again after the application
12752 	 * reads data from it.  Once the window has opened again and the
12753 	 * remote end starts to send again the ACK clock takes over and
12754 	 * provides the most current window information.
12755 	 *
12756 	 * We must avoid the silly window syndrome whereas every read from
12757 	 * the receive buffer, no matter how small, causes a window update
12758 	 * to be sent.  We also should avoid sending a flurry of window
12759 	 * updates when the socket buffer had queued a lot of data and the
12760 	 * application is doing small reads.
12761 	 *
12762 	 * Prevent a flurry of pointless window updates by only sending an
12763 	 * update when we can increase the advertized window by more than
12764 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12765 	 * full or is very small be more aggressive and send an update
12766 	 * whenever we can increase by two mss sized segments. In all other
12767 	 * situations the ACK's to new incoming data will carry further
12768 	 * window increases.
12769 	 *
12770 	 * Don't send an independent window update if a delayed ACK is
12771 	 * pending (it will get piggy-backed on it) or the remote side
12772 	 * already has done a half-close and won't send more data.  Skip
12773 	 * this if the connection is in T/TCP half-open state.
12774 	 */
12775 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12776 	    !(tp->t_flags & TF_DELACK) &&
12777 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12778 		/* Check to see if we should do a window update */
12779 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12780 			goto send;
12781 	}
12782 	/*
12783 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12784 	 * is also a catch-all for the retransmit timer timeout case.
12785 	 */
12786 	if (tp->t_flags & TF_ACKNOW) {
12787 		goto send;
12788 	}
12789 	if (flags & TH_RST) {
12790 		/* Always send a RST if one is due */
12791 		goto send;
12792 	}
12793 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12794 		goto send;
12795 	}
12796 	/*
12797 	 * If our state indicates that FIN should be sent and we have not
12798 	 * yet done so, then we need to send.
12799 	 */
12800 	if (flags & TH_FIN &&
12801 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12802 		goto send;
12803 	}
12804 	/*
12805 	 * No reason to send a segment, just return.
12806 	 */
12807 just_return:
12808 	SOCKBUF_UNLOCK(sb);
12809 just_return_nolock:
12810 	if (tot_len)
12811 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12812 	if (bbr->rc_no_pacing)
12813 		slot = 0;
12814 	if (tot_len == 0) {
12815 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12816 		    tp->snd_wnd) {
12817 			BBR_STAT_INC(bbr_rwnd_limited);
12818 			app_limited = BBR_JR_RWND_LIMITED;
12819 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12820 			if ((bbr->rc_in_persist == 0) &&
12821 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12822 			    (tp->snd_max == tp->snd_una) &&
12823 			    sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
12824 				/* No send window.. we must enter persist */
12825 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12826 			}
12827 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12828 			BBR_STAT_INC(bbr_app_limited);
12829 			app_limited = BBR_JR_APP_LIMITED;
12830 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12831 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12832 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12833 			BBR_STAT_INC(bbr_cwnd_limited);
12834  			app_limited = BBR_JR_CWND_LIMITED;
12835 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12836 									bbr->r_ctl.rc_lost_bytes)));
12837 			bbr->rc_cwnd_limited = 1;
12838 		} else {
12839 			BBR_STAT_INC(bbr_app_limited);
12840 			app_limited = BBR_JR_APP_LIMITED;
12841 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12842 		}
12843 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12844 		bbr->r_agg_early_set = 0;
12845 		bbr->r_ctl.rc_agg_early = 0;
12846 		bbr->r_ctl.rc_last_delay_val = 0;
12847 	} else if (bbr->rc_use_google == 0)
12848 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12849 	/* Are we app limited? */
12850 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12851 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12852 		/**
12853 		 * We are application limited.
12854 		 */
12855 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12856 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12857 	}
12858 	if (tot_len == 0)
12859 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12860 	/* Dont update the time if we did not send */
12861 	bbr->r_ctl.rc_last_delay_val = 0;
12862 	bbr->rc_output_starts_timer = 1;
12863 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12864 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12865 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12866 		/* Make sure snd_nxt is drug up */
12867 		tp->snd_nxt = tp->snd_max;
12868 	}
12869 	return (error);
12870 
12871 send:
12872 	if (doing_tlp == 0) {
12873 		/*
12874 		 * Data not a TLP, and its not the rxt firing. If it is the
12875 		 * rxt firing, we want to leave the tlp_in_progress flag on
12876 		 * so we don't send another TLP. It has to be a rack timer
12877 		 * or normal send (response to acked data) to clear the tlp
12878 		 * in progress flag.
12879 		 */
12880 		bbr->rc_tlp_in_progress = 0;
12881 		bbr->rc_tlp_rtx_out = 0;
12882 	} else {
12883 		/*
12884 		 * Its a TLP.
12885 		 */
12886 		bbr->rc_tlp_in_progress = 1;
12887 	}
12888 	bbr_timer_cancel(bbr, __LINE__, cts);
12889 	if (rsm == NULL) {
12890 		if (sbused(sb) > 0) {
12891 			/*
12892 			 * This is sub-optimal. We only send a stand alone
12893 			 * FIN on its own segment.
12894 			 */
12895 			if (flags & TH_FIN) {
12896 				flags &= ~TH_FIN;
12897 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12898 					/* Lets not send this */
12899 					slot = 0;
12900 					goto just_return;
12901 				}
12902 			}
12903 		}
12904 	} else {
12905 		/*
12906 		 * We do *not* send a FIN on a retransmit if it has data.
12907 		 * The if clause here where len > 1 should never come true.
12908 		 */
12909 		if ((len > 0) &&
12910 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12911 		    (flags & TH_FIN))) {
12912 			flags &= ~TH_FIN;
12913 			len--;
12914 		}
12915 	}
12916 	SOCKBUF_LOCK_ASSERT(sb);
12917 	if (len > 0) {
12918 		if ((tp->snd_una == tp->snd_max) &&
12919 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12920 			/*
12921 			 * This qualifies as a RTT_PROBE session since we
12922 			 * drop the data outstanding to nothing and waited
12923 			 * more than bbr_rtt_probe_time.
12924 			 */
12925 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12926 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12927 		}
12928 		if (len >= maxseg)
12929 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12930 		else
12931 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12932 	}
12933 	/*
12934 	 * Before ESTABLISHED, force sending of initial options unless TCP
12935 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12936 	 * plus TCP options always fit in a single mbuf, leaving room for a
12937 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12938 	 * + optlen <= MCLBYTES
12939 	 */
12940 	optlen = 0;
12941 #ifdef INET6
12942 	if (isipv6)
12943 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12944 	else
12945 #endif
12946 		hdrlen = sizeof(struct tcpiphdr);
12947 
12948 	/*
12949 	 * Compute options for segment. We only have to care about SYN and
12950 	 * established connection segments.  Options for SYN-ACK segments
12951 	 * are handled in TCP syncache.
12952 	 */
12953 	to.to_flags = 0;
12954 	local_options = 0;
12955 	if ((tp->t_flags & TF_NOOPT) == 0) {
12956 		/* Maximum segment size. */
12957 		if (flags & TH_SYN) {
12958 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12959 			if (tp->t_port)
12960 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12961 			to.to_flags |= TOF_MSS;
12962 			/*
12963 			 * On SYN or SYN|ACK transmits on TFO connections,
12964 			 * only include the TFO option if it is not a
12965 			 * retransmit, as the presence of the TFO option may
12966 			 * have caused the original SYN or SYN|ACK to have
12967 			 * been dropped by a middlebox.
12968 			 */
12969 			if (IS_FASTOPEN(tp->t_flags) &&
12970 			    (tp->t_rxtshift == 0)) {
12971 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12972 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12973 					to.to_tfo_cookie =
12974 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12975 					to.to_flags |= TOF_FASTOPEN;
12976 					wanted_cookie = 1;
12977 				} else if (tp->t_state == TCPS_SYN_SENT) {
12978 					to.to_tfo_len =
12979 					    tp->t_tfo_client_cookie_len;
12980 					to.to_tfo_cookie =
12981 					    tp->t_tfo_cookie.client;
12982 					to.to_flags |= TOF_FASTOPEN;
12983 					wanted_cookie = 1;
12984 				}
12985 			}
12986 		}
12987 		/* Window scaling. */
12988 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12989 			to.to_wscale = tp->request_r_scale;
12990 			to.to_flags |= TOF_SCALE;
12991 		}
12992 		/* Timestamps. */
12993 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12994 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12995 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12996 			to.to_tsecr = tp->ts_recent;
12997 			to.to_flags |= TOF_TS;
12998 			local_options += TCPOLEN_TIMESTAMP + 2;
12999 		}
13000 		/* Set receive buffer autosizing timestamp. */
13001 		if (tp->rfbuf_ts == 0 &&
13002 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
13003 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
13004 		/* Selective ACK's. */
13005 		if (flags & TH_SYN)
13006 			to.to_flags |= TOF_SACKPERM;
13007 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13008 		    tp->rcv_numsacks > 0) {
13009 			to.to_flags |= TOF_SACK;
13010 			to.to_nsacks = tp->rcv_numsacks;
13011 			to.to_sacks = (u_char *)tp->sackblks;
13012 		}
13013 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13014 		/* TCP-MD5 (RFC2385). */
13015 		if (tp->t_flags & TF_SIGNATURE)
13016 			to.to_flags |= TOF_SIGNATURE;
13017 #endif				/* TCP_SIGNATURE */
13018 
13019 		/* Processing the options. */
13020 		hdrlen += (optlen = tcp_addoptions(&to, opt));
13021 		/*
13022 		 * If we wanted a TFO option to be added, but it was unable
13023 		 * to fit, ensure no data is sent.
13024 		 */
13025 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13026 		    !(to.to_flags & TOF_FASTOPEN))
13027 			len = 0;
13028 	}
13029 	if (tp->t_port) {
13030 		if (V_tcp_udp_tunneling_port == 0) {
13031 			/* The port was removed?? */
13032 			SOCKBUF_UNLOCK(&so->so_snd);
13033 			return (EHOSTUNREACH);
13034 		}
13035 		hdrlen += sizeof(struct udphdr);
13036 	}
13037 #ifdef INET6
13038 	if (isipv6)
13039 		ipoptlen = ip6_optlen(tp->t_inpcb);
13040 	else
13041 #endif
13042 	if (tp->t_inpcb->inp_options)
13043 		ipoptlen = tp->t_inpcb->inp_options->m_len -
13044 		    offsetof(struct ipoption, ipopt_list);
13045 	else
13046 		ipoptlen = 0;
13047 	ipoptlen = 0;
13048 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13049 	ipoptlen += ipsec_optlen;
13050 #endif
13051 	if (bbr->rc_last_options != local_options) {
13052 		/*
13053 		 * Cache the options length this generally does not change
13054 		 * on a connection. We use this to calculate TSO.
13055 		 */
13056 		bbr->rc_last_options = local_options;
13057 	}
13058 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
13059 	p_maxseg = min(maxseg, pace_max_segs);
13060 	/*
13061 	 * Adjust data length if insertion of options will bump the packet
13062 	 * length beyond the t_maxseg length. Clear the FIN bit because we
13063 	 * cut off the tail of the segment.
13064 	 */
13065 	if (len > maxseg) {
13066 		if (len != 0 && (flags & TH_FIN)) {
13067 			flags &= ~TH_FIN;
13068 		}
13069 		if (tso) {
13070 			uint32_t moff;
13071 			int32_t max_len;
13072 
13073 			/* extract TSO information */
13074 			if_hw_tsomax = tp->t_tsomax;
13075 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13076 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13077 			KASSERT(ipoptlen == 0,
13078 			    ("%s: TSO can't do IP options", __func__));
13079 
13080 			/*
13081 			 * Check if we should limit by maximum payload
13082 			 * length:
13083 			 */
13084 			if (if_hw_tsomax != 0) {
13085 				/* compute maximum TSO length */
13086 				max_len = (if_hw_tsomax - hdrlen -
13087 				    max_linkhdr);
13088 				if (max_len <= 0) {
13089 					len = 0;
13090 				} else if (len > max_len) {
13091 					len = max_len;
13092 				}
13093 			}
13094 			/*
13095 			 * Prevent the last segment from being fractional
13096 			 * unless the send sockbuf can be emptied:
13097 			 */
13098 			if ((sb_offset + len) < sbavail(sb)) {
13099 				moff = len % (uint32_t)maxseg;
13100 				if (moff != 0) {
13101 					len -= moff;
13102 				}
13103 			}
13104 			/*
13105 			 * In case there are too many small fragments don't
13106 			 * use TSO:
13107 			 */
13108 			if (len <= maxseg) {
13109 				len = maxseg;
13110 				tso = 0;
13111 			}
13112 		} else {
13113 			/* Not doing TSO */
13114 			if (optlen + ipoptlen >= tp->t_maxseg) {
13115 				/*
13116 				 * Since we don't have enough space to put
13117 				 * the IP header chain and the TCP header in
13118 				 * one packet as required by RFC 7112, don't
13119 				 * send it. Also ensure that at least one
13120 				 * byte of the payload can be put into the
13121 				 * TCP segment.
13122 				 */
13123 				SOCKBUF_UNLOCK(&so->so_snd);
13124 				error = EMSGSIZE;
13125 				sack_rxmit = 0;
13126 				goto out;
13127 			}
13128 			len = maxseg;
13129 		}
13130 	} else {
13131 		/* Not doing TSO */
13132 		if_hw_tsomaxsegcount = 0;
13133 		tso = 0;
13134 	}
13135 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13136 	    ("%s: len > IP_MAXPACKET", __func__));
13137 #ifdef DIAGNOSTIC
13138 #ifdef INET6
13139 	if (max_linkhdr + hdrlen > MCLBYTES)
13140 #else
13141 	if (max_linkhdr + hdrlen > MHLEN)
13142 #endif
13143 		panic("tcphdr too big");
13144 #endif
13145 	/*
13146 	 * This KASSERT is here to catch edge cases at a well defined place.
13147 	 * Before, those had triggered (random) panic conditions further
13148 	 * down.
13149 	 */
13150 #ifdef BBR_INVARIANTS
13151 	if (sack_rxmit) {
13152 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13153 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13154 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13155 		}
13156 	}
13157 #endif
13158 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13159 	if ((len == 0) &&
13160 	    (flags & TH_FIN) &&
13161 	    (sbused(sb))) {
13162 		/*
13163 		 * We have outstanding data, don't send a fin by itself!.
13164 		 */
13165 		slot = 0;
13166 		goto just_return;
13167 	}
13168 	/*
13169 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13170 	 * and initialize the header from the template for sends on this
13171 	 * connection.
13172 	 */
13173 	if (len) {
13174 		uint32_t moff;
13175 		uint32_t orig_len;
13176 
13177 		/*
13178 		 * We place a limit on sending with hptsi.
13179 		 */
13180 		if ((rsm == NULL) && len > pace_max_segs)
13181 			len = pace_max_segs;
13182 		if (len <= maxseg)
13183 			tso = 0;
13184 #ifdef INET6
13185 		if (MHLEN < hdrlen + max_linkhdr)
13186 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13187 		else
13188 #endif
13189 			m = m_gethdr(M_NOWAIT, MT_DATA);
13190 
13191 		if (m == NULL) {
13192 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13193 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13194 			SOCKBUF_UNLOCK(sb);
13195 			error = ENOBUFS;
13196 			sack_rxmit = 0;
13197 			goto out;
13198 		}
13199 		m->m_data += max_linkhdr;
13200 		m->m_len = hdrlen;
13201 		/*
13202 		 * Start the m_copy functions from the closest mbuf to the
13203 		 * sb_offset in the socket buffer chain.
13204 		 */
13205 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13206 #ifdef BBR_INVARIANTS
13207 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13208 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13209 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13210 				    doing_retran_from,
13211 				    picked_up_retran,
13212 				    doing_tlp);
13213 
13214 #endif
13215 			/*
13216 			 * In this messed up situation we have two choices,
13217 			 * a) pretend the send worked, and just start timers
13218 			 * and what not (not good since that may lead us
13219 			 * back here a lot). <or> b) Send the lowest segment
13220 			 * in the map. <or> c) Drop the connection. Lets do
13221 			 * <b> which if it continues to happen will lead to
13222 			 * <c> via timeouts.
13223 			 */
13224 			BBR_STAT_INC(bbr_offset_recovery);
13225 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13226 			sb_offset = 0;
13227 			if (rsm == NULL) {
13228 				sack_rxmit = 0;
13229 				len = sbavail(sb);
13230 			} else {
13231 				sack_rxmit = 1;
13232 				if (rsm->r_start != tp->snd_una) {
13233 					/*
13234 					 * Things are really messed up, <c>
13235 					 * is the only thing to do.
13236 					 */
13237 					BBR_STAT_INC(bbr_offset_drop);
13238 					SOCKBUF_UNLOCK(sb);
13239 					(void)m_free(m);
13240 					return (-EFAULT); /* tcp_drop() */
13241 				}
13242 				len = rsm->r_end - rsm->r_start;
13243 			}
13244 			if (len > sbavail(sb))
13245 				len = sbavail(sb);
13246 			if (len > maxseg)
13247 				len = maxseg;
13248 		}
13249 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13250 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13251 			m_copydata(mb, moff, (int)len,
13252 			    mtod(m, caddr_t)+hdrlen);
13253 			if (rsm == NULL)
13254 				sbsndptr_adv(sb, mb, len);
13255 			m->m_len += len;
13256 		} else {
13257 			struct sockbuf *msb;
13258 
13259 			if (rsm)
13260 				msb = NULL;
13261 			else
13262 				msb = sb;
13263 #ifdef BBR_INVARIANTS
13264 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13265 				if (rsm) {
13266 					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 ",
13267 					    tp, bbr, len, moff,
13268 					    sbavail(sb), rsm,
13269 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13270 					    doing_retran_from,
13271 					    picked_up_retran,
13272 					    doing_tlp, sack_rxmit);
13273 				} else {
13274 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13275 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13276 				}
13277 			}
13278 #endif
13279 			orig_len = len;
13280 			m->m_next = tcp_m_copym(
13281 				mb, moff, &len,
13282 				if_hw_tsomaxsegcount,
13283 				if_hw_tsomaxsegsize, msb,
13284 				((rsm == NULL) ? hw_tls : 0)
13285 #ifdef NETFLIX_COPY_ARGS
13286 				, &filled_all
13287 #endif
13288 				);
13289 			if (len <= maxseg) {
13290 				/*
13291 				 * Must have ran out of mbufs for the copy
13292 				 * shorten it to no longer need tso. Lets
13293 				 * not put on sendalot since we are low on
13294 				 * mbufs.
13295 				 */
13296 				tso = 0;
13297 			}
13298 			if (m->m_next == NULL) {
13299 				SOCKBUF_UNLOCK(sb);
13300 				(void)m_free(m);
13301 				error = ENOBUFS;
13302 				sack_rxmit = 0;
13303 				goto out;
13304 			}
13305 		}
13306 #ifdef BBR_INVARIANTS
13307 		if (tso && len < maxseg) {
13308 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13309 			    tp, len, maxseg);
13310 		}
13311 		if (tso && if_hw_tsomaxsegcount) {
13312 			int32_t seg_cnt = 0;
13313 			struct mbuf *foo;
13314 
13315 			foo = m;
13316 			while (foo) {
13317 				seg_cnt++;
13318 				foo = foo->m_next;
13319 			}
13320 			if (seg_cnt > if_hw_tsomaxsegcount) {
13321 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13322 			}
13323 		}
13324 #endif
13325 		/*
13326 		 * If we're sending everything we've got, set PUSH. (This
13327 		 * will keep happy those implementations which only give
13328 		 * data to the user when a buffer fills or a PUSH comes in.)
13329 		 */
13330 		if (sb_offset + len == sbused(sb) &&
13331 		    sbused(sb) &&
13332 		    !(flags & TH_SYN)) {
13333 			flags |= TH_PUSH;
13334 		}
13335 		SOCKBUF_UNLOCK(sb);
13336 	} else {
13337 		SOCKBUF_UNLOCK(sb);
13338 		if (tp->t_flags & TF_ACKNOW)
13339 			KMOD_TCPSTAT_INC(tcps_sndacks);
13340 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13341 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13342 		else
13343 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13344 
13345 		m = m_gethdr(M_NOWAIT, MT_DATA);
13346 		if (m == NULL) {
13347 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13348 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13349 			error = ENOBUFS;
13350 			/* Fudge the send time since we could not send */
13351 			sack_rxmit = 0;
13352 			goto out;
13353 		}
13354 #ifdef INET6
13355 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13356 		    MHLEN >= hdrlen) {
13357 			M_ALIGN(m, hdrlen);
13358 		} else
13359 #endif
13360 			m->m_data += max_linkhdr;
13361 		m->m_len = hdrlen;
13362 	}
13363 	SOCKBUF_UNLOCK_ASSERT(sb);
13364 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13365 #ifdef MAC
13366 	mac_inpcb_create_mbuf(inp, m);
13367 #endif
13368 #ifdef INET6
13369 	if (isipv6) {
13370 		ip6 = mtod(m, struct ip6_hdr *);
13371 		if (tp->t_port) {
13372 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13373 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13374 			udp->uh_dport = tp->t_port;
13375 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13376 			udp->uh_ulen = htons(ulen);
13377 			th = (struct tcphdr *)(udp + 1);
13378 		} else {
13379 			th = (struct tcphdr *)(ip6 + 1);
13380 		}
13381 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13382 	} else
13383 #endif				/* INET6 */
13384 	{
13385 		ip = mtod(m, struct ip *);
13386 #ifdef TCPDEBUG
13387 		ipov = (struct ipovly *)ip;
13388 #endif
13389 		if (tp->t_port) {
13390 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13391 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13392 			udp->uh_dport = tp->t_port;
13393 			ulen = hdrlen + len - sizeof(struct ip);
13394 			udp->uh_ulen = htons(ulen);
13395 			th = (struct tcphdr *)(udp + 1);
13396 		} else {
13397 			th = (struct tcphdr *)(ip + 1);
13398 		}
13399 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13400 	}
13401 	/*
13402 	 * If we are doing retransmissions, then snd_nxt will not reflect
13403 	 * the first unsent octet.  For ACK only packets, we do not want the
13404 	 * sequence number of the retransmitted packet, we want the sequence
13405 	 * number of the next unsent octet.  So, if there is no data (and no
13406 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13407 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13408 	 * one byte beyond the right edge of the window, so use snd_nxt in
13409 	 * that case, since we know we aren't doing a retransmission.
13410 	 * (retransmit and persist are mutually exclusive...)
13411 	 */
13412 	if (sack_rxmit == 0) {
13413 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13414 			/* New data (including new persists) */
13415 			th->th_seq = htonl(tp->snd_max);
13416 			bbr_seq = tp->snd_max;
13417 		} else if (flags & TH_SYN) {
13418 			/* Syn's always send from iss */
13419 			th->th_seq = htonl(tp->iss);
13420 			bbr_seq = tp->iss;
13421 		} else if (flags & TH_FIN) {
13422 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13423 				/*
13424 				 * If we sent the fin already its 1 minus
13425 				 * snd_max
13426 				 */
13427 				th->th_seq = (htonl(tp->snd_max - 1));
13428 				bbr_seq = (tp->snd_max - 1);
13429 			} else {
13430 				/* First time FIN use snd_max */
13431 				th->th_seq = htonl(tp->snd_max);
13432 				bbr_seq = tp->snd_max;
13433 			}
13434 		} else {
13435 			/*
13436 			 * len == 0 and not persist we use snd_max, sending
13437 			 * an ack unless we have sent the fin then its 1
13438 			 * minus.
13439 			 */
13440 			/*
13441 			 * XXXRRS Question if we are in persists and we have
13442 			 * nothing outstanding to send and we have not sent
13443 			 * a FIN, we will send an ACK. In such a case it
13444 			 * might be better to send (tp->snd_una - 1) which
13445 			 * would force the peer to ack.
13446 			 */
13447 			if (tp->t_flags & TF_SENTFIN) {
13448 				th->th_seq = htonl(tp->snd_max - 1);
13449 				bbr_seq = (tp->snd_max - 1);
13450 			} else {
13451 				th->th_seq = htonl(tp->snd_max);
13452 				bbr_seq = tp->snd_max;
13453 			}
13454 		}
13455 	} else {
13456 		/* All retransmits use the rsm to guide the send */
13457 		th->th_seq = htonl(rsm->r_start);
13458 		bbr_seq = rsm->r_start;
13459 	}
13460 	th->th_ack = htonl(tp->rcv_nxt);
13461 	if (optlen) {
13462 		bcopy(opt, th + 1, optlen);
13463 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13464 	}
13465 	th->th_flags = flags;
13466 	/*
13467 	 * Calculate receive window.  Don't shrink window, but avoid silly
13468 	 * window syndrome.
13469 	 */
13470 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13471 				  recwin < maxseg)))
13472 		recwin = 0;
13473 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13474 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13475 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13476 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13477 		recwin = TCP_MAXWIN << tp->rcv_scale;
13478 
13479 	/*
13480 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13481 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13482 	 * handled in syncache.
13483 	 */
13484 	if (flags & TH_SYN)
13485 		th->th_win = htons((u_short)
13486 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13487 	else {
13488 		/* Avoid shrinking window with window scaling. */
13489 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13490 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13491 	}
13492 	/*
13493 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13494 	 * window.  This may cause the remote transmitter to stall.  This
13495 	 * flag tells soreceive() to disable delayed acknowledgements when
13496 	 * draining the buffer.  This can occur if the receiver is
13497 	 * attempting to read more data than can be buffered prior to
13498 	 * transmitting on the connection.
13499 	 */
13500 	if (th->th_win == 0) {
13501 		tp->t_sndzerowin++;
13502 		tp->t_flags |= TF_RXWIN0SENT;
13503 	} else
13504 		tp->t_flags &= ~TF_RXWIN0SENT;
13505 	/*
13506 	 * We don't support urgent data, but drag along
13507 	 * the pointer in case of a stack switch.
13508 	 */
13509 	tp->snd_up = tp->snd_una;
13510 
13511 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13512 	if (to.to_flags & TOF_SIGNATURE) {
13513 		/*
13514 		 * Calculate MD5 signature and put it into the place
13515 		 * determined before. NOTE: since TCP options buffer doesn't
13516 		 * point into mbuf's data, calculate offset and use it.
13517 		 */
13518 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13519 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13520 			/*
13521 			 * Do not send segment if the calculation of MD5
13522 			 * digest has failed.
13523 			 */
13524 			goto out;
13525 		}
13526 	}
13527 #endif
13528 
13529 	/*
13530 	 * Put TCP length in extended header, and then checksum extended
13531 	 * header and data.
13532 	 */
13533 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13534 #ifdef INET6
13535 	if (isipv6) {
13536 		/*
13537 		 * ip6_plen is not need to be filled now, and will be filled
13538 		 * in ip6_output.
13539 		 */
13540 		if (tp->t_port) {
13541 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13542 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13543 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13544 			th->th_sum = htons(0);
13545 			UDPSTAT_INC(udps_opackets);
13546 		} else {
13547 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13548 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13549 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13550 			    optlen + len, IPPROTO_TCP, 0);
13551 		}
13552 	}
13553 #endif
13554 #if defined(INET6) && defined(INET)
13555 	else
13556 #endif
13557 #ifdef INET
13558 	{
13559 		if (tp->t_port) {
13560 			m->m_pkthdr.csum_flags = CSUM_UDP;
13561 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13562 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13563 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13564 			th->th_sum = htons(0);
13565 			UDPSTAT_INC(udps_opackets);
13566 		} else {
13567 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13568 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13569 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13570 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13571 			    IPPROTO_TCP + len + optlen));
13572 		}
13573 		/* IP version must be set here for ipv4/ipv6 checking later */
13574 		KASSERT(ip->ip_v == IPVERSION,
13575 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13576 	}
13577 #endif
13578 
13579 	/*
13580 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13581 	 * header checksum is always provided. XXX: Fixme: This is currently
13582 	 * not the case for IPv6.
13583 	 */
13584 	if (tso) {
13585 		KASSERT(len > maxseg,
13586 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13587 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13588 		csum_flags |= CSUM_TSO;
13589 		m->m_pkthdr.tso_segsz = maxseg;
13590 	}
13591 	KASSERT(len + hdrlen == m_length(m, NULL),
13592 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13593 	    __func__, len, hdrlen, m_length(m, NULL)));
13594 
13595 #ifdef TCP_HHOOK
13596 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13597 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13598 #endif
13599 #ifdef TCPDEBUG
13600 	/*
13601 	 * Trace.
13602 	 */
13603 	if (so->so_options & SO_DEBUG) {
13604 		u_short save = 0;
13605 
13606 #ifdef INET6
13607 		if (!isipv6)
13608 #endif
13609 		{
13610 			save = ipov->ih_len;
13611 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13612 			      * (th->th_off << 2) */ );
13613 		}
13614 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13615 #ifdef INET6
13616 		if (!isipv6)
13617 #endif
13618 			ipov->ih_len = save;
13619 	}
13620 #endif				/* TCPDEBUG */
13621 
13622 	/* Log to the black box */
13623 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13624 		union tcp_log_stackspecific log;
13625 
13626 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13627 		/* Record info on type of transmission */
13628 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13629 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13630 		log.u_bbr.flex3 = maxseg;
13631 		log.u_bbr.flex4 = delay_calc;
13632 		/* Encode filled_all into the upper flex5 bit */
13633 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13634 		log.u_bbr.flex5 <<= 1;
13635 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13636 		log.u_bbr.flex5 <<= 29;
13637 		if (filled_all)
13638 			log.u_bbr.flex5 |= 0x80000000;
13639 		log.u_bbr.flex5 |= tp->t_maxseg;
13640 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13641 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13642 		/* lets poke in the low and the high here for debugging */
13643 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13644 		if (rsm || sack_rxmit) {
13645 			if (doing_tlp)
13646 				log.u_bbr.flex8 = 2;
13647 			else
13648 				log.u_bbr.flex8 = 1;
13649 		} else {
13650 			log.u_bbr.flex8 = 0;
13651 		}
13652 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13653 		    len, &log, false, NULL, NULL, 0, tv);
13654 	} else {
13655 		lgb = NULL;
13656 	}
13657 	/*
13658 	 * Fill in IP length and desired time to live and send to IP level.
13659 	 * There should be a better way to handle ttl and tos; we could keep
13660 	 * them in the template, but need a way to checksum without them.
13661 	 */
13662 	/*
13663 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13664 	 * because in6_cksum() need it.
13665 	 */
13666 #ifdef INET6
13667 	if (isipv6) {
13668 		/*
13669 		 * we separately set hoplimit for every segment, since the
13670 		 * user might want to change the value via setsockopt. Also,
13671 		 * desired default hop limit might be changed via Neighbor
13672 		 * Discovery.
13673 		 */
13674 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13675 
13676 		/*
13677 		 * Set the packet size here for the benefit of DTrace
13678 		 * probes. ip6_output() will set it properly; it's supposed
13679 		 * to include the option header lengths as well.
13680 		 */
13681 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13682 
13683 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13684 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13685 		else
13686 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13687 
13688 		if (tp->t_state == TCPS_SYN_SENT)
13689 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13690 
13691 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13692 		/* TODO: IPv6 IP6TOS_ECT bit on */
13693 		error = ip6_output(m, inp->in6p_outputopts,
13694 		    &inp->inp_route6,
13695 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13696 		    NULL, NULL, inp);
13697 
13698 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13699 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13700 	}
13701 #endif				/* INET6 */
13702 #if defined(INET) && defined(INET6)
13703 	else
13704 #endif
13705 #ifdef INET
13706 	{
13707 		ip->ip_len = htons(m->m_pkthdr.len);
13708 #ifdef INET6
13709 		if (isipv6)
13710 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13711 #endif				/* INET6 */
13712 		/*
13713 		 * If we do path MTU discovery, then we set DF on every
13714 		 * packet. This might not be the best thing to do according
13715 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13716 		 * the problem so it affects only the first tcp connection
13717 		 * with a host.
13718 		 *
13719 		 * NB: Don't set DF on small MTU/MSS to have a safe
13720 		 * fallback.
13721 		 */
13722 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13723 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13724 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13725 				ip->ip_off |= htons(IP_DF);
13726 			}
13727 		} else {
13728 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13729 		}
13730 
13731 		if (tp->t_state == TCPS_SYN_SENT)
13732 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13733 
13734 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13735 
13736 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13737 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13738 		    inp);
13739 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13740 			mtu = inp->inp_route.ro_nh->nh_mtu;
13741 	}
13742 #endif				/* INET */
13743 out:
13744 
13745 	if (lgb) {
13746 		lgb->tlb_errno = error;
13747 		lgb = NULL;
13748 	}
13749 	/*
13750 	 * In transmit state, time the transmission and arrange for the
13751 	 * retransmit.  In persist state, just set snd_max.
13752 	 */
13753 	if (error == 0) {
13754 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13755 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13756 		    (tp->t_flags & TF_SACK_PERMIT) &&
13757 		    tp->rcv_numsacks > 0)
13758 			tcp_clean_dsack_blocks(tp);
13759 		/* We sent an ack clear the bbr_segs_rcvd count */
13760 		bbr->output_error_seen = 0;
13761 		bbr->oerror_cnt = 0;
13762 		bbr->bbr_segs_rcvd = 0;
13763 		if (len == 0)
13764 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13765 		/* Do accounting for new sends */
13766 		if ((len > 0) && (rsm == NULL)) {
13767 			int idx;
13768 			if (tp->snd_una == tp->snd_max) {
13769 				/*
13770 				 * Special case to match google, when
13771 				 * nothing is in flight the delivered
13772 				 * time does get updated to the current
13773 				 * time (see tcp_rate_bsd.c).
13774 				 */
13775 				bbr->r_ctl.rc_del_time = cts;
13776 			}
13777 			if (len >= maxseg) {
13778 				idx = (len / maxseg) + 3;
13779 				if (idx >= TCP_MSS_ACCT_ATIMER)
13780 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13781 				else
13782 					counter_u64_add(bbr_out_size[idx], 1);
13783 			} else {
13784 				/* smaller than a MSS */
13785 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13786 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13787 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13788 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13789 			}
13790 		}
13791 	}
13792 	abandon = 0;
13793 	/*
13794 	 * We must do the send accounting before we log the output,
13795 	 * otherwise the state of the rsm could change and we account to the
13796 	 * wrong bucket.
13797 	 */
13798 	if (len > 0) {
13799 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13800 		if (error == 0) {
13801 			if (tp->snd_una == tp->snd_max)
13802 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13803 		}
13804 	}
13805 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13806 	    cts, mb, &abandon, rsm, 0, sb);
13807 	if (abandon) {
13808 		/*
13809 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13810 		 * sent we should hit this condition.
13811 		 */
13812 		return (0);
13813 	}
13814 	if (bbr->rc_in_persist == 0) {
13815 		/*
13816 		 * Advance snd_nxt over sequence space of this segment.
13817 		 */
13818 		if (error)
13819 			/* We don't log or do anything with errors */
13820 			goto skip_upd;
13821 
13822 		if (tp->snd_una == tp->snd_max &&
13823 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13824 			/*
13825 			 * Update the time we just added data since none was
13826 			 * outstanding.
13827 			 */
13828 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13829 			bbr->rc_tp->t_acktime  = ticks;
13830 		}
13831 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13832 			if (flags & TH_SYN) {
13833 				/*
13834 				 * Smack the snd_max to iss + 1
13835 				 * if its a FO we will add len below.
13836 				 */
13837 				tp->snd_max = tp->iss + 1;
13838 			}
13839 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13840 				tp->snd_max++;
13841 				tp->t_flags |= TF_SENTFIN;
13842 			}
13843 		}
13844 		if (sack_rxmit == 0)
13845 			tp->snd_max += len;
13846 skip_upd:
13847 		if ((error == 0) && len)
13848 			tot_len += len;
13849 	} else {
13850 		/* Persists case */
13851 		int32_t xlen = len;
13852 
13853 		if (error)
13854 			goto nomore;
13855 
13856 		if (flags & TH_SYN)
13857 			++xlen;
13858 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13859 			++xlen;
13860 			tp->t_flags |= TF_SENTFIN;
13861 		}
13862 		if (xlen && (tp->snd_una == tp->snd_max)) {
13863 			/*
13864 			 * Update the time we just added data since none was
13865 			 * outstanding.
13866 			 */
13867 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13868 			bbr->rc_tp->t_acktime = ticks;
13869 		}
13870 		if (sack_rxmit == 0)
13871 			tp->snd_max += xlen;
13872 		tot_len += (len + optlen + ipoptlen);
13873 	}
13874 nomore:
13875 	if (error) {
13876 		/*
13877 		 * Failures do not advance the seq counter above. For the
13878 		 * case of ENOBUFS we will fall out and become ack-clocked.
13879 		 * capping the cwnd at the current flight.
13880 		 * Everything else will just have to retransmit with the timer
13881 		 * (no pacer).
13882 		 */
13883 		SOCKBUF_UNLOCK_ASSERT(sb);
13884 		BBR_STAT_INC(bbr_saw_oerr);
13885 		/* Clear all delay/early tracks */
13886 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13887 		bbr->r_ctl.rc_agg_early = 0;
13888 		bbr->r_agg_early_set = 0;
13889 		bbr->output_error_seen = 1;
13890 		if (bbr->oerror_cnt < 0xf)
13891 			bbr->oerror_cnt++;
13892 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13893 			/* drop the session */
13894 			return (-ENETDOWN);
13895 		}
13896 		switch (error) {
13897 		case ENOBUFS:
13898 			/*
13899 			 * Make this guy have to get ack's to send
13900 			 * more but lets make sure we don't
13901 			 * slam him below a T-O (1MSS).
13902 			 */
13903 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13904 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13905 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13906 				if (tp->snd_cwnd < maxseg)
13907 					tp->snd_cwnd = maxseg;
13908 			}
13909 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13910 			BBR_STAT_INC(bbr_saw_enobuf);
13911 			if (bbr->bbr_hdrw_pacing)
13912 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13913 			else
13914 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13915 			/*
13916 			 * Here even in the enobuf's case we want to do our
13917 			 * state update. The reason being we may have been
13918 			 * called by the input function. If so we have had
13919 			 * things change.
13920 			 */
13921 			error = 0;
13922 			goto enobufs;
13923 		case EMSGSIZE:
13924 			/*
13925 			 * For some reason the interface we used initially
13926 			 * to send segments changed to another or lowered
13927 			 * its MTU. If TSO was active we either got an
13928 			 * interface without TSO capabilits or TSO was
13929 			 * turned off. If we obtained mtu from ip_output()
13930 			 * then update it and try again.
13931 			 */
13932 			/* Turn on tracing (or try to) */
13933 			{
13934 				int old_maxseg;
13935 
13936 				old_maxseg = tp->t_maxseg;
13937 				BBR_STAT_INC(bbr_saw_emsgsiz);
13938 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13939 				if (mtu != 0)
13940 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13941 				if (old_maxseg <= tp->t_maxseg) {
13942 					/* Huh it did not shrink? */
13943 					tp->t_maxseg = old_maxseg - 40;
13944 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13945 				}
13946 				/*
13947 				 * Nuke all other things that can interfere
13948 				 * with slot
13949 				 */
13950 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13951 					slot = bbr_get_pacing_delay(bbr,
13952 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13953 					    (tot_len + len), cts, 0);
13954 					if (slot < bbr_error_base_paceout)
13955 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13956 				} else
13957 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13958 				bbr->rc_output_starts_timer = 1;
13959 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13960 				    tot_len);
13961 				return (error);
13962 			}
13963 		case EPERM:
13964 			tp->t_softerror = error;
13965 			/* Fall through */
13966 		case EHOSTDOWN:
13967 		case EHOSTUNREACH:
13968 		case ENETDOWN:
13969 		case ENETUNREACH:
13970 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13971 				tp->t_softerror = error;
13972 			}
13973 			/* FALLTHROUGH */
13974 		default:
13975 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13976 			bbr->rc_output_starts_timer = 1;
13977 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13978 			return (error);
13979 		}
13980 #ifdef STATS
13981 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13982 		    len &&
13983 		    (rsm == NULL) &&
13984 	    (bbr->rc_in_persist == 0)) {
13985 		tp->gput_seq = bbr_seq;
13986 		tp->gput_ack = bbr_seq +
13987 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13988 		tp->gput_ts = cts;
13989 		tp->t_flags |= TF_GPUTINPROG;
13990 #endif
13991 	}
13992 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13993 	if ((bbr->bbr_hdw_pace_ena) &&
13994 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13995 	    (bbr->rc_past_init_win) &&
13996 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13997 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13998 	    (inp->inp_route.ro_nh &&
13999 	     inp->inp_route.ro_nh->nh_ifp)) {
14000 		/*
14001 		 * We are past the initial window and
14002 		 * have at least one measurement so we
14003 		 * could use hardware pacing if its available.
14004 		 * We have an interface and we have not attempted
14005 		 * to setup hardware pacing, lets try to now.
14006 		 */
14007 		uint64_t rate_wanted;
14008 		int err = 0;
14009 
14010 		rate_wanted = bbr_get_hardware_rate(bbr);
14011 		bbr->bbr_attempt_hdwr_pace = 1;
14012 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
14013 						      inp->inp_route.ro_nh->nh_ifp,
14014 						      rate_wanted,
14015 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
14016 						      &err, NULL);
14017 		if (bbr->r_ctl.crte) {
14018 			bbr_type_log_hdwr_pacing(bbr,
14019 						 bbr->r_ctl.crte->ptbl->rs_ifp,
14020 						 rate_wanted,
14021 						 bbr->r_ctl.crte->rate,
14022 						 __LINE__, cts, err);
14023 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14024 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14025 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
14026 			bbr->bbr_hdrw_pacing = 1;
14027 			/* Now what is our gain status? */
14028 			if (bbr->r_ctl.crte->rate < rate_wanted) {
14029 				/* We have a problem */
14030 				bbr_setup_less_of_rate(bbr, cts,
14031 						       bbr->r_ctl.crte->rate, rate_wanted);
14032 			} else {
14033 				/* We are good */
14034 				bbr->gain_is_limited = 0;
14035 				bbr->skip_gain = 0;
14036 			}
14037 			tcp_bbr_tso_size_check(bbr, cts);
14038 		} else {
14039 			bbr_type_log_hdwr_pacing(bbr,
14040 						 inp->inp_route.ro_nh->nh_ifp,
14041 						 rate_wanted,
14042 						 0,
14043 						 __LINE__, cts, err);
14044 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14045 		}
14046 	}
14047 	if (bbr->bbr_hdrw_pacing) {
14048 		/*
14049 		 * Worry about cases where the route
14050 		 * changes or something happened that we
14051 		 * lost our hardware pacing possibly during
14052 		 * the last ip_output call.
14053 		 */
14054 		if (inp->inp_snd_tag == NULL) {
14055 			/* A change during ip output disabled hw pacing? */
14056 			bbr->bbr_hdrw_pacing = 0;
14057 		} else if ((inp->inp_route.ro_nh == NULL) ||
14058 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
14059 			/*
14060 			 * We had an interface or route change,
14061 			 * detach from the current hdwr pacing
14062 			 * and setup to re-attempt next go
14063 			 * round.
14064 			 */
14065 			bbr->bbr_hdrw_pacing = 0;
14066 			bbr->bbr_attempt_hdwr_pace = 0;
14067 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14068 			tcp_bbr_tso_size_check(bbr, cts);
14069 		}
14070 	}
14071 	/*
14072 	 * Data sent (as far as we can tell). If this advertises a larger
14073 	 * window than any other segment, then remember the size of the
14074 	 * advertised window. Any pending ACK has now been sent.
14075 	 */
14076 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14077 		tp->rcv_adv = tp->rcv_nxt + recwin;
14078 
14079 	tp->last_ack_sent = tp->rcv_nxt;
14080 	if ((error == 0) &&
14081 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14082 	    (doing_tlp == 0) &&
14083 	    (tso == 0) &&
14084 	    (len > 0) &&
14085 	    ((flags & TH_RST) == 0) &&
14086 	    ((flags & TH_SYN) == 0) &&
14087 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14088 	    (bbr->rc_in_persist == 0) &&
14089 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14090 		/*
14091 		 * For non-tso we need to goto again until we have sent out
14092 		 * enough data to match what we are hptsi out every hptsi
14093 		 * interval.
14094 		 */
14095 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14096 			/* Make sure snd_nxt is drug up */
14097 			tp->snd_nxt = tp->snd_max;
14098 		}
14099 		if (rsm != NULL) {
14100 			rsm = NULL;
14101 			goto skip_again;
14102 		}
14103 		rsm = NULL;
14104 		sack_rxmit = 0;
14105 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14106 		goto again;
14107 	}
14108 skip_again:
14109 	if ((error == 0) && (flags & TH_FIN))
14110 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14111 	if ((error == 0) && (flags & TH_RST))
14112 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14113 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14114 		/*
14115 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14116 		 * what we have sent so far
14117 		 */
14118 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14119 		if (bbr->rc_no_pacing)
14120 			slot = 0;
14121 	}
14122 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14123 enobufs:
14124 	if (bbr->rc_use_google == 0)
14125 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14126 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14127 							bbr->r_ctl.rc_lost_bytes)));
14128 	bbr->rc_output_starts_timer = 1;
14129 	if (bbr->bbr_use_rack_cheat &&
14130 	    (more_to_rxt ||
14131 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14132 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14133 		if (slot > 1000)
14134 			slot = 1000;
14135 	}
14136 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14137 		/*
14138 		 * We don't change the tso size until some number of sends
14139 		 * to give the hardware commands time to get down
14140 		 * to the interface.
14141 		 */
14142 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14143 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14144 			bbr->hw_pacing_set = 1;
14145 			tcp_bbr_tso_size_check(bbr, cts);
14146 		}
14147 	}
14148 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14149 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14150 		/* Make sure snd_nxt is drug up */
14151 		tp->snd_nxt = tp->snd_max;
14152 	}
14153 	return (error);
14154 
14155 }
14156 
14157 /*
14158  * See bbr_output_wtime() for return values.
14159  */
14160 static int
14161 bbr_output(struct tcpcb *tp)
14162 {
14163 	int32_t ret;
14164 	struct timeval tv;
14165 	struct tcp_bbr *bbr;
14166 
14167 	NET_EPOCH_ASSERT();
14168 
14169 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14170 	INP_WLOCK_ASSERT(tp->t_inpcb);
14171 	(void)tcp_get_usecs(&tv);
14172 	ret = bbr_output_wtime(tp, &tv);
14173 	return (ret);
14174 }
14175 
14176 static void
14177 bbr_mtu_chg(struct tcpcb *tp)
14178 {
14179 	struct tcp_bbr *bbr;
14180 	struct bbr_sendmap *rsm, *frsm = NULL;
14181 	uint32_t maxseg;
14182 
14183 	/*
14184 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14185 	 * over the current size as SACK_PASS so a retransmit will occur.
14186 	 */
14187 
14188 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14189 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14190 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14191 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14192 		/* Don't mess with ones acked (by sack?) */
14193 		if (rsm->r_flags & BBR_ACKED)
14194 			continue;
14195 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14196 			/*
14197 			 * We mark sack-passed on all the previous large
14198 			 * sends we did. This will force them to retransmit.
14199 			 */
14200 			rsm->r_flags |= BBR_SACK_PASSED;
14201 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14202 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14203 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14204 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14205 				rsm->r_flags |= BBR_MARKED_LOST;
14206 			}
14207 			if (frsm == NULL)
14208 				frsm = rsm;
14209 		}
14210 	}
14211 	if (frsm) {
14212 		bbr->r_ctl.rc_resend = frsm;
14213 	}
14214 }
14215 
14216 static int
14217 bbr_pru_options(struct tcpcb *tp, int flags)
14218 {
14219 	if (flags & PRUS_OOB)
14220 		return (EOPNOTSUPP);
14221 	return (0);
14222 }
14223 
14224 struct tcp_function_block __tcp_bbr = {
14225 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14226 	.tfb_tcp_output = bbr_output,
14227 	.tfb_do_queued_segments = ctf_do_queued_segments,
14228 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14229 	.tfb_tcp_do_segment = bbr_do_segment,
14230 	.tfb_tcp_ctloutput = bbr_ctloutput,
14231 	.tfb_tcp_fb_init = bbr_init,
14232 	.tfb_tcp_fb_fini = bbr_fini,
14233 	.tfb_tcp_timer_stop_all = bbr_stopall,
14234 	.tfb_tcp_timer_activate = bbr_timer_activate,
14235 	.tfb_tcp_timer_active = bbr_timer_active,
14236 	.tfb_tcp_timer_stop = bbr_timer_stop,
14237 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14238 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14239 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14240 	.tfb_pru_options = bbr_pru_options,
14241 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14242 };
14243 
14244 /*
14245  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14246  * socket option arguments.  When it re-acquires the lock after the copy, it
14247  * has to revalidate that the connection is still valid for the socket
14248  * option.
14249  */
14250 static int
14251 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14252 		struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14253 {
14254 	struct epoch_tracker et;
14255 	int32_t error = 0, optval;
14256 
14257 	switch (sopt->sopt_level) {
14258 	case IPPROTO_IPV6:
14259 	case IPPROTO_IP:
14260 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14261 	}
14262 
14263 	switch (sopt->sopt_name) {
14264 	case TCP_RACK_PACE_MAX_SEG:
14265 	case TCP_RACK_MIN_TO:
14266 	case TCP_RACK_REORD_THRESH:
14267 	case TCP_RACK_REORD_FADE:
14268 	case TCP_RACK_TLP_THRESH:
14269 	case TCP_RACK_PKT_DELAY:
14270 	case TCP_BBR_ALGORITHM:
14271 	case TCP_BBR_TSLIMITS:
14272 	case TCP_BBR_IWINTSO:
14273 	case TCP_BBR_RECFORCE:
14274 	case TCP_BBR_STARTUP_PG:
14275 	case TCP_BBR_DRAIN_PG:
14276 	case TCP_BBR_RWND_IS_APP:
14277 	case TCP_BBR_PROBE_RTT_INT:
14278 	case TCP_BBR_PROBE_RTT_GAIN:
14279 	case TCP_BBR_PROBE_RTT_LEN:
14280 	case TCP_BBR_STARTUP_LOSS_EXIT:
14281 	case TCP_BBR_USEDEL_RATE:
14282 	case TCP_BBR_MIN_RTO:
14283 	case TCP_BBR_MAX_RTO:
14284 	case TCP_BBR_PACE_PER_SEC:
14285 	case TCP_DELACK:
14286 	case TCP_BBR_PACE_DEL_TAR:
14287 	case TCP_BBR_SEND_IWND_IN_TSO:
14288 	case TCP_BBR_EXTRA_STATE:
14289 	case TCP_BBR_UTTER_MAX_TSO:
14290 	case TCP_BBR_MIN_TOPACEOUT:
14291 	case TCP_BBR_FLOOR_MIN_TSO:
14292 	case TCP_BBR_TSTMP_RAISES:
14293 	case TCP_BBR_POLICER_DETECT:
14294 	case TCP_BBR_USE_RACK_CHEAT:
14295 	case TCP_DATA_AFTER_CLOSE:
14296 	case TCP_BBR_HDWR_PACE:
14297 	case TCP_BBR_PACE_SEG_MAX:
14298 	case TCP_BBR_PACE_SEG_MIN:
14299 	case TCP_BBR_PACE_CROSS:
14300 	case TCP_BBR_PACE_OH:
14301 #ifdef NETFLIX_PEAKRATE
14302 	case TCP_MAXPEAKRATE:
14303 #endif
14304 	case TCP_BBR_TMR_PACE_OH:
14305 	case TCP_BBR_RACK_RTT_USE:
14306 	case TCP_BBR_RETRAN_WTSO:
14307 		break;
14308 	default:
14309 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14310 		break;
14311 	}
14312 	INP_WUNLOCK(inp);
14313 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14314 	if (error)
14315 		return (error);
14316 	INP_WLOCK(inp);
14317 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14318 		INP_WUNLOCK(inp);
14319 		return (ECONNRESET);
14320 	}
14321 	tp = intotcpcb(inp);
14322 	if (tp->t_fb != &__tcp_bbr) {
14323 		INP_WUNLOCK(inp);
14324 		return (ENOPROTOOPT);
14325 	}
14326 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14327 	switch (sopt->sopt_name) {
14328 	case TCP_BBR_PACE_PER_SEC:
14329 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14330 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14331 		break;
14332 	case TCP_BBR_PACE_DEL_TAR:
14333 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14334 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14335 		break;
14336 	case TCP_BBR_PACE_SEG_MAX:
14337 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14338 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14339 		break;
14340 	case TCP_BBR_PACE_SEG_MIN:
14341 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14342 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14343 		break;
14344 	case TCP_BBR_PACE_CROSS:
14345 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14346 		bbr->r_ctl.bbr_cross_over = optval;
14347 		break;
14348 	case TCP_BBR_ALGORITHM:
14349 		BBR_OPTS_INC(tcp_bbr_algorithm);
14350 		if (optval && (bbr->rc_use_google == 0)) {
14351 			/* Turn on the google mode */
14352 			bbr_google_mode_on(bbr);
14353 			if ((optval > 3) && (optval < 500)) {
14354 				/*
14355 				 * Must be at least greater than .3%
14356 				 * and must be less than 50.0%.
14357 				 */
14358 				bbr->r_ctl.bbr_google_discount = optval;
14359 			}
14360 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14361 			/* Turn off the google mode */
14362 			bbr_google_mode_off(bbr);
14363 		}
14364 		break;
14365 	case TCP_BBR_TSLIMITS:
14366 		BBR_OPTS_INC(tcp_bbr_tslimits);
14367 		if (optval == 1)
14368 			bbr->rc_use_ts_limit = 1;
14369 		else if (optval == 0)
14370 			bbr->rc_use_ts_limit = 0;
14371 		else
14372 			error = EINVAL;
14373 		break;
14374 
14375 	case TCP_BBR_IWINTSO:
14376 		BBR_OPTS_INC(tcp_bbr_iwintso);
14377 		if ((optval >= 0) && (optval < 128)) {
14378 			uint32_t twin;
14379 
14380 			bbr->rc_init_win = optval;
14381 			twin = bbr_initial_cwnd(bbr, tp);
14382 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14383 				tp->snd_cwnd = twin;
14384 			else
14385 				error = EBUSY;
14386 		} else
14387 			error = EINVAL;
14388 		break;
14389 	case TCP_BBR_STARTUP_PG:
14390 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14391 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14392 			bbr->r_ctl.rc_startup_pg = optval;
14393 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14394 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14395 			}
14396 		} else
14397 			error = EINVAL;
14398 		break;
14399 	case TCP_BBR_DRAIN_PG:
14400 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14401 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14402 			bbr->r_ctl.rc_drain_pg = optval;
14403 		else
14404 			error = EINVAL;
14405 		break;
14406 	case TCP_BBR_PROBE_RTT_LEN:
14407 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14408 		if (optval <= 1)
14409 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14410 		else
14411 			error = EINVAL;
14412 		break;
14413 	case TCP_BBR_PROBE_RTT_GAIN:
14414 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14415 		if (optval <= BBR_UNIT)
14416 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14417 		else
14418 			error = EINVAL;
14419 		break;
14420 	case TCP_BBR_PROBE_RTT_INT:
14421 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14422 		if (optval > 1000)
14423 			bbr->r_ctl.rc_probertt_int = optval;
14424 		else
14425 			error = EINVAL;
14426 		break;
14427 	case TCP_BBR_MIN_TOPACEOUT:
14428 		BBR_OPTS_INC(tcp_bbr_topaceout);
14429 		if (optval == 0) {
14430 			bbr->no_pacing_until = 0;
14431 			bbr->rc_no_pacing = 0;
14432 		} else if (optval <= 0x00ff) {
14433 			bbr->no_pacing_until = optval;
14434 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14435 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14436 				/* Turn on no pacing */
14437 				bbr->rc_no_pacing = 1;
14438 			}
14439 		} else
14440 			error = EINVAL;
14441 		break;
14442 	case TCP_BBR_STARTUP_LOSS_EXIT:
14443 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14444 		bbr->rc_loss_exit = optval;
14445 		break;
14446 	case TCP_BBR_USEDEL_RATE:
14447 		error = EINVAL;
14448 		break;
14449 	case TCP_BBR_MIN_RTO:
14450 		BBR_OPTS_INC(tcp_bbr_min_rto);
14451 		bbr->r_ctl.rc_min_rto_ms = optval;
14452 		break;
14453 	case TCP_BBR_MAX_RTO:
14454 		BBR_OPTS_INC(tcp_bbr_max_rto);
14455 		bbr->rc_max_rto_sec = optval;
14456 		break;
14457 	case TCP_RACK_MIN_TO:
14458 		/* Minimum time between rack t-o's in ms */
14459 		BBR_OPTS_INC(tcp_rack_min_to);
14460 		bbr->r_ctl.rc_min_to = optval;
14461 		break;
14462 	case TCP_RACK_REORD_THRESH:
14463 		/* RACK reorder threshold (shift amount) */
14464 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14465 		if ((optval > 0) && (optval < 31))
14466 			bbr->r_ctl.rc_reorder_shift = optval;
14467 		else
14468 			error = EINVAL;
14469 		break;
14470 	case TCP_RACK_REORD_FADE:
14471 		/* Does reordering fade after ms time */
14472 		BBR_OPTS_INC(tcp_rack_reord_fade);
14473 		bbr->r_ctl.rc_reorder_fade = optval;
14474 		break;
14475 	case TCP_RACK_TLP_THRESH:
14476 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14477 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14478 		if (optval)
14479 			bbr->rc_tlp_threshold = optval;
14480 		else
14481 			error = EINVAL;
14482 		break;
14483 	case TCP_BBR_USE_RACK_CHEAT:
14484 		BBR_OPTS_INC(tcp_use_rackcheat);
14485 		if (bbr->rc_use_google) {
14486 			error = EINVAL;
14487 			break;
14488 		}
14489 		BBR_OPTS_INC(tcp_rack_cheat);
14490 		if (optval)
14491 			bbr->bbr_use_rack_cheat = 1;
14492 		else
14493 			bbr->bbr_use_rack_cheat = 0;
14494 		break;
14495 	case TCP_BBR_FLOOR_MIN_TSO:
14496 		BBR_OPTS_INC(tcp_utter_max_tso);
14497 		if ((optval >= 0) && (optval < 40))
14498 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14499 		else
14500 			error = EINVAL;
14501 		break;
14502 	case TCP_BBR_UTTER_MAX_TSO:
14503 		BBR_OPTS_INC(tcp_utter_max_tso);
14504 		if ((optval >= 0) && (optval < 0xffff))
14505 			bbr->r_ctl.bbr_utter_max = optval;
14506 		else
14507 			error = EINVAL;
14508 		break;
14509 
14510 	case TCP_BBR_EXTRA_STATE:
14511 		BBR_OPTS_INC(tcp_extra_state);
14512 		if (optval)
14513 			bbr->rc_use_idle_restart = 1;
14514 		else
14515 			bbr->rc_use_idle_restart = 0;
14516 		break;
14517 	case TCP_BBR_SEND_IWND_IN_TSO:
14518 		BBR_OPTS_INC(tcp_iwnd_tso);
14519 		if (optval) {
14520 			bbr->bbr_init_win_cheat = 1;
14521 			if (bbr->rc_past_init_win == 0) {
14522 				uint32_t cts;
14523 				cts = tcp_get_usecs(&bbr->rc_tv);
14524 				tcp_bbr_tso_size_check(bbr, cts);
14525 			}
14526 		} else
14527 			bbr->bbr_init_win_cheat = 0;
14528 		break;
14529 	case TCP_BBR_HDWR_PACE:
14530 		BBR_OPTS_INC(tcp_hdwr_pacing);
14531 		if (optval){
14532 			bbr->bbr_hdw_pace_ena = 1;
14533 			bbr->bbr_attempt_hdwr_pace = 0;
14534 		} else {
14535 			bbr->bbr_hdw_pace_ena = 0;
14536 #ifdef RATELIMIT
14537 			if (bbr->r_ctl.crte != NULL) {
14538 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14539 				bbr->r_ctl.crte = NULL;
14540 			}
14541 #endif
14542 		}
14543 		break;
14544 
14545 	case TCP_DELACK:
14546 		BBR_OPTS_INC(tcp_delack);
14547 		if (optval < 100) {
14548 			if (optval == 0) /* off */
14549 				tp->t_delayed_ack = 0;
14550 			else if (optval == 1) /* on which is 2 */
14551 				tp->t_delayed_ack = 2;
14552 			else /* higher than 2 and less than 100 */
14553 				tp->t_delayed_ack = optval;
14554 			if (tp->t_flags & TF_DELACK) {
14555 				tp->t_flags &= ~TF_DELACK;
14556 				tp->t_flags |= TF_ACKNOW;
14557 				NET_EPOCH_ENTER(et);
14558 				bbr_output(tp);
14559 				NET_EPOCH_EXIT(et);
14560 			}
14561 		} else
14562 			error = EINVAL;
14563 		break;
14564 	case TCP_RACK_PKT_DELAY:
14565 		/* RACK added ms i.e. rack-rtt + reord + N */
14566 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14567 		bbr->r_ctl.rc_pkt_delay = optval;
14568 		break;
14569 #ifdef NETFLIX_PEAKRATE
14570 	case TCP_MAXPEAKRATE:
14571 		BBR_OPTS_INC(tcp_maxpeak);
14572 		error = tcp_set_maxpeakrate(tp, optval);
14573 		if (!error)
14574 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14575 		break;
14576 #endif
14577 	case TCP_BBR_RETRAN_WTSO:
14578 		BBR_OPTS_INC(tcp_retran_wtso);
14579 		if (optval)
14580 			bbr->rc_resends_use_tso = 1;
14581 		else
14582 			bbr->rc_resends_use_tso = 0;
14583 		break;
14584 	case TCP_DATA_AFTER_CLOSE:
14585 		BBR_OPTS_INC(tcp_data_ac);
14586 		if (optval)
14587 			bbr->rc_allow_data_af_clo = 1;
14588 		else
14589 			bbr->rc_allow_data_af_clo = 0;
14590 		break;
14591 	case TCP_BBR_POLICER_DETECT:
14592 		BBR_OPTS_INC(tcp_policer_det);
14593 		if (bbr->rc_use_google == 0)
14594 			error = EINVAL;
14595 		else if (optval)
14596 			bbr->r_use_policer = 1;
14597 		else
14598 			bbr->r_use_policer = 0;
14599 		break;
14600 
14601 	case TCP_BBR_TSTMP_RAISES:
14602 		BBR_OPTS_INC(tcp_ts_raises);
14603 		if (optval)
14604 			bbr->ts_can_raise = 1;
14605 		else
14606 			bbr->ts_can_raise = 0;
14607 		break;
14608 	case TCP_BBR_TMR_PACE_OH:
14609 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14610 		if (bbr->rc_use_google) {
14611 			error = EINVAL;
14612 		} else {
14613 			if (optval)
14614 				bbr->r_ctl.rc_incr_tmrs = 1;
14615 			else
14616 				bbr->r_ctl.rc_incr_tmrs = 0;
14617 		}
14618 		break;
14619 	case TCP_BBR_PACE_OH:
14620 		BBR_OPTS_INC(tcp_pacing_oh);
14621 		if (bbr->rc_use_google) {
14622 			error = EINVAL;
14623 		} else {
14624 			if (optval > (BBR_INCL_TCP_OH|
14625 				      BBR_INCL_IP_OH|
14626 				      BBR_INCL_ENET_OH)) {
14627 				error = EINVAL;
14628 				break;
14629 			}
14630 			if (optval & BBR_INCL_TCP_OH)
14631 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14632 			else
14633 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14634 			if (optval & BBR_INCL_IP_OH)
14635 				bbr->r_ctl.rc_inc_ip_oh = 1;
14636 			else
14637 				bbr->r_ctl.rc_inc_ip_oh = 0;
14638 			if (optval & BBR_INCL_ENET_OH)
14639 				bbr->r_ctl.rc_inc_enet_oh = 1;
14640 			else
14641 				bbr->r_ctl.rc_inc_enet_oh = 0;
14642 		}
14643 		break;
14644 	default:
14645 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14646 		break;
14647 	}
14648 #ifdef NETFLIX_STATS
14649 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14650 #endif
14651 	INP_WUNLOCK(inp);
14652 	return (error);
14653 }
14654 
14655 /*
14656  * return 0 on success, error-num on failure
14657  */
14658 static int
14659 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14660     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14661 {
14662 	int32_t error, optval;
14663 
14664 	/*
14665 	 * Because all our options are either boolean or an int, we can just
14666 	 * pull everything into optval and then unlock and copy. If we ever
14667 	 * add a option that is not a int, then this will have quite an
14668 	 * impact to this routine.
14669 	 */
14670 	switch (sopt->sopt_name) {
14671 	case TCP_BBR_PACE_PER_SEC:
14672 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14673 		break;
14674 	case TCP_BBR_PACE_DEL_TAR:
14675 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14676 		break;
14677 	case TCP_BBR_PACE_SEG_MAX:
14678 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14679 		break;
14680 	case TCP_BBR_MIN_TOPACEOUT:
14681 		optval = bbr->no_pacing_until;
14682 		break;
14683 	case TCP_BBR_PACE_SEG_MIN:
14684 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14685 		break;
14686 	case TCP_BBR_PACE_CROSS:
14687 		optval = bbr->r_ctl.bbr_cross_over;
14688 		break;
14689 	case TCP_BBR_ALGORITHM:
14690 		optval = bbr->rc_use_google;
14691 		break;
14692 	case TCP_BBR_TSLIMITS:
14693 		optval = bbr->rc_use_ts_limit;
14694 		break;
14695 	case TCP_BBR_IWINTSO:
14696 		optval = bbr->rc_init_win;
14697 		break;
14698 	case TCP_BBR_STARTUP_PG:
14699 		optval = bbr->r_ctl.rc_startup_pg;
14700 		break;
14701 	case TCP_BBR_DRAIN_PG:
14702 		optval = bbr->r_ctl.rc_drain_pg;
14703 		break;
14704 	case TCP_BBR_PROBE_RTT_INT:
14705 		optval = bbr->r_ctl.rc_probertt_int;
14706 		break;
14707 	case TCP_BBR_PROBE_RTT_LEN:
14708 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14709 		break;
14710 	case TCP_BBR_PROBE_RTT_GAIN:
14711 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14712 		break;
14713 	case TCP_BBR_STARTUP_LOSS_EXIT:
14714 		optval = bbr->rc_loss_exit;
14715 		break;
14716 	case TCP_BBR_USEDEL_RATE:
14717 		error = EINVAL;
14718 		break;
14719 	case TCP_BBR_MIN_RTO:
14720 		optval = bbr->r_ctl.rc_min_rto_ms;
14721 		break;
14722 	case TCP_BBR_MAX_RTO:
14723 		optval = bbr->rc_max_rto_sec;
14724 		break;
14725 	case TCP_RACK_PACE_MAX_SEG:
14726 		/* Max segments in a pace */
14727 		optval = bbr->r_ctl.rc_pace_max_segs;
14728 		break;
14729 	case TCP_RACK_MIN_TO:
14730 		/* Minimum time between rack t-o's in ms */
14731 		optval = bbr->r_ctl.rc_min_to;
14732 		break;
14733 	case TCP_RACK_REORD_THRESH:
14734 		/* RACK reorder threshold (shift amount) */
14735 		optval = bbr->r_ctl.rc_reorder_shift;
14736 		break;
14737 	case TCP_RACK_REORD_FADE:
14738 		/* Does reordering fade after ms time */
14739 		optval = bbr->r_ctl.rc_reorder_fade;
14740 		break;
14741 	case TCP_BBR_USE_RACK_CHEAT:
14742 		/* Do we use the rack cheat for rxt */
14743 		optval = bbr->bbr_use_rack_cheat;
14744 		break;
14745 	case TCP_BBR_FLOOR_MIN_TSO:
14746 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14747 		break;
14748 	case TCP_BBR_UTTER_MAX_TSO:
14749 		optval = bbr->r_ctl.bbr_utter_max;
14750 		break;
14751 	case TCP_BBR_SEND_IWND_IN_TSO:
14752 		/* Do we send TSO size segments initially */
14753 		optval = bbr->bbr_init_win_cheat;
14754 		break;
14755 	case TCP_BBR_EXTRA_STATE:
14756 		optval = bbr->rc_use_idle_restart;
14757 		break;
14758 	case TCP_RACK_TLP_THRESH:
14759 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14760 		optval = bbr->rc_tlp_threshold;
14761 		break;
14762 	case TCP_RACK_PKT_DELAY:
14763 		/* RACK added ms i.e. rack-rtt + reord + N */
14764 		optval = bbr->r_ctl.rc_pkt_delay;
14765 		break;
14766 	case TCP_BBR_RETRAN_WTSO:
14767 		optval = bbr->rc_resends_use_tso;
14768 		break;
14769 	case TCP_DATA_AFTER_CLOSE:
14770 		optval = bbr->rc_allow_data_af_clo;
14771 		break;
14772 	case TCP_DELACK:
14773 		optval = tp->t_delayed_ack;
14774 		break;
14775 	case TCP_BBR_HDWR_PACE:
14776 		optval = bbr->bbr_hdw_pace_ena;
14777 		break;
14778 	case TCP_BBR_POLICER_DETECT:
14779 		optval = bbr->r_use_policer;
14780 		break;
14781 	case TCP_BBR_TSTMP_RAISES:
14782 		optval = bbr->ts_can_raise;
14783 		break;
14784 	case TCP_BBR_TMR_PACE_OH:
14785 		optval = bbr->r_ctl.rc_incr_tmrs;
14786 		break;
14787 	case TCP_BBR_PACE_OH:
14788 		optval = 0;
14789 		if (bbr->r_ctl.rc_inc_tcp_oh)
14790 			optval |= BBR_INCL_TCP_OH;
14791 		if (bbr->r_ctl.rc_inc_ip_oh)
14792 			optval |= BBR_INCL_IP_OH;
14793 		if (bbr->r_ctl.rc_inc_enet_oh)
14794 			optval |= BBR_INCL_ENET_OH;
14795 		break;
14796 	default:
14797 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14798 		break;
14799 	}
14800 	INP_WUNLOCK(inp);
14801 	error = sooptcopyout(sopt, &optval, sizeof optval);
14802 	return (error);
14803 }
14804 
14805 /*
14806  * return 0 on success, error-num on failure
14807  */
14808 static int
14809 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
14810 {
14811 	int32_t error = EINVAL;
14812 	struct tcp_bbr *bbr;
14813 
14814 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14815 	if (bbr == NULL) {
14816 		/* Huh? */
14817 		goto out;
14818 	}
14819 	if (sopt->sopt_dir == SOPT_SET) {
14820 		return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
14821 	} else if (sopt->sopt_dir == SOPT_GET) {
14822 		return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
14823 	}
14824 out:
14825 	INP_WUNLOCK(inp);
14826 	return (error);
14827 }
14828 
14829 static const char *bbr_stack_names[] = {
14830 	__XSTRING(STACKNAME),
14831 #ifdef STACKALIAS
14832 	__XSTRING(STACKALIAS),
14833 #endif
14834 };
14835 
14836 static bool bbr_mod_inited = false;
14837 
14838 static int
14839 tcp_addbbr(module_t mod, int32_t type, void *data)
14840 {
14841 	int32_t err = 0;
14842 	int num_stacks;
14843 
14844 	switch (type) {
14845 	case MOD_LOAD:
14846 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14847 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14848 		    sizeof(struct bbr_sendmap),
14849 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14850 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14851 		    sizeof(struct tcp_bbr),
14852 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14853 		sysctl_ctx_init(&bbr_sysctl_ctx);
14854 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14855 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14856 		    OID_AUTO,
14857 #ifdef STACKALIAS
14858 		    __XSTRING(STACKALIAS),
14859 #else
14860 		    __XSTRING(STACKNAME),
14861 #endif
14862 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14863 		    "");
14864 		if (bbr_sysctl_root == NULL) {
14865 			printf("Failed to add sysctl node\n");
14866 			err = EFAULT;
14867 			goto free_uma;
14868 		}
14869 		bbr_init_sysctls();
14870 		num_stacks = nitems(bbr_stack_names);
14871 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14872 		    bbr_stack_names, &num_stacks);
14873 		if (err) {
14874 			printf("Failed to register %s stack name for "
14875 			    "%s module\n", bbr_stack_names[num_stacks],
14876 			    __XSTRING(MODNAME));
14877 			sysctl_ctx_free(&bbr_sysctl_ctx);
14878 	free_uma:
14879 			uma_zdestroy(bbr_zone);
14880 			uma_zdestroy(bbr_pcb_zone);
14881 			bbr_counter_destroy();
14882 			printf("Failed to register " __XSTRING(MODNAME)
14883 			    " module err:%d\n", err);
14884 			return (err);
14885 		}
14886 		tcp_lro_reg_mbufq();
14887 		bbr_mod_inited = true;
14888 		printf(__XSTRING(MODNAME) " is now available\n");
14889 		break;
14890 	case MOD_QUIESCE:
14891 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14892 		break;
14893 	case MOD_UNLOAD:
14894 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14895 		if (err == EBUSY)
14896 			break;
14897 		if (bbr_mod_inited) {
14898 			uma_zdestroy(bbr_zone);
14899 			uma_zdestroy(bbr_pcb_zone);
14900 			sysctl_ctx_free(&bbr_sysctl_ctx);
14901 			bbr_counter_destroy();
14902 			printf(__XSTRING(MODNAME)
14903 			    " is now no longer available\n");
14904 			bbr_mod_inited = false;
14905 		}
14906 		tcp_lro_dereg_mbufq();
14907 		err = 0;
14908 		break;
14909 	default:
14910 		return (EOPNOTSUPP);
14911 	}
14912 	return (err);
14913 }
14914 
14915 static moduledata_t tcp_bbr = {
14916 	.name = __XSTRING(MODNAME),
14917 	    .evhand = tcp_addbbr,
14918 	    .priv = 0
14919 };
14920 
14921 MODULE_VERSION(MODNAME, 1);
14922 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14923 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14924